0

I compile the list: titleList.add(0, title), apply it in sharedpreferences: prefs.putString(TITLES, title).apply() and now need to retrieve it.


I have looked at a lot of the solutions here and none seem to fit my problem well. The program is suppose to take text a user inputs and save it using SharedPreferences, so it can be used in a ListActivity later. This list is currently an ArrayList (I believe I need it in an array list because I am using AutoCompleteEditText for suggestions from the array list, so I need the adapter).
Based on the above logic,prefs is a sharedpreference object full of string objects. I have tried using prefs.getAll().values.toArray(new String[0...100]). I found that in an "Android" book. It works, but only gets the first item. After trying methods, Set<?> and a few others, that was the method that got anything at all.
It is all I need to have the program working PERFECTLY. Can someone please help getting this list to save in sharedpreferences, retrieving it as a complete, split, list (that can be indexed) and passing it to a ListActivity?
ArrayList<String> titleList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_make_lyric);    

    autoCompleteAdapter = new ArrayAdapter<>(
            this,
            android.R.layout.simple_list_item_1,
            titleList
    );

    lyricTitle.setAdapter(autoCompleteAdapter);
    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()));
        }
    });    

    saveBtn = (Button) findViewById(R.id.saveBtn);
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            performSave();
        }
    });

    titlePref = getSharedPreferences(titlePrefFile, MODE_PRIVATE);
    //titleList = titlePref.getAll().values().toArray();
}
private void performSave() {
    String title = lyricTitle.getText().toString();
    String song = lyricHolder.getText().toString();
    if(!areFieldsNull(title, song)) {
        saveSongFile(title, song);
        warnSave.show();
    }
    else
        warnEmpty.show();
}
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 (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            bufferWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //update song title list adapter
    autoCompleteAdapter = new ArrayAdapter<>(
            this,
            android.R.layout.simple_list_item_1,
            titleList
    );
    lyricTitle.setAdapter(autoCompleteAdapter);
    titleList.add(0,title);
    prefEditor = titlePref.edit();
    prefEditor.putString("titleList", title).apply();
}


Sorry, formatting the code just wont work for me. Thank you and Happy Holidays!
Frank B.
  • 204
  • 5
  • 17
  • 3
    Please provide some code snippet, So we get what you are trying to do – foxt7ot Dec 24 '14 at 16:20
  • You are passing the title string only in the sharedpreferences , is that what you are trying to do? You can pass the complete list to sharedpreferences and then get the complete list back. Also you are adding in the list at 0 position only. – varun Dec 24 '14 at 16:38

2 Answers2

0

I think you need to use ObjectSerializer.

Save :

    ArrayList<String> strings = new ArrayList<String>();
    string.add("Hello!");
    //save list into SP
    SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
    Editor editor = prefs.edit();
    try {
        editor.putString("LIST", ObjectSerializer.serialize(strings));
    } catch (IOException e) {
        e.printStackTrace();
    }
    editor.commit();

Restore :

        // load list from preference
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
        ArrayList<String> strings = new ArrayList<String>();
        try {
            strings = (ArrayList<String>) ObjectSerializer.deserialize(prefs.getString("LIST", ObjectSerializer.serialize(new ArrayList<String>())));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

Or use parcelable wrapping to save/retrieve your data

Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
0

Sergey's answer may be just fine. Also, take a look at JPM's answer and class, on this thread. I used it yesterday.

So, using JPM's class, here's writing myBigArrayList:

// write data file for later use
String ser = SerializeObject.objectToString(myBigArrayList);
if (ser != null && !ser.equalsIgnoreCase("")) {
    SerializeObject.WriteSettings(c, ser, "myobject.dat");
} else {
    SerializeObject.WriteSettings(c, "", "myobject.dat");
}

And, here's a method I adapted, that returns a complete, intact arraylist:

private ArrayList<yabbaData> getYabbaData() {
    String ser = SerializeObject.ReadSettings(getActivity().getApplicationContext(), "myobject.dat");
    ArrayList<yabbaData> give = null;
    if (ser != null && !ser.equalsIgnoreCase("")) {
        Object obj = SerializeObject.stringToObject(ser);
        // Then cast it to your object and
        if (obj instanceof ArrayList) {
            // Do something
            give = (ArrayList<yabbaData>) obj;
        }
    }
    return give;
}

In the write, I use c as my application context, where I had passed in getApplicationContext().

In the read, I used getActivity().getApplicationContext() because I was in a fragment. Sub in String for my yabbaData object, in ArrayList, and I think it's ready to use.

Community
  • 1
  • 1
wwfloyd
  • 312
  • 3
  • 11