以正确的顺序保存和显示ArrayList [英] Saving and Displaying ArrayList in correct order

查看:491
本文介绍了以正确的顺序保存和显示ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名初级开发人员,对如何保存屏幕实例的经验很少.

I am a junior developer and I have very little experience with how to save the instance of a screen.

活动:

我的应用程序所做的是,用户每小时输入的输入次数已完成(X).我想做的是,当用户离开此页面并转到另一个活动,然后返回时,该列表将保留.

What my application does is that the user is entering in a number of completed (X) each hour. What I would like to do is that when the user leaves this page and goes to another activity, then returns, the list will retain.

我尝试使用此代码:

 @Override
protected void onPause() {
    super.onPause();
    //Set the values
    sharedPreferences = getSharedPreferences("MYPREFS", MODE_PRIVATE );
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Set<String> set = new HashSet<String>();
    set.addAll(ListElementsArrayList);
    editor.putStringSet("list", set);
    editor.apply();
    }


@Override
public void onResume() {
    super.onResume();
    sharedPreferences = getSharedPreferences("MYPREFS", MODE_PRIVATE );
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Set<String> set = sharedPreferences.getStringSet("list", null);
    ListElementsArrayList.addAll(set);
    listView.setAdapter(adapter);
}

要添加到列表的代码:

 handler = new Handler() ;

    ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));

    adapter = new ArrayAdapter<String>(Processing.this,
            android.R.layout.simple_list_item_1,
            ListElementsArrayList
    );

    listView.setAdapter(adapter);


    btnShippersCompleted.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            shippersCompleted = textView.getText().toString();
            ListElementsArrayList.add(shippersCompleted + "- Hour " + Hour++);
            adapter.notifyDataSetChanged();
        }
    });

尽管我在onResume()方法上收到了一个空指针.所以我改为将代码添加到RELOAD按钮.尽管现在该列表已出现故障,但它仍在工作(请参见屏幕截图).

Although I received a null pointer on the onResume() method. So I added the code to a RELOAD button instead. It was working although now the list is going out of order (see screenshot).

我该怎么办

  1. 取消重新加载按钮,以便自动保留列表

  1. Eradicate the reload button so the list remains automatically

按照保存顺序重新加载列表.

Reload the list in the order that it was saved.

推荐答案

也许这不是您正在等待的答案,而是尝试使用数据库,因为共享首选项本身存储了无序的元素列表(已设置) .或者,您应该对列表进行排序,然后才将其设置为适配器.

Maybe this is not the answer that you are waiting for, but try using the database, because the shared preferences store in themselves an unordered list of elements (set). Or you should sort the list, and only then set it to the adapter.

这篇关于以正确的顺序保存和显示ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆