简体   繁体   English

使用共享首选项将项目保存在列表视图中

[英]Save item in listview with sharedpreferences

I need to stored my listview that i create dynamically by a "add" button. 我需要存储我通过“添加”按钮动态创建的列表视图。 Of course right now if i go out of application the items disappears. 当然现在如果我退出应用程序,这些项目就会消失。 I tryied in this way but something's wrong 我以这种方式尝试,但出了点问题

public class MainActivity extends Activity{
    private EditText etInput;
    private Button btnAdd;
    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;

    /* Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setUpView();

        // Eliminare un elemento al longClick con dialog di conferma
        lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View v,
                    final int position, long id) {
                // TODO Auto-generated method stub
                    AlertDialog.Builder adb = new AlertDialog.Builder(
                    MainActivity.this);
                    adb.setTitle("Are you sure");
                    adb.setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub
                                itemArrey.remove(position);
                                itemAdapter.notifyDataSetChanged();

                            }
                        });
                adb.setNegativeButton("No",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub
                                 dialog.dismiss();

                            }
                        });
                adb.show();

                return false;
            }
        });

        lvItem.setClickable(true);
        lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

            Object o = lvItem.getItemAtPosition(position);
            Intent intent2 = new Intent(getApplicationContext(), MainActivity.class); // Mettere settings.class quando creata
            MainActivity.this.startActivity(intent2); 
          }
        });
    }

    private void setUpView() {
        etInput = (EditText)this.findViewById(R.id.editText_input);
        btnAdd = (Button)this.findViewById(R.id.button_add);
        lvItem = (ListView)this.findViewById(R.id.listView_items);


        itemArrey = new ArrayList<String>();
        itemArrey.clear();

        itemAdapter = new ArrayAdapter<String>(this, R.layout.customlistview,itemArrey);
        lvItem.setAdapter(itemAdapter);


        btnAdd.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                addItemList();
            }
        });  

    }

    protected void addItemList() {

    if (isInputValid(etInput)) {
        itemArrey.add(0,etInput.getText().toString());
        etInput.setText("");

        itemAdapter.notifyDataSetChanged();

    }   

    }

    protected boolean isInputValid(EditText etInput2) {
        // TODO Auto-generatd method stub
        if (etInput2.getText().toString().trim().length()<1) {
            etInput2.setError("Insert value");
            return false;
        } else {
            return true;
        }

    }
    // Shared preferences
    protected void SavePreferences(String key, String value) {
        // TODO Auto-generated method stub
        SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = data.edit();
        editor.putString(key, value);
        editor.commit();


    }
    protected void LoadPreferences(){
        SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
        String dataSet = data.getString("LISTS", "None Available");

         itemAdapter.add(dataSet);
         itemAdapter.notifyDataSetChanged();
    }

I don't know how "call" the shared preferences and i don't know if in this way it's correct. 我不知道如何“调用”共享的首选项,也不知道这种方式是否正确。 Right now nothing happen, nothing is saving. 现在什么也没有发生,什么也没有节省。 Someone can help me please? 有人可以帮我吗? Thanks 谢谢

Right now nothing happen, nothing is saving. 现在什么也没有发生,什么也没有节省。

That's because you never call your SavePreferences() method. 那是因为您永远不会调用SavePreferences()方法。

If you want to continue using SharedPreferences to store the data in your list, you will need to call SavePreferences() on every item in the list. 如果要继续使用SharedPreferences将数据存储在列表中,则需要在列表中的每个项目上调用SavePreferences()

However, SharedPreferences are used for storing data in a key-value format. 但是, SharedPreferences用于以键值格式存储数据。 This means that every item in your list will require a key, and you need to know that key to retrieve the data. 这意味着列表中的每个项目都将需要一个密钥,并且您需要知道该密钥才能检索数据。 If your list can contain a variable number of items, SharedPreferences is likely not what you want. 如果您的列表可以包含可变数量的项目,则SharedPreferences可能不是您想要的。

I recommend reading the Storage Options documentation, which provides a complete example using Shared Preferences correctly, and discusses other options which may better suit your needs. 我建议阅读“ 存储选项”文档,其中提供了正确使用“ Shared Preferences的完整示例,并讨论了更适合您需要的其他选项。

You should look at this API training about activity life cycle: 您应该看一下有关活动生命周期的API培训:

http://developer.android.com/training/basics/activity-lifecycle/index.html http://developer.android.com/training/basics/activity-lifecycle/index.html

and also this: 还有这个:

http://developer.android.com/training/basics/activity-lifecycle/recreating.html http://developer.android.com/training/basics/activity-lifecycle/recreating.html

As you can see, your activity can be gone because the user actively destroy it (using the back button) or the system can destroy it. 如您所见,您的活动可以消失,因为用户可以主动销毁它(使用“后退”按钮),或者系统可以销毁它。 If they system destroy it you can use onSaveInstanceState to save the data and onCreate to retrieve it. 如果他们破坏了系统,则可以使用onSaveInstanceState保存数据,并使用onCreate检索数据。 In that case you do not have to use SharedPreferences - just use Bundle as described in the link. 在这种情况下,您不必使用SharedPreferences-只需按链接中所述使用Bundle。

However, if you want to persist your data when the user close it, you should save your data when the call back onDestroy() is called. 但是,如果要在用户关闭数据时保留数据,则应在调用onDestroy()时保存数据。 And retrieve the data when onCreate() is called. 并在调用onCreate()时检索数据。 onDestroy() is called before the system thinks that your activity is not needed anymore, like when the user click the "back" button. 在系统认为不再需要您的活动之前(例如用户单击“后退”按钮时),将调用onDestroy()。 In that case you do have to use one of the storage method provided by android, including Shared preferences. 在这种情况下,您必须使用android提供的一种存储方法,包括“共享”偏好设置。 Like someone else said, it requires a "key, value" mechanism, so it might not match 100% with what you do. 就像其他人所说的那样,它需要一种“键,值”机制,因此它可能与您的工作不完全匹配。 Using sqlLite is a bit heavy weight for this task, since your data is not really of a table type either (a single column table, actually, which is still not database worthy IMO). 对于这个任务,使用sqlLite有点重,因为您的数据也不是真正的表类型(实际上,单列表仍然不值得IMO使用)。 I think the best way to store your list is to use internal file. 我认为存储列表的最佳方法是使用内部文件。 When onDestroy() is called, grab all your data and save to a file. 调用onDestroy()时,获取所有数据并保存到文件中。 When onCreate() is called, read the file and repopulate your list. 调用onCreate()时,读取文件并重新填充列表。 You can read about android file system, including internal files here: 您可以在此处阅读有关android文件系统的信息,包括内部文件:

http://developer.android.com/training/basics/data-storage/files.html http://developer.android.com/training/basics/data-storage/files.html

As a close note, if the user press the "Home" button, your activity will not be destroyed. 最后,如果用户按下“主页”按钮,您的活动将不会被破坏。 If he then "Force close" your app then nothing will be saved. 如果他然后“强行关闭”您的应用,则将不会保存任何内容。 If you still want to save it even in that case, I suggest you to save your data when "onStop()" is called and reset your list when onStart() is called. 如果即使在这种情况下仍要保存它,建议您在调用“ onStop()”时保存数据,并在调用onStart()时重置列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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