How to capture data correctly from the list?

Asked

Viewed 41 times

0

I put the code down on onCreate and onResume, but of the problem when putting in the onResume. Whenever I return/leave the editing screen, onResume goes into action and goes through the whole list again.

Example: I add item 1, the TextView with the value, I go back to the edit screen and add item 2, calling the onResume and adds item 1 again and then adds item 2 in the sum and so on.

How can I make the sum start from the item I added to not occur this problem ?

@Override protected void onResume() { 
super.onResume(); 
TextView txtTotal = (TextView)findViewById(R.id.txtTotal); 
for(int i = 0; i < itemList.size(); i++) { 
totalItems = totalItems + itemList.get(i).getPreco(); } txtTotal.setText(String.valueOf(totalItems)); } 

I first get the bank list on onCreate, using:

realm = Realm.getDefaultInstance(); 
itemList = realm.where(Item.class).findAll();
  • Look I always instate my components in onCreate. To tell you the truth I’ve never seen anyone instantiating anywhere else, unless it’s an adapter or something

1 answer

1


If I understand your question correctly, you would like to add only the value of the new item added. The fastest solution is to just reset the price variable and add it all up again.

Override protected void onResume() { 
    super.onResume(); 

    TextView txtTotal = findViewById(R.id.txtTotal);
    totalItems = 0; // <- reiniciando var

    for (int i = 0; i < itemList.size(); i++) { 
        totalItems = totalItems + itemList.get(i).getPreco(); 
    } 

    txtTotal.setText(String.valueOf(totalItems)); 
}

The long and more correct answer: You need to call your Activity "creation/editing" waiting for a result to return, so you can add an event that is triggered when you return to the listing.

Call Activity that way:

startActivityForResult(intent, requestCode);

"requestCode" can be any integer only to identify which Activity is returning. Using the "onActivityResult" event in the list Activity it is possible to detect when returning to the list.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK && requestCode == 1) {

    }
}

The "requestCode" should be the same as the one you sent, and then you can return the desired values for the calculation within the "date" (Bundle).

I strongly recommend that you read the tutorials of the android itself:

How to generate results with an Activity

  • Thanks! It worked the first option. I will study a little more the second before implementing.

  • @Wandersonsouza Marks the answer as correct to help people with the same doubt in the future.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.