Question

ALL,

I did look around and searched on stackoverflow, but my question was not answered or I just searched incorrectly.

I have a list view which displays a text along with the button. When this button is clicked I am opening another activity with the different list passing the text from previous activity.

Now, when I press "Back" button, I am going back to "Activity1". Here I can press the button again on the same row or on the different one and I should go to the "Activity2" which needs to keep the previously put text in the "listview_Activity2" and add the newly selected text from "listview_Activity1".

I did create a custom adapters for both list views and "Activity1" works fine on the first button press. However, on the second press the application does not keep the first selected text.

Now, everywhere I look it is either adding items to list view from the same activity by pressing a button or keep the list view item state. I don't care about item state at all, and my items are coming from another activity.

Could someone please help?

Here is the code:

private static List<Product> products;

@Override
public void onCreate(Bundle savedInstance)
{
    super.onCreate( savedInstance );
    products = new ArrayList<Product>();
    Intent intent = getIntent();
    Product product = intent.getParcelableExtra( "cart_product" );
    products.add( product );
    CartLineAdapter adapter = new CartLineAdapter( this, R.layout.cart_line, products );
    setContentView( R.layout.cart );
    ListView view = (ListView) findViewById( R.id.cart_items );
    view.setAdapter( adapter );
}
Était-ce utile?

La solution

You need to have some persistence for your data. If you only want it to be kept while currently in the app then you can use static variables. Create a class that holds a static ArrayList or something similar which you will add the data to after selecting an item from the list in the first Activity. Then each time you go to the second Activity you can populate your list using the data from that static ArrayList.

Your other options are to store this data in SharedPreferences (probably not ideal for this situation but maybe) or a DB if you want it to persist if the application is closed.

Edit

For any of the options you can override onBackPressed()

@Override
public void onBackPressed()
{
    // save data here if it hasn't yet been saved
    super.onBackPressed();
}

Storage Options

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top