簡體   English   中英

使用共享首選項將項目保存在列表視圖中

[英]Save item in listview with sharedpreferences

我需要存儲我通過“添加”按鈕動態創建的列表視圖。 當然現在如果我退出應用程序,這些項目就會消失。 我以這種方式嘗試,但出了點問題

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();
    }

我不知道如何“調用”共享的首選項,也不知道這種方式是否正確。 現在什么也沒有發生,什么也沒有節省。 有人可以幫我嗎? 謝謝

現在什么也沒有發生,什么也沒有節省。

那是因為您永遠不會調用SavePreferences()方法。

如果要繼續使用SharedPreferences將數據存儲在列表中,則需要在列表中的每個項目上調用SavePreferences()

但是, SharedPreferences用於以鍵值格式存儲數據。 這意味着列表中的每個項目都將需要一個密鑰,並且您需要知道該密鑰才能檢索數據。 如果您的列表可以包含可變數量的項目,則SharedPreferences可能不是您想要的。

我建議閱讀“ 存儲選項”文檔,其中提供了正確使用“ Shared Preferences的完整示例,並討論了更適合您需要的其他選項。

您應該看一下有關活動生命周期的API培訓:

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

還有這個:

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

如您所見,您的活動可以消失,因為用戶可以主動銷毀它(使用“后退”按鈕),或者系統可以銷毀它。 如果他們破壞了系統,則可以使用onSaveInstanceState保存數據,並使用onCreate檢索數據。 在這種情況下,您不必使用SharedPreferences-只需按鏈接中所述使用Bundle。

但是,如果要在用戶關閉數據時保留數據,則應在調用onDestroy()時保存數據。 並在調用onCreate()時檢索數據。 在系統認為不再需要您的活動之前(例如用戶單擊“后退”按鈕時),將調用onDestroy()。 在這種情況下,您必須使用android提供的一種存儲方法,包括“共享”偏好設置。 就像其他人所說的那樣,它需要一種“鍵,值”機制,因此它可能與您的工作不完全匹配。 對於這個任務,使用sqlLite有點重,因為您的數據也不是真正的表類型(實際上,單列表仍然不值得IMO使用)。 我認為存儲列表的最佳方法是使用內部文件。 調用onDestroy()時,獲取所有數據並保存到文件中。 調用onCreate()時,讀取文件並重新填充列表。 您可以在此處閱讀有關android文件系統的信息,包括內部文件:

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

最后,如果用戶按下“主頁”按鈕,您的活動將不會被破壞。 如果他然后“強行關閉”您的應用,則將不會保存任何內容。 如果即使在這種情況下仍要保存它,建議您在調用“ onStop()”時保存數據,並在調用onStart()時重置列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM