mardi 5 mai 2015

ArrayList won't store old sting value passed through intent

My problem is that I have an intent which is sending string value to my MainActivity. I am trying to save those values in ArrayList but only the last one is displayed.

Here is my MainActivity:

  ArrayList<String> productNames= new ArrayList<String>();



public void addNewProduct(View view){
    Intent i = new Intent(this,AddProduct.class);
    startActivity(i);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState!=null){
        productNames=savedInstanceState.getStringArrayList("products");
    }
    setContentView(R.layout.activity_main);
    Bundle productData=getIntent().getExtras();
    if(productData==null){
        return;
    }
    String product=productData.getString("product");
    productNames.add(product);
    ListView productList=(ListView)findViewById(R.id.productList);
    ArrayAdapter adapter = new CustomAdapter(this,productNames);
    adapter.notifyDataSetChanged();
   productList.setAdapter(adapter);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putStringArrayList("products",productNames);
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    productNames=savedInstanceState.getStringArrayList("products");
}

}

My question is that why the producNames ArrayList is being created again?

Aucun commentaire:

Enregistrer un commentaire