简体   繁体   中英

How to use onSaveInstance method with Recyclerview

I have an App which should keep all the data displayed into Recycler when the screen is rotated. the recycler receives data from a Custom Array List. there is also a second variable used to set the Uri of the VideoView inside the adapter.

already tried onSave and onRestoreIntance. maybe I have used them wrong.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    // Variables-----------------------------------------

     recyclerView = findViewById(R.id.recyclerView);
    Button video = findViewById(R.id.video);
    Button camera = findViewById(R.id.camera);
    Button send = findViewById(R.id.send);
    final EditText editText = findViewById(R.id.editText);


    // Layout Manager------------------------------------------------

    linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    linearLayoutManager.setStackFromEnd(true);
    RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setItemAnimator(itemAnimator);


    // Adapter-----------------------------------------

        //adapter.notifyDataSetChanged();
        adapter =  new myAdapter(dati, this);
        recyclerView.setAdapter(adapter);



    // Click Listener Video button---------------------------------------- 
    video.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            startActivityForResult(intent,0);
        }
    });

    // Click Listener Camera button--------------------------------------
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
        }
    });

    // Click Listener Send button-----------------------------------------
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String string = editText.getText().toString();
            dati.add(new ModelloDati(0,string));
            adapter.notifyItemInserted(dati.size());
            editText.getText().clear();
            recyclerView.smoothScrollToPosition(dati.size());
            closeKeyboard();
        }
    });

    if(savedInstanceState != null)



linearLayoutManager.onRestoreInstanceState(
savedInstanceState.getParcelable("STATO_LISTA"));

}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable  
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
        case 0:
            try {
                Uri contentURI = data.getData();
                passUri = contentURI;
                String recordedVideoPath = getPath(contentURI);
                saveVideoToInternalStorage(recordedVideoPath);
                dati.add(new ModelloDati(2, contentURI));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());

            }catch (Throwable o){Log.i("CAM","User aborted action");}
        case 1:
            try {
                Bitmap bitmap = (Bitmap)data.getExtras().get("data");
                dati.add(new ModelloDati(1,bitmap));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());


            }catch(Throwable o){
                Log.i("CAM","User aborted action");
            }

    }


}


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

    if (saveList != null) {
        linearLayoutManager.onRestoreInstanceState(saveList);
    }
}


@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveList = linearLayoutManager.onSaveInstanceState();
    outState.putParcelable("STATO_LISTA",saveList);
}


@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if(savedInstanceState != null)
       savedInstanceState.getParcelable("STATO_LISTA");
}

}

Android offers Architecture components which helps you deal with those kind of situations. For example ViewModel

The Android framework manages the lifecycles of UI controllers, such as activities and fragments. The framework may decide to destroy or re-create a UI controller in response to certain user actions or device events that are completely out of your control.

If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. For example, your app may include a list of users in one of its activities. When the activity is re-created for a configuration change, the new activity has to re-fetch the list of users. For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps.

So basically you can hold your dataset for your adapter in your ViewModel and inside onCreate get the data and set it into your adapter.

MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
new adapter(model.getData(),this); // just for the example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM