将数据从ListView保存到SharedPreferences

时间:2017-01-18 17:30:34

标签: android listview sharedpreferences android-arrayadapter

我的活动有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>

1 个答案:

答案 0 :(得分:0)

目前还不清楚问题是什么,但这是我要尝试的内容

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

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