我试图将数据从QR扫描仪活动传递到另一个活动,并在另一个活动中显示扫描结果。当我扫描QR码时,它返回到其他活动,但当我按回它时它停止工作并给我这个错误
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { cmp=com.justinjunias.stockitem/.receiptactivity.CreateReceiptActivity (has extras) }} to activity {com.justinjunias.stockitem/com.justinjunias.stockitem.receiptactivity.CreateReceiptActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
由这条线引起的:
qrResult = extras.getString("QRItemtype");
这是我的QR扫描仪活动:
public class QRScannerActivity extends AppCompatActivity implements View.OnClickListener {
//View Objects
private String itemTypeQR;
//qr code scanner object
private IntentIntegrator qrScan;
private static final int QR_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qrscanner_activity);
//intializing scan object
qrScan = new IntentIntegrator(this);
qrScan.setOrientationLocked(false);
qrScan.initiateScan();
}
//Getting the scan results
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
//if qrcode has nothing in it
if (result.getContents() == null) {
Intent qrResult = new Intent(QRScannerActivity.this, CreateReceiptActivity.class);
itemTypeQR = result.getContents();
qrResult.putExtra("QRItemtype",itemTypeQR);
startActivity(qrResult);
finish();
} else {
//if qr contains data
try {
//converting the data to json
JSONObject obj = new JSONObject(result.getContents());
//setting values to textviews
Intent qrResult = new Intent(QRScannerActivity.this, CreateReceiptActivity.class);
itemTypeQR = obj.getString("type");
qrResult.putExtra("QRItemtype",itemTypeQR);
setResult(RESULT_OK, qrResult);
startActivityForResult(qrResult,QR_REQUEST_CODE);
finish();
} catch (JSONException e) {
e.printStackTrace();
itemTypeQR = result.getContents();
Intent qrResult = new Intent(QRScannerActivity.this,CreateReceiptActivity.class);
qrResult.putExtra("QRItemtype",itemTypeQR);
setResult(RESULT_OK, qrResult);
startActivityForResult(qrResult,QR_REQUEST_CODE);
finish();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onClick(View view) {
//initiating the qr code scan
qrScan.initiateScan();
}
}
这是我想要显示QR扫描结果的活动。
public class CreateReceiptActivity extends AppCompatActivity {
@BindView(R.id.receipt_date)
TextView date;
@BindView(R.id.receipt_invoice)
TextView invoiceNumber;
@BindView(R.id.btn_receipt_add_item)
ImageButton addItem;
@BindView(R.id.btn_receipt_print)
ImageButton printItem;
@BindView(R.id.receipt_view_recycler)
RecyclerView recyclerView;
@BindView(R.id.create_receipt_pb_loading)
ProgressBar pbloading;
private static final int QR_REQUEST_CODE = 1;
List<ListAutoComplete> autoCompleteList;
ListAutoComplete listAutoComplete;
List<ListReceiptItem> receiptItemList;
ListReceiptItem listReceiptItem;
ReceiptItemAdapter adapter;
public String itemType, itemQty, itemPrice, itemDate, itemInvoice, lastInvoice, qrResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_receipt);
ButterKnife.bind(this);
receiptItemList = new ArrayList<>();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new ReceiptItemAdapter(this, receiptItemList);
recyclerView.setAdapter(adapter);
itemInvoice = invoiceNumber.getText().toString();
itemDate = setDate(date);
date.setText(this.getString(R.string.date, setDate(date)));
printItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
pbloading.setVisibility(View.VISIBLE);
cutStock();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(CreateReceiptActivity.this);
builder.setMessage("Print Transaksi ?").setPositiveButton("Ya", dialogClickListener)
.setNegativeButton("Tidak", dialogClickListener).show();
}
});
addItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater li = CreateReceiptActivity.this.getLayoutInflater();
final View v = li.inflate(R.layout.alertdialog_create_receipt, null);
final AlertDialog.Builder builder = new AlertDialog.Builder(CreateReceiptActivity.this);
builder.setView(v);
final EditText addItemType = v.findViewById(R.id.alertdialog_receipt_type);
final EditText addItemQty = v.findViewById(R.id.alertdialog_receipt_qty);
final EditText addItemPrice = v.findViewById(R.id.alertdialog_receipt_price);
Button btnSubmit = v.findViewById(R.id.alertdialog_receipt_submit);
final AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button btnScan = v.findViewById(R.id.alertdialog_receipt_scanqr);
btnScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(CreateReceiptActivity.this, QRScannerActivity.class);
startActivityForResult(i, QR_REQUEST_CODE);
alertDialog.dismiss();
}
});
}
});
alertDialog.show();
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
itemType = addItemType.getText().toString().trim();
itemQty = addItemQty.getText().toString().trim();
itemPrice = addItemPrice.getText().toString().trim();
listReceiptItem = new ListReceiptItem(itemType, itemQty, itemPrice, "0");
receiptItemList.add(listReceiptItem);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
alertDialog.dismiss();
Toast.makeText(CreateReceiptActivity.this, "barang tertambah", Toast.LENGTH_SHORT).show();
}
});
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
} else if (data != null) {
if (requestCode == QR_REQUEST_CODE) {
Bundle extras = getIntent().getExtras();
qrResult = extras.getString("QRItemtype");
if (qrResult == null) {
Toast.makeText(this, "Scan gagal", Toast.LENGTH_SHORT).show();
} else if (!(qrResult == null)) {
Toast.makeText(this, qrResult, Toast.LENGTH_SHORT).show();
}
}
}
}
private void cutStock() {
final FirebaseFirestore db = FirebaseFirestore.getInstance();
for (ListReceiptItem listreceiptItem : receiptItemList) {
final String soldItemDate = date.getText().toString().trim();
final String soldItemInvoice = invoiceNumber.getText().toString().trim();
final String soldItemtype = listreceiptItem.getType();
final String soldItemQty = listreceiptItem.getQty();
final String soldItemPrice = listreceiptItem.getPrice();
db.collection("watchlist").whereEqualTo("type", soldItemtype)
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());
String id = document.getString("id");
String oldqty = document.getString("qty");
Integer i = Integer.parseInt(oldqty) - Integer.parseInt(soldItemQty);
String newQty = String.valueOf(i);
Map<Object, String> map = new HashMap<>();
map.put("qty", newQty);
db.collection("watchlist").document(document.getId()).set(map, SetOptions.merge());
ArrayList<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> receiptItem = new HashMap<>();
receiptItem.put("invoice", soldItemInvoice);
list.add(receiptItem);
receiptItem.put("date", soldItemDate);
list.add(receiptItem);
receiptItem.put("type", soldItemtype);
list.add(receiptItem);
receiptItem.put("qty", soldItemQty);
list.add(receiptItem);
receiptItem.put("price", soldItemPrice);
list.add(receiptItem);
final FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("sales").add(receiptItem).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(CreateReceiptActivity.this, "Berhasil mencetak transaksi", Toast.LENGTH_SHORT).show();
Integer i = Integer.parseInt(soldItemInvoice) + 1;
String newInvoice = String.valueOf(i);
invoiceNumber.setText(newInvoice);
pbloading.setVisibility(View.GONE);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(CreateReceiptActivity.this, "Gagal mencetak", Toast.LENGTH_SHORT).show();
pbloading.setVisibility(View.GONE);
}
});
}
} else {
Toast.makeText(CreateReceiptActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
Log.w(Tag.ITEM, "error getting documents", task.getException());
pbloading.setVisibility(View.GONE);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(CreateReceiptActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
pbloading.setVisibility(View.GONE);
}
});
}
}
public void getTypeList() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference documentReference = db.collection("watchlist");
documentReference.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());
String type = document.getString("type");
listAutoComplete = new ListAutoComplete(type);
autoCompleteList.add(listAutoComplete);
}
} else {
Log.w(Tag.ITEM, "error getting documents", task.getException());
}
}
});
}
public String setDate(TextView view) {
java.util.Date today = Calendar.getInstance().getTime();//getting date
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");//formating according to my need
String date = formatter.format(today);
view.setText(date);
return date;
}
}
在QRScannerActivity中,您仅在“if”条件下使用startActivity()而不是startActivityForResult()。
所以尝试使用startActivityForResult()而不是startActivity(),如下所示:
if (result.getContents() == null)
{
Intent qrResult = new Intent(QRScannerActivity.this, CreateReceiptActivity.class);
itemTypeQR = result.getContents();
qrResult.putExtra("QRItemtype",itemTypeQR);
startActivityForResult(qrResult);
finish();
}
在你的CreateReceiptActivity中尝试使用if条件,如extras!= null && extras.containsKey(“QRItemtype”),如下所示:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
} else if (data != null) {
if (requestCode == QR_REQUEST_CODE) {
Bundle extras = getIntent().getExtras();
if(extras != null && extras .containsKey("QRItemtype")){
qrResult = extras.getString("QRItemtype");
if (qrResult == null) {
Toast.makeText(this, "Scan gagal", Toast.LENGTH_SHORT).show();
} else if (!(qrResult == null)) {
Toast.makeText(this, qrResult, Toast.LENGTH_SHORT).show();
}
}
}
}
}
您正在将QRScannerActivity的bundle传递给CreateReceiptActivity,并尝试在CreateReceiptActivity的onActivityResult()中获取它,但我的建议是尝试获取“Bundle extras = getIntent()。getExtras();”在CreateReceiptActivity的onCreate()中,因为我认为你不需要CreateReceiptActivity的onActivityResult()的“Intent data”中的任何内容,如下所示:
else if (data != null) {
if (requestCode == QR_REQUEST_CODE) {
Bundle extras = data.getExtras();
}
}
但你正在使用
else if (data != null) {
if (requestCode == QR_REQUEST_CODE) {
Bundle extras = getIntent().getExtras();
}
}
所以首先要决定你想要使用哪个。谢谢