Efficientway to Save/load List items to text file android

梦想的初衷 提交于 2019-12-22 11:27:16

问题


Hi All does anyone have a Efficient way to Save and load list view array items to a text file how would you integrate save and load into this code ?

I have some direction for example for save to text.

         File f = File.createTempFile("file", ".txt",Environment.getExternalStorageDirectory ());
        FileWriter fw = new FileWriter(f);
        fw.write(m_listItems);
        fw.close();

All i want to do is have the ability save and load the list items that i add to the listview Any help would be much appreciated . I'm lost.

thanking you guys in advance.

public class ListtestActivity extends Activity {
ArrayAdapter<String> m_adapter;
ArrayList<String> m_listItems = new ArrayList<String>();


Button bt;
Button save;
Button Loadtxt;
EditText et;
TextView tv;
ListView lv;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 save = (Button) findViewById(R.id.button2);
Loadtxt = (Button) findViewById(R.id.button3);
bt = (Button) findViewById(R.id.button1);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.textView1);
lv = (ListView) findViewById(R.id.listView1);
m_adapter = new ArrayAdapter<String>   (this,android.R.layout.simple_list_item_1, m_listItems);

 lv.setAdapter(m_adapter);
final String input = et.getText().toString();

bt.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

    String input = et.getText().toString();
    if(null!=input&&input.length()>0){     

    m_listItems.add(input);

    m_adapter.notifyDataSetChanged();

  }

save.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {



  }

 Loadtxt.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {



 }
}
});

回答1:


Try this,it may be help to you

public  void writeToFile(String fileName)
{
    try {
        final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/folderName/" );

        if (!dir.exists())
        {
            if(!dir.mkdirs()){
                Log.e("TAG","could not create the directories");
            }
        }

        final File myFile = new File(dir, fileName + ".txt");
        if (!myFile.exists())
            myFile.createNewFile();



        FileWriter writer = new FileWriter(myFile);
        for(String str: m_listItems) {
            writer.write(str);
        }
        writer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}



回答2:


If you want a fast and robust solution, you can use Java object serialization. However, that file you write will not be human-readable any more, as it will be stored in binary format.

http://www.vogella.com/tutorials/JavaSerialization/article.html

I say robust because, today you are using a ArrayList<String>. Tomorrow if you wanted to change it to ArrayList<MyOwnClass>, you could still use the serialization option without any changes to save and load back the object.

If you wanted to use something robust like serialization, but still keep it human readable, you could use a JSON library like Gson, and stream the contents directly to a file.

https://stackoverflow.com/a/29319491/1364747




回答3:


The Simple XML Framework makes it very easy to serialize your objects to storage file in XML format.

The Apache CSV library makes it easy to read and write data as comma-separated or tab-delimited files.

Search Stack Overflow for more discussions and examples of both.




回答4:


An easy way would be to convert you list of objects into a string then deserialise it when you need it. You can do it with Gson this way:

Convert to string

Gson gson = new Gson();
List<MyObject> objects = new ArrayList<>();
objects.add(...) //whatever, all your datas to save

String objectsStr = gson.toJson(objects));
//Save you string in a file or in a preference.

String to object

String objectsStr = ...//get form file or prefs
Gson gson = new Gson();
List<MyObjects> list = new ArrayList< MyObjects >();
list = Arrays.asList(gson.fromJson(objectsStr, MyObjects[].class));

Don't forget to mark the serialisable fields in your class:

public class MyObject {

    @SerializedName("field1")
    @Expose
    private String filed1;
    @SerializedName("field2")
    @Expose
    private String field1;

}



回答5:


protected Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bais);
    Object ret= ois.readObject();
    ois.close();
    return ret;
}

protected byte[] objectToBytes(Serializable object) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(object);
    oos.close();
    return baos.toByteArray();
}


来源:https://stackoverflow.com/questions/37916573/efficientway-to-save-load-list-items-to-text-file-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!