2012-04-08 112 views

回答

1

我asuming要保存被點擊用戶,該行的內容:

如果使用ListActivity覆蓋onListItemClick(LV的ListView,視圖V,INT位置,長ID)。然後String str = lv.getItemAtPosition(position).toString()可以給你包含在該行中的字符串。其他可能性取決於您的具體實施情況。您還可以訪問被點擊的視圖。

我不認爲你想保存所有行的內容,因爲你已經在數據庫中有這些內容,並且可以簡單地從那裏查詢和保存。

一旦你有字符串。創建一個新文件並寫入它。寫作

一種方式提交:

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

如果我想保存所有的信息,我該怎麼做? – Christian 2012-04-09 13:38:48

+0

您可以嘗試:lv.getCount()獲取總項目。然後循環所有項目以獲取每行的內容。 lv.getItemAtPosition(位置)的ToString()。職位價值將從零到數。加起來所有的字符串並保存如上。 – user1318455 2012-04-09 23:06:11

2

嘗試數組序列(可以序列,並取回對象)

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

getItemAtPosition()不是一個好主意,因爲如果項目沒有出現在屏幕上,它將返回null。 – Dale 2016-06-21 17:51:21

0

寫入文件的機制已覆蓋好,但我想添加更多關於:

我從數據庫中提取所有內容

在這種情況下,您可以從ListView中獲取光標,然後使用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(); 
} 
相關問題