【发布时间】:2016-07-22 21:20:46
【问题描述】:
当我点击商店ObjectArray 进入sharedPreference 时,我有按钮,现在我想要另一个按钮来删除ObjectArray。
如何删除一个条目?我可以设法从 sharedPreference 中清除所有日期,但这不是我想要的...
这是我要存储的代码:
private void logDateTime() {
TextView name = (TextView) findViewById(R.id.tv_tel);
String m1 = name.getText().toString();
mTvName = (TextView) findViewById(R.id.tv_name);
Intent i = new Intent(CountryActivity1.this, LogActivity.class);
String m2 = mTvName.getText().toString();
startActivity(i);
// Variables
String date = DateFormat.getDateInstance().format(new Date());
String time = DateFormat.getTimeInstance().format(new Date());
String desc = m2;
String desc1 = m1;
JSONArray completeArray = new JSONArray();
try {
// Open the JSON file and initialize a string builder
FileInputStream in = openFileInput(FILENAME);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
// Read the existing content in the JSON file and add it to the
// string builder
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
if (sb.toString() != "") {
JSONArray temp_arr = new JSONArray(sb.toString());
completeArray = temp_arr;
}
} catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
// Initialize the JSON object for the new entry
JSONObject entry = new JSONObject();
// Initialize the JSON object that will contain the entry object
JSONObject finalEntry = new JSONObject();
try {
// Add the time and date to the entry object
entry.put("date", date);
entry.put("time", time);
entry.put("description", desc);
entry.put("description1", desc1);
// Add the entry object to a new object called "entry"
finalEntry.put("entry", entry);
completeArray.put(finalEntry);
// Convert the complete array in to a string
String jsonEntry = completeArray.toString();
// Write complete array to the file
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(jsonEntry.getBytes());
fos.close();
// Notify that an entry has been created
Toast toast = Toast.makeText(getApplicationContext(), "Saved",
Toast.LENGTH_LONG);
toast.show();
}
catch (JSONException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
提前致谢
【问题讨论】:
-
你的问题是什么?你遇到什么错误了吗?
-
我想从 sharedPreference 中删除一个条目...
-
我无法在您的代码中使用 SharedPreferences
-
你可以得到最后一个条目的字符数,并可以使用 trim 方法从 json 数组中删除最后一个条目