【发布时间】: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