how to save contents of a listview to a text file in android?

孤街醉人 提交于 2019-12-25 08:20:23

问题


I have a listview that has a bunch of content and I want to know how I can save the contents inside the list view as a text file? I am pulling all the content from a database.


回答1:


Try array serialization (you can serialize and get back Objects)

    ObjectOutputStream out;
    Object[] objs = new Object[yourListView.getCount()];

    for (int i = 0 ; i < youeListView.getCount();i++) {
        Object obj = (Object)yourListView.getItemAtPosition(i);
        objs[i] = obj;
    }
    try {
        out = new ObjectOutputStream(
                new FileOutputStream(
                        new File(yourFile.txt)));
        out.writeObject(objs);
        out.flush();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }



回答2:


I am asuming you want to save the content of the row that was clicked by the user:

If using ListActivity override onListItemClick (ListView lv, View v, int position, long id). Then String str = lv.getItemAtPosition(position).toString() can give you the string contained in the row. Other possibilities exist depending on your exact implementation. You also have access to the view that was clicked.

I dont think you want to save the content of all the rows as you already have that in your database and can simply query and save from there.

Once you have the string. create a new file and write to it.

One way of writing to file:

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

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Error while saving file", Toast.LENGTH_LONG).show();
        }



回答3:


The mechanics of writing to a file have been covered well, but I'd like to add more about:

I am pulling all the content from a database

In that case, you can get the cursor from your ListView, then use SQLiteCursor.getItemAtPosition().

private String getCsvFromViewCursor(ListView myListView) {
    StringBuilder builder = new StringBuilder();
    SQLiteCursor cursor;
    builder.append("\"Field 1\",\"Field 2\"\n");
    for (int i = 0; i < myListView.getCount(); i++ ){
        cursor = (SQLiteCursor) myListView.getItemAtPosition(i);
        builder.append("\"").append(cursor.getString(0)).append("\",");
        builder.append("\"").append(cursor.getString(1)).append("\"\n");
    }
    return builder.toString();
}


来源:https://stackoverflow.com/questions/10060105/how-to-save-contents-of-a-listview-to-a-text-file-in-android

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