我有一个应用程序保存String
的数组列表,并使用ObjectSerializer
对其进行序列化,然后将该序列化列表保存在SharedPreferences
实例中。
它涉及来自同一SharePreferences
对象的两个“放置”和“获取”活动。
在ListActivity
中,我长按项目以开始删除过程。在String
删除后,我使用更新的ListAdapter
对象重新初始化ArrayList<String>
以更新ListView
。通过再次调用ListAcivity
重新启动后,我的列表中的项目REAPPEARS。单击时会导致NullPointerException
,因为它现在指向不再存在的对象(null
)。
我尝试从ArrayList<String>
删除项目,然后将其放入ObjectSerializer
然后SharedPreferences
。我甚至尝试删除旧的SharedPreference
值(使用clear()
或remove()
方法)。也许我只是忽略了一步,但我无法弄清楚是什么导致它。
是否有人能够显示或指导我如何序列化ArrayList<String>
,保存到SharedPreference
对象,从列表中删除和项目,并更新SharedPreference
对象以便我可以从另一个活动获得相同的(正确更新的列表)SharedPreference
对象吗?
非常感谢你!
以下是我的(缩短的)代码:
活动1:
public static final String TITLE_PREF = "titleList";
ArrayList<String> titleList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveSongFile(title, song);
}
});
}
private void saveSongFile(String title, String song) {
BufferedWriter bufferWriter = null;
try {
FileOutputStream fos = openFileOutput(title, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fos));
bufferWriter.write(song);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// new songs (not updated songs) go to the top
if (!titleList.contains(title))
titleList.add(0, title);
mSetTitleListAdapter(titleList);
saveTitleArray();
}
private void saveTitleArray() {
prefEditor = titlePref.edit();
try {
prefEditor.putString(TITLE_PREF, ObjectSerializer.serialize(titleList));
} catch (IOException e) {
e.printStackTrace();
}
prefEditor.apply();
}
private void mSetTitleListAdapter(ArrayList<String> List) {
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
List
);
titleBox.setAdapter(autoCompleteAdapter);
}
活动2(ListActivity):
public static final String EXTRA_NAME = "com.frankbrenyah.lyricmaker.NAME";
public static final String TITLE_PREF = "titleList";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_song_list);
//init string array from blank list or sharedPref saved data
songListArray = new ArrayList<>();
titlePref = getSharedPreferences(TITLE_PREF, MODE_PRIVATE);
try {
songListArray = (ArrayList<String>) ObjectSerializer.deserialize(
titlePref.getString(TITLE_PREF,
ObjectSerializer.serialize(new ArrayList<String>())
)
);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetListAdapter(songListArray);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final AlertDialog.Builder confirmDel = new AlertDialog.Builder(pickSong_List.this);
confirmDel.setTitle("Delete?")
.setMessage("This cannot be undone!")
.setPositiveButton("DO NOT delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//system default is dismiss()
}
})
.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//delete song, then update title list
getApplicationContext().deleteFile(songListArray.get(position));
songListArray.remove(position);
updateSharedPref(titlePref, TITLE_PREF, songListArray);
mSetListAdapter(songListArray);
Toast.makeText(
getApplicationContext(),
"Deleted",
Toast.LENGTH_SHORT).show();
}
});
confirmDel.create().show();
return true;
}
});
}
@Override
protected void onListItemClick (ListView l, View v, int position, long id){
//return selected song to main activity so it can be loaded into text box's
Intent resultIntent = new Intent(EXTRA_NAME, Uri.parse(songListArray.get(position)));
setResult(RESULT_OK, resultIntent);
finish();
}
private void mSetListAdapter(ArrayList<String> list) {
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
list
);
setListAdapter(arrayAdapter);
}
private void updateSharedPref(SharedPreferences sharedPref,
String prefFileName,
ArrayList<String> list) {
SharedPreferences.Editor editor = sharedPref.edit();
try {
editor.putString(prefFileName, ObjectSerializer.serialize(list));
} catch (IOException e) {
e.printStackTrace();
}
editor.apply();
}
ADDITION :以下是来自随机选择的用户的一个错误实例。
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,
request=0, result=-1, data=Intent { act=com.my.app.NAME
dat=Scrivo una Canzone }} to activity
{com.my.app/com.my.app.ActivityONE}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
java.io.BufferedReader.close()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3633)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3676)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1358)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5351)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
... 10 more