【问题标题】:Saving data from ListView into SharedPreferences将数据从 ListView 保存到 SharedPreferences
【发布时间】:2017-01-18 17:30:34
【问题描述】:

我有具有 Listview 的活动。 ListView 中的数据必须保存在 sharedPreferences 中。我有两种方法 LoadPreferences 和 SavePreferences。但问题是它们不能一起工作。这两种方法都有效,然后我将它们分别使用到一个适配器中。但我需要他们两个。我犯错了吗? MainActivity 是:

 public class MainPage extends AppCompatActivity {
            SharedPreferences prefs;
            EditText input;
            Button btnAdd, btnDel;
            ListView list;
            ArrayAdapter<String> adapter, adapter2;
            public static ArrayList<String> taskList = new ArrayList<String>();


            @Override
            protected void onCreate(final Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                prefs = getSharedPreferences("myUsers", MODE_PRIVATE);
                input = (EditText) findViewById(R.id.txtItem);
                btnAdd = (Button) findViewById(R.id.btnAdd);
                list = (ListView) findViewById(R.id.list1);
                btnDel = (Button) findViewById(R.id.btnDel);
                userName();
                LoadPreferences();
                adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
                ///adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,taskList);
                list.setAdapter(adapter);
                list.setAdapter(adapter2);



                btnAdd.setOnClickListener(new View.OnClickListener() {

                                              @Override
                                              public void onClick(View v) {
                                                  // TODO Auto-generated method stub
                                                  String task = input.getText().toString();
                                                  adapter.add(task);
                                                  adapter.notifyDataSetChanged();
                                                  SavePreferences();
                                              }
                                          }
                );
            }

            public boolean onCreateOptionsMenu(Menu menu) {
                getMenuInflater().inflate(R.menu.menu1, menu);//What Options Menu to present
                return super.onCreateOptionsMenu(menu);
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                String msg = "";
                switch (item.getItemId()) {//selected menu item
                    case R.id.first:
                        ///msg="first selected";
                        Logout();
                        break;
                    case R.id.second:
                        msg = "Second selected";
                        break;
                }
                /// Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();

                return super.onOptionsItemSelected(item);
            }

            public void Logout() {
                JSONObject userJson = getUserByName(userName());
                Toast.makeText(this, "found" + userJson, Toast.LENGTH_LONG).show();
                String status = "status";
                try {
                    userJson.put(status, false);//local json change
                    prefs.edit().putString(userJson.getString("name"), userJson.toString()).commit();//save changed JSON

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Intent i = new Intent(this, Login.class);
                this.startActivity(i);
            }

            private JSONObject getUserByName(String name) {
                try {
                    return new JSONObject(prefs.getString(name, ""));
                } catch (JSONException e) {
                    return null;
                }
            }

            public String userName() {
                String msg =null;
                Intent i = getIntent();//get Intent - that started this Activity
                if (i.hasExtra("userName")) {//if has data by key: "msg"
                    msg = i.getStringExtra("userName");//get data by key "msg" as String
                   //// Toast.makeText(this, msg, Toast.LENGTH_LONG).show();

                }
                return msg;
            }

            protected void SavePreferences() {
                JSONObject ExistUser = getUserByName(userName());
                ////Toast.makeText(this,ExistUser+"found",Toast.LENGTH_LONG).show();
                String ag = input.getText().toString().trim();
                if (ag.length() != 0) {
                    taskList.add(ag);
                    input.setText("");
                    try {
                        ExistUser.put("task", new JSONArray(taskList));
                        prefs.edit().putString(ExistUser.getString("name"), ExistUser.toString()).commit();
                        Toast.makeText(this, ExistUser + "found", Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                }
            }


            public ArrayList<String> LoadPreferences() {
                JSONObject ExistUser = getUserByName(userName());
                try {
                    if(ExistUser.getJSONArray("task")!=null){
                        JSONArray jArray = ExistUser.getJSONArray("task");
                        if (jArray != null) {
                            for (int i=0;i<jArray.length();i++){
                                taskList.add(jArray.getString(i));
                            }
                        }
                    }
                    else{
                        return null;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return taskList;
            }

        }

布局是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/txtItem"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/hintTxtItem"
        />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/lblBtnAdd"
        android:layout_toRightOf="@id/txtItem"
        android:background="#009900"
        />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:text="@string/txtEmpty"
        android:gravity="center_horizontal"
        />

    <ListView
        android:id="@+id/list1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:choiceMode="multipleChoice" >
    </ListView>

    <Button
        android:id="@+id/btnDel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/lblBtnDel"
        android:background="#009900"
        />
</RelativeLayout>

【问题讨论】:

  • 正如我之前为您回答的 - 不要将列表存储到 SharedPreferences...您对数据库有什么看法?
  • 另外,list.setAdapter(adapter2); 将不起作用,因为 1) adapter2 为 null 并且 2) 您一次只能将 一个 适配器分配给 ListView
  • 首先,这会比我想象的更复杂。我刚刚学习,我仍然不知道如何与数据库交互。其次,现在我只需要连接两件事。列表视图和共享首选项。如果我要使用数据库,我需要连接三件事。第三,我觉得我非常接近解决方案。但如果你说这只是一种可能的方式,我会尝试......
  • 有一些数据库库,例如 SugarORM 或 Cupboard,让 SQLite 数据库变得非常简单。通过使用 SharedPreferences 并一遍又一遍地手动提取和重新构建相同的 JSON,您会使它变得比必要的复杂得多。
  • 谢谢。我会试试的。

标签: android listview sharedpreferences android-arrayadapter


【解决方案1】:

目前还不清楚问题出在哪里,但这是我会尝试的方法

您想通过用户名从数组中加载字符串...

public ArrayList<String> loadUserTasks(String userName) {
    List<String> taskList = new ArrayList<String>();
    JSONObject user = getUserByName(userName);
    try {
        JSONArray tasks = user.getJSONArray("task");
        if(tasks != null){
            for (int i = 0; i < jArray.length(); i++){
                taskList.add(tasks.getString(i));
            }
        } 
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return taskList;
}

然后,当您创建适配器时,您可以获得该列表。

String userName = userName();
List<String> tasks = loadUserTasks(userName);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tasks);
list.setAdapter(adapter);

并且您想将来自适配器的字符串保存到 JSON 中

protected void saveTasksForUser(String userName) {
    // Store value currently in input field
    String currentTask = input.getText().toString().trim();
    if (!currentTask.isEmpty()) {
        adapter.add(currentTask);
        input.setText("");
    }

    // Save values from adapter into JSON
    JSONArray tasks = new JSONArray();
    for (int i = 0; i < adapter.getCount(); i++) {
        tasks.put(adapter.getItem(i));
    }

    // Update the User 
    JSONObject user = getUserByName(userName);
    user.put("task", tasks);
    prefs.edit().putString(userName, user.toString()).commit();
}

【讨论】:

  • 终于成功了。你是天才。非常感谢你!我告诉过你它会起作用的。 =)
  • 也许它太多了,但现在我完全失去了我试图删除值。我想通过单击删除单个值。如果您愿意,我可以打开新问题并标记您。我不想这样做,因为这是同一个问题。提前致谢。
  • 点击一个项目。使用您自己的代码从适配器中删除。使用我的答案保存列表。
  • 非常感谢您对数据库的建议。我终于将它集成到我的项目中,这真的很容易。
  • 很高兴你这么认为。有些人觉得这真的很难:)
猜你喜欢
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
相关资源
最近更新 更多