编辑要在SharedPreferences中保存的活动共享ArrayList

时间:2015-03-11 22:55:39

标签: java android arrays serialization sharedpreferences

我有ArrayList<String>我在共享偏好中保存在活动A 中。我从第二个活动( ListActivity )访问该列表。 活动A 为结果启动 ListActivity 。单击某个项目时, ListActivity 会将该位置的字符串发送到活动A 以供使用。长按可让您删除。

当我从列表中删除时,我想在sharedpreferences中保存新的(最新的)列表。请!我怎样才能做到这一点?我只需要弹出列表,你做你的事情,并在保存最新列表后消失。

我尝试了很多方法(此时代码拼凑而成)但删除项目后,当我再次打开 ListActivity 时,删除的项目仍然存在。

我的代码如下......

活动A:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_write);

    ...
    lyricTitle = (AutoCompleteTextView) findViewById(R.id.lyricTitle);
    ...
    lyricTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // load in song when selected from auto-complete list
            lyricHolder.setText(openSongFile(lyricTitle.getText().toString()));
        }
    });
    lyricHolder = (EditText) findViewById(R.id.lyricHolder);

    newSongBtn = (ImageView) findViewById(R.id.newSongBtn);
    newSongBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (areFieldsNull(lyricTitle.getText().toString(),
                    lyricHolder.getText().toString()))
                alertEmpty.show();
            else {
                /** There is some redundancy within performSave() here */
                performSave();
                lyricTitle.setText("");
                lyricHolder.setText("");
            }
        }
    });

    ...
    findBtn = (Button) findViewById(R.id.findBtn);
    findBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent showListIntent = new Intent(getApplicationContext(), pickActivity.class);
            startActivityForResult(showListIntent, GET_SONG_CODE);
            Log.i("TAG1", "Starting pickActivity.class for result");
        }
    });
    saveBtn = (Button) findViewById(R.id.saveBtn);
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            performSave();
        }
    });
    ...
    // init sharedPreferences
    colorPref = getSharedPreferences(COLOR_PREF, MODE_PRIVATE);
    titlePref = getSharedPreferences(TITLE_PREF, MODE_PRIVATE);
    externalSDPref = getSharedPreferences(EXTERNAL_SD_PREF, MODE_PRIVATE);

    // load defaults of sharedPreferences
    titleList = new ArrayList<>();
    try {
        titleList = (ArrayList<String>) ObjectSerializer
                .deserialize(titlePref.getString(TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    mSetTitleListAdapter(titleList);
    ...

} //end onCreate

private void mSetTitleListAdapter(ArrayList<String> List) {
    autoCompleteAdapter = new ArrayAdapter<>(
            this,
            android.R.layout.simple_list_item_1,
            List
    );
    lyricTitle.setAdapter(autoCompleteAdapter);
}
    ...
private boolean areFieldsNull(String title, String song) {
    // check if the text fields are empty
    return (
            title.isEmpty()||
            title.equals(" ")||
            title.equals("  ")||
            song.isEmpty()||
            song.equals(" ")||
            song.equals("  ")
    );
}
private void performSave() {
    String title = lyricTitle.getText().toString();
    String song = lyricHolder.getText().toString();
    if(!areFieldsNull(title, song)) {
        saveSongFile(title, song);
        alertSave.show();
    }
    else
        alertEmpty.show();
}

private void saveTitleArray() {
    // save string array list in shared prefs
    try {
        prefEditor = titlePref.edit();
        prefEditor.putString(TITLE_PREF, ObjectSerializer.serialize(titleList));
    } catch (IOException e) {
        e.printStackTrace();
    }
    prefEditor.apply();
}

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();
        }
    }
    if(isExternalStoragePresent()&&externalSD_box.isChecked()){
        // save to the SD card IF SD is found AND enableSD_box is checked
        File path = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File songFile = new File (path, title + ".txt");
        try {
            OutputStream os = new FileOutputStream(songFile);
            byte[] data = song.getBytes();
            os.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // new songs (but not updated songs) go to top
    if (!titleList.contains(title))
        titleList.add(0, title);
    mSetTitleListAdapter(titleList);
    saveTitleArray();
}

private String openSongFile(String title){
    BufferedReader bufferReader = null;
    StringBuilder builder = new StringBuilder();
    try {
        FileInputStream fis = openFileInput(title);
        bufferReader = new BufferedReader(new InputStreamReader(fis));
        String line;
        while ((line = bufferReader.readLine()) != null) {
            builder.append(line + "\r\n");
        }
    }  catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            bufferReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return builder.toString();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // when pickActivity ListView returns result
   Log.i("TAG1", "Activity data returned from pickActivity.class");
    if (requestCode == GET_SONG_CODE && resultCode == RESULT_OK) {
        String title = data.getData().toString();
        lyricTitle.setText(title);
        lyricHolder.setText(openSongFile(title));
        Log.i("TAG1", "Result success\nSong loaded into edittext");
        Toast.makeText(this, "\""+title+"\""+" selected", Toast.LENGTH_SHORT).show();
    }
}

ListActivity:

public class pickActivity extends ListActivity {

ArrayList<String> songListArray;
SharedPreferences titlePref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pick_song);
    Log.i("TAG2", "pickActivity.class created");

    // init string array from blank list or sharedPref saved data
    titlePref = getSharedPreferences(writeActivity.TITLE_PREF, MODE_PRIVATE);
    songListArray = new ArrayList<>();
    try {
        songListArray = (ArrayList<String>) ObjectSerializer
                .deserialize(titlePref.getString(writeActivity.TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    mSetListAdapter(songListArray);
    Log.i("TAG2", "Extra received and set");
    mSetListAdapter(songListArray);

    getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
            Log.i("TAG2", "onItemLongClick()");
            final AlertDialog.Builder confirmDel = new AlertDialog.Builder(pickActivity.this);
            confirmDel.setTitle("Delete Song")
                    .setIcon(R.mipmap.ic_keeper)
                    .setMessage("Are you sure you want " +
                            "\"" + songListArray.get(position) +
                            "\"" + " gone?")
                    .setPositiveButton("CANCEL", 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, title, then update title list
                            getApplicationContext().deleteFile(songListArray.get(position));
                            songListArray.remove(position);
                            Log.i("TAG2", "Item deleted from list");
                            updateSharedPref(titlePref, writeActivity.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) {
    Log.i("TAG2", "onListItemClick()");
    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);
    Log.i("TAG2", "ArrayList adapter set");
}

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.commit();
    Log.i("TAG2", "SharedPref updated!");
}

}

1 个答案:

答案 0 :(得分:0)

老实说,在这种情况下,源代码会有很多帮助......

我最好的猜测(没有任何代码),请确保你打电话

editor.apply();

而不是

editor.commit();