Skip to content Skip to sidebar Skip to footer

How To Save Contents Of A Listview To A Text File In Android?

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.

Solution 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();
    }

Solution 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 {
            Filef= File.createTempFile("file", ".txt", Environment.getExternalStorageDirectory ());
            FileWriterfw=newFileWriter(f);
            fw.write(str);
            fw.close();

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

Solution 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().

privateString 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();
}

Post a Comment for "How To Save Contents Of A Listview To A Text File In Android?"