Christian
Christian

Reputation: 942

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.

Upvotes: 0

Views: 3402

Answers (3)

Dale
Dale

Reputation: 5785

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

Upvotes: 0

liipod
liipod

Reputation: 21

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

Upvotes: 2

user1318455
user1318455

Reputation: 43

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

Upvotes: 1

Related Questions