如何使用内部存储存储自定义对象的ArrayList?

时间:2013-12-30 11:59:05

标签: java android arraylist internal-storage

我想使用内部存储来存储名为WordList的自定义对象的ArrayList。

这是我的代码:

@SuppressWarnings("serial")
public class WordList extends MainActivity implements Serializable {

public String name;
public ArrayList<String> wordarray;
public ArrayList<String> definitionarray;

public WordList(String newName)
{
    this.name = newName;
    this.wordarray = new ArrayList<String>();
    this.definitionarray = new ArrayList<String>();
}

public String getName()
{
    return name;
}

private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeUTF(name);
    out.writeObject(wordarray);
    out.writeObject(definitionarray);
}

private void readObject(ObjectInputStream in) throws IOException,
        ClassNotFoundException {
    name = in.readUTF();
    wordarray = (ArrayList<String>) in.readObject();
    definitionarray = (ArrayList<String>) in.readObject();
}  
}

这是主要的活动:

    public class MainActivity extends Activity {
private EditText text;
private ArrayList<WordList> lists = new ArrayList<WordList>();
private TextView textview;
FileOutputStream fos;
String filePath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (EditText) findViewById(R.id.editText1);
    textview = (TextView) findViewById(R.id.test);
    filePath = getApplicationContext().getFilesDir().getPath().toString() + ".fileName.txt";
}


public void onClick(View view) throws FileNotFoundException {
    switch (view.getId()) {
    case R.id.addtoarray:
        String input = text.getText().toString();
        WordList list = new WordList(input);
        lists.add(list);
        break;
    case R.id.save:
        try {
            File f = new File(filePath);
            FileOutputStream fos = new FileOutputStream(f, true);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            Toast.makeText(getApplicationContext(), "Wrote " + String.valueOf(lists.size() + "objects to file!"), Toast.LENGTH_LONG).show();
            oos.writeInt(lists.size());
            for(int i=0; i<lists.size(); i++)
            {
                oos.writeObject(lists.get(i));
            }
            oos.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        break;
    case R.id.load:
        File saveFile = new File(filePath);
        if (saveFile.exists())
        {
            Toast.makeText(getApplicationContext(), "File found!",
                    Toast.LENGTH_SHORT).show(); 
        try {
            FileInputStream fis = new FileInputStream(saveFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            int num = ois.readInt();
            for(int i = 0; i<num; i++)
            {
                WordList o = (WordList) ois.readObject();
                lists.add(o);
            }
            fis.close();
            ois.close();
        } catch (FileNotFoundException e) {
          e.printStackTrace();
      } catch (StreamCorruptedException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      } catch (ClassNotFoundException e) {
          e.printStackTrace();
      }
    } else {
        Toast.makeText(getApplicationContext(), "File not found!",
              Toast.LENGTH_SHORT).show();
    }
        textview.setText(lists.get(0).getName());
        break;
    }
}

关于Toasts,保存对象,但应用程序在阅读时遇到问题。有人可以告诉我,我在这里做错了什么吗?

1 个答案:

答案 0 :(得分:0)

您可以分两步完成:
1.您需要能够将WordList对象转换为String对象/变量,反之亦然。您可以使用评论中的建议来解答您如何执行此操作 2.然后,您将能够使用SharedPreferences保存String对象

在您的代码中,您将执行以下操作:
1.当您需要将对象保存在内存中时,将其转换为字符串:

String my_object = GetStringFromMyObject(object_to_save);

2。然后将其保存在SharedPreferences中:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("my_object_key", my_object);

3。最后,您可以随时恢复该值:

MyObject object_to_restore = GetMyObjectFromString(prefs.getString("my_object_key", "default_value));