1

我有一个应用程序,它保存一个数组列表String并使用ObjectSerializer然后将该序列化列表保存在一个SharedPreferences实例中对其进行序列化。

SharePreferences它涉及从同一个对象“放置”和“获取”两个活动。

在 aListActivity中,我长按一个项目以开始删除过程。删除后,我使用更新的对象String重新初始化. 在我通过再次调用它重新启动后,该项目重新出现在我的列表中。它在单击时会导致 a ,因为它现在指向一个不再存在的对象 ( )。ListAdapterArrayList<String>ListViewListAcivityNullPointerExceptionnull

我尝试从 中删除项目ArrayList<String>,然后将其放入ObjectSerializerthen中SharedPreferences。我什至尝试删除旧SharedPreference值(使用clear()remove()方法)。也许我只是忽略了一步,但我无法弄清楚是什么原因造成的。

任何人都可以向我展示或指导我如何序列化ArrayList<String>,保存到SharedPreference对象,从列表中删除和项目,并更新对象,以便我可以从另一个活动SharedPreference中获取相同的(正确更新的列表)对象?SharedPreference

太感谢了!

以下是我的(缩短的)代码:

活动一:

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(列表活动):

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

补充:以下是随机选择的用户的一个错误实例。

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
4

0 回答 0