[英]Android List disappear after intent back to activity
I have a CreateReceiptActivity and also QRScan activity, after intent to QR Scan and intent back to CreateReceiptActivity. 在意图进行QR扫描并意图回到CreateReceiptActivity后,我有一个CreateReceiptActivity和QRScan活动。 The list or receipt item becomes empty again ( if I already add item to the list, after that I want to add item again using QR Scan, the item in the list becomes empty again).
列表或收据项再次变为空(如果我已经将项添加到列表中,之后我想使用QR扫描再次添加项,则列表中的项再次变为空)。 Can somebody help me with this issue ?
有人可以帮我解决这个问题吗?
here's the code 这是代码
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;
ArrayList temporaryList;
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;
}
}
};
Builder builder = new Builder(CreateReceiptActivity.this);
builder.setMessage("Print Transaksi ?").setPositiveButton("Ya", dialogClickListener)
.setNegativeButton("Tidak", dialogClickListener).show();
}
});
Bundle extras = getIntent().getExtras();
if(extras != null && extras .containsKey("QRItemtype")){
qrResult = extras.getString("QRItemtype");
if (qrResult == null) {
Toast.makeText(CreateReceiptActivity.this, "Scan gagal", Toast.LENGTH_SHORT).show();
} else if (!(qrResult == null)) {
Toast.makeText(CreateReceiptActivity.this, qrResult, Toast.LENGTH_SHORT).show();
}
}
addItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openDialog();
}
});
}
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);
}
});
}
}
@Override
protected void onResume() {
super.onResume();
openDialog();
}
private void openDialog(){
LayoutInflater li = CreateReceiptActivity.this.getLayoutInflater();
final View v = li.inflate(R.layout.alertdialog_create_receipt, null);
final Builder builder = new 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);
addItemType.setText(qrResult);
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.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();
qrResult = null;
Toast.makeText(CreateReceiptActivity.this, "barang tertambah", Toast.LENGTH_SHORT).show();
}
});
}
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;
}
}
This is my QRScan activity: 这是我的QRScan活动:
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);
startActivityForResult(qrResult,QR_REQUEST_CODE);
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();
}
}
Hi first make your ListReceiptItem implements Parcelable like below: 嗨首先让ListReceiptItem实现Parcelable,如下所示:
public class ListReceiptItem implements Parcelable {
// please keep your methods and variables here as it is
}
Don't forget to write "writeToParcel" method in your ListReceiptItem class and below is only example of "writeToParcel" method. 不要忘记在ListReceiptItem类中编写“writeToParcel”方法,下面只是“writeToParcel”方法的示例。 you have to google it if you doesn't know about Parcelable.
如果你不知道Parcelable,你必须谷歌。
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeString(this.name);
dest.writeString(this.grade);
}
Then copy paste below two classes as it is because i have just edited it where it passes list from QRScannerActivity to CreateReceiptActivity and after adding items from CreateReceiptActivity it will return that list in QRScannerActivity and we can found it in onActivityResult() of QRScannerActivity. 然后复制粘贴在两个类之下,因为我刚刚编辑它从QRScannerActivity传递列表到CreateReceiptActivity,在从CreateReceiptActivity添加项目后,它将在QRScannerActivity中返回该列表,我们可以在QRScannerActivity的onActivityResult()中找到它。 Also don't call finish() after startActivityForResult().
也不要在startActivityForResult()之后调用finish()。
QRScannerActivity
QRScannerActivity
public class QRScannerActivity extends AppCompatActivity implements View.OnClickListener {
//View Objects
private String itemTypeQR;
//qr code scanner object
private IntentIntegrator qrScan;
// newly added
List<ListReceiptItem> receiptItemList = new List<ListReceiptItem>;
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) {
if(requestCode == QR_REQUEST_CODE && resultCode == Activity.RESULT_OK){
if(data != null && data.getExtras() != null){
List<ListReceiptItem> receiptItemListNew = (List<ListReceiptItem>) bundle.getParcelable("mList");
if(receiptItemListNew != null){
receiptItemList.clear();
receiptItemList.addAll(receiptItemListNew);
}
}
}
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);
qrResult.putParcelable("mList", receiptItemList);
startActivityForResult(qrResult,QR_REQUEST_CODE);
} 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);
qrResult.putParcelable("mList", receiptItemList);
setResult(RESULT_OK, qrResult);
startActivityForResult(qrResult,QR_REQUEST_CODE);
} catch (JSONException e) {
e.printStackTrace();
itemTypeQR = result.getContents();
Intent qrResult = new Intent(QRScannerActivity.this,CreateReceiptActivity.class);
qrResult.putExtra("QRItemtype",itemTypeQR);
qrResult.putParcelable("mList", receiptItemList);
setResult(RESULT_OK, qrResult);
startActivityForResult(qrResult,QR_REQUEST_CODE);
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onClick(View view) {
//initiating the qr code scan
qrScan.initiateScan();
}
}
CreateReceiptActivity
CreateReceiptActivity
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 = new List<ListReceiptItem>;
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);
if(getIntent().getExtras() != null && getIntent().getExtras().contains("mList")){
receiptItemList.clear();
receiptItemList.addAll((List<ListReceiptItem>) getIntent().getExtras().getParcelableExtra("mList"));
}
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);
i.putParcelable("mList", receiptItemList);
startActivityForResult(i, QR_REQUEST_CODE);
}
});
}
});
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();
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.