Search code examples
javaandroidfirebasefirebase-realtime-databasescreen-orientation

on rotate android screen onclick button instead of adding new items, it will delete the previous itesm


ok the app has 1 button onclick will add item to arraylist and then to firebase but when i rotate screen an click same button, instead of adding more items, will delete all items created before rotating screen then will add items again. here is my button code

conver_textview_to_string=new ArrayList<>();
      b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    conver_textview_to_string.add("123");
                    for(int i=0;i<conver_textview_to_string.size();i++){
                        myRef.setValue(conver_textview_to_string);
                    }

                }
            });

Thank you


Solution

  • On screen rotation the Activity is recreated, so in-order for you to save previous data(before screen rotation), you have to store your data/values inside onSaveInstanceState and get its value inside onRestoreInstanceState

    protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putParcelableArrayList("myText", conver_textview_to_string);
        }
    
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        conver_textview_to_string = savedInstanceState.getParcelableArrayList("myText");    
    }