This question already has answers here:
How to save custom ArrayList on Android screen rotate?

(4个答案)


4年前关闭。




我有一个ArrayList,其中包含使用Volley从网上获取的自定义json对象。我希望能够在屏幕旋转时保存和还原这些对象。我还想保存并恢复屏幕旋转上的当前滚动位置。

我有一个粗略的想法,可以使用onSaveInstanceState和onRestoreInstanceState完成吗?

活动代码

public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";



    //Creating a list of posts
    private List<PostItems> mPostItemsList;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "Device rotated and onCreate called");

        //Initializing Views
        recyclerView = (RecyclerView) findViewById(R.id.post_recycler);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);


        //Initializing the postlist
        mPostItemsList = new ArrayList<>();
        adapter = new PostAdapter(mPostItemsList, this);

        recyclerView.setAdapter(adapter);

        if (NetworkCheck.isAvailableAndConnected(this)) {
            //Caling method to get data
            getData();
        } else {
            final Context mContext;
            mContext = this;
            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setTitle(R.string.alert_titl);
            alertDialogBuilder.setMessage(R.string.alert_mess);
            alertDialogBuilder.setPositiveButton(R.string.alert_posi, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!NetworkCheck.isAvailableAndConnected(mContext)) {
                        alertDialogBuilder.show();
                    } else {
                        getData();
                    }


                }
            });
            alertDialogBuilder.setNegativeButton(R.string.alert_nega, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            });
            alertDialogBuilder.show();

        }

    }

    //This method will get data from the web api
    private void getData(){


        Log.d(TAG, "getData called");
        //Showing progress dialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
        mProgressDialog.show();

        //Creating a json request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, "onResponse called");
                        //Dismissing the progress dialog
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }
                        /*progressDialog.dismiss();*/


                        //calling method to parse json array
                        parseData(response);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }

    //This method will parse json data
    private void parseData(JSONArray array){
        Log.d(TAG, "Parsing array");

        for(int i = 0; i<array.length(); i++) {
            PostItems postItem = new PostItems();
            JSONObject jsonObject = null;
            try {
                jsonObject = array.getJSONObject(i);
                postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
                postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));

 } catch (JSONException w) {
                w.printStackTrace();
            }
            mPostItemsList.add(postItem);
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy called");
        if (mProgressDialog != null){
            mProgressDialog.dismiss();
            Log.d(TAG, "mProgress dialog dismissed");

        }
    }


提前致谢。

请注意How to save custom ArrayList on Android screen rotate?的重复项。虽然在活动中声明了该问题的数组列表,但我是从网上凌空抽出我的。我不知道如何为我的arraylist实现它,否则不会问这个问题

最佳答案

实际上,这是the post you mentioned的副本。是的,该列表是在该帖子的活动的onCreate()中声明的,而您是异步进行的。但是,想法是相同的。

一旦有要发送的数据,就可以在应用程序的任何位置进行保存和还原。

在您的情况下,关键是每次设备旋转时都不调用getData()。如果您已经在mPostItemsList中加载了数据,请通过onSaveInstanceState()保存并还原它,然后在onCreate()中从保存的状态中获取数据。如果该数据不存在,则调用getData()。

public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";
    private final String KEY_POST_ITEMS = "#postitems";

    //Creating a list of posts
    private List<PostItems> mPostItemsList;

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

        initializeViews();

        if (savedInstanceState != null && savedInstanceState.containsKey(KEY_POST_ITEMS)){
            mPostItemsList = savedInstanceState.getParcelableArrayList(KEY_POST_ITEMS);
        } else {
            //Initializing the postlist
            mPostItemsList = new ArrayList<>();

            if (NetworkCheck.isAvailableAndConnected(this)) {
                //Caling method to get data
                getData();
            } else {
                showNoNetworkDialog();
            }
        }

        mAdapter = new PostAdapter(mPostItemsList, this);
        recyclerView.setAdapter(adapter);

    }

    private void parseData(JSONArray array){
        mPostItemsList.clear();

        for(int i = 0; i<array.length(); i++) {
            PostItems postItem = new PostItems();
            JSONObject jsonObject = null;
            try {
                jsonObject = array.getJSONObject(i);
                postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
                postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
            } catch (JSONException w) {
                w.printStackTrace();
            }

            mPostItemsList.add(postItem);
        }

        mAdapter.notifyDataSetchanged();

    }


编辑:我没有看到保存滚动位置的要求。为此,请查看Emin Ayar's answer。另外,这里也有类似的答案:How to save recyclerview scroll position

07-24 09:49
查看更多