Search code examples
androidandroid-activitysavestate

How to save a variable value when starting another activity


One of the activities (Activity A) I have in the application displays a list of videos as you can see in the image:

enter image description here The videos are stored in an ArrayList called videosList, when the user select a video the video is played using an embedded YouTube player in another activity B. The problem is when the user goes back from activity B (The activity with the video player) to activity A (The activity with the list of videos) the variable videosList is null so the application stops running with error.

I tried to implement the

protected void onSaveInstanceState(Bundle savedInstanceState) and the protected void onRestoreInstanceState(Bundle savedInstanceState) methods to save the activity state and some variables so when the user is back to Activity A the application can display the list of videos again, but when I try to gat the values I previously saved in onSaveInstanceState(Bundle savedInstanceState) in the public void onCreate(Bundle savedInstanceState) the savedInstanceStateis always NULL.

Here is my code:

 public class VideosCatalogActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {



    private Toolbar toolbar;
    private GridView videosGrid;
    private ArrayList<VideoEntity> videosList;

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase database;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        Log.d(TAG, " onCreate(Bundle) - Ini ");
        super.onCreate(savedInstanceState);
        //  onSaveInstanceState();

        setContentView(R.layout.videos_catalog_layout);
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        toolbar.setTitle(R.string.app_name);
        toolbar.setTitleTextColor(getResources().getColor(R.color.com_facebook_button_background_color_focused));
        mAuth = FirebaseAuth.getInstance();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                FirebaseUser user = mAuth.getCurrentUser();

            }
        };

        database = FirebaseDatabase.getInstance();
        Bundle bundle = getIntent().getExtras();

        String actividad = bundle.getString("Activity");

        if (actividad.equals("DocumentariesCategoriesActivity")) {


            videosList = bundle.getParcelableArrayList("com.app.example.VideoEntity");


updateCatalog();

            /*

            String videoId = "";


            if (!videosList.isEmpty() && !videosList.equals(null)) {

                for (VideoEntity video : videosList) {
                    DatabaseReference mRef = database.getReference().child("Videos").child(video.getId());
                    mRef.setValue(video);
                }


                videosGrid = (GridView) findViewById(R.id.videosGrid);
                MyGridViewAdapter adapter = new MyGridViewAdapter(this);
                adapter.setVideosList(videosList);
                videosGrid.setAdapter(adapter);
                videosGrid.setOnItemClickListener(this);
            } */

        }


        Log.d(TAG, " onCreate(Bundle) - Fi ");
    }






    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        Log.d(TAG, "onCreateOptionsMenu(Menu) - Ini");

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);

        Log.d(TAG, "onCreateOptionsMenu(Menu) - Fi");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {

        Log.d(TAG, "onOptionItemSelected(MenuItem) - Ini");

        switch (menuItem.getItemId()) {

            case R.id.action_logout:
                updateActivity(mAuth.getCurrentUser());

        }

        Log.d(TAG, "onOptionItemSelected(MenuItem) - Fi");
        return true;
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Log.d(TAG, " onItemClick(AdapterView<?>, View, int, long) - Ini ");

        Intent intent = new Intent(getApplicationContext(), YoutubePlayerActivity.class);
        intent.putExtra("VIDEO_ID", videosList.get(position).getId());

        startActivity(intent);

        Log.d(TAG, " onItemClick(AdapterView<?>, View, int, long) - Fi ");

    }

    protected void updateActivity(FirebaseUser user) {
        Log.d(TAG, "updateActivity(FirebaseUser) - Ini");

        mAuth.signOut();
        Intent i = new Intent(VideosCatalogActivity.this, LoginActivity.class);
        startActivity(i);


        Log.d(TAG, "updateActivity(FirebaseUser) - Fi");
    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        Log.d(TAG, "onSaveInstanceState(Bundle) - Ini");
        super.onSaveInstanceState(savedInstanceState);

        savedInstanceState.putParcelableArrayList("VIDEOS_LIST", videosList);
        savedInstanceState.putAll(savedInstanceState);

        Log.d(TAG, "onSaveInstanceState(Bundle) - Fi");
        Log.i("","onSaveInstance is executed");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        Log.d(TAG, "onRestoreInstanceState(Bundle) - Ini");
        super.onRestoreInstanceState(savedInstanceState);

        videosList = savedInstanceState.getParcelableArrayList("VIDEOS_LIST");
        updateCatalog();

        Log.i("","onRestoreInstance is executed");
        Log.d(TAG, "onRestoreInstanceState(Bundle) - Fi");
    }

    protected void updateCatalog() {

        Log.d(TAG, "updateCatalog() - Ini");

        String videoId = "";

        for (VideoEntity video : videosList) {
            DatabaseReference mRef = database.getReference().child("Videos").child(video.getId());
            mRef.setValue(video);
        }

        videosGrid = (GridView) findViewById(R.id.videosGrid);
        MyGridViewAdapter adapter = new MyGridViewAdapter(this);
        adapter.setVideosList(videosList);
        videosGrid.setAdapter(adapter);
        videosGrid.setOnItemClickListener(this);



        Log.d(TAG, "updateCatalog() - Fi");

    }


}

Any idea how can i solve this problem please ?


Solution

  • Why dont you use a SingletonData class? that stores the ArrayList and when you need to reload the ArrayList you load it from the Singleton.

    public class DataSingleton {
    
        private static DataSingleton instance = new DataSingleton();
        private DataSingleton(){    }
    
        public static DataSingleton getInstance(){  return instance;    }
        public static void setIntances(DataSingleton instance){DataSingleton.instance = instance;}
    
        private ArrayList<Videos> videosList;
    
    
        public void setArrayVideos(ArrayList<Videos> videos){
            videosList=videos;
        }
    
        public ArrayList<Videos> getArrayVideos(){
            return videosList;
        }
    }
    

    then you call the class in the activity A and set the ArrayList wherever you want.

    DataSingleton.getInstance().setArrayVideos(videosList);   
    videosList= DataSingleton.getInstance().getArrayVideos();