2015-09-27 20 views
0

我有一個列表的字符串:寫入字符串到數據庫,並顯示在GridView的

abc 
def 
xyz 

我寫的代碼插入每個字符串(從第一行至最後一行),以文件通過點擊一個按鈕。這意味着我需要在按鈕上單擊三次以將所有字符串插入到文件中。之後,我有其他按鈕來顯示數據到gridview。 Gridview的每一行對應於每個字符串,如

1. abc (1. is just index of gridview row) 
2. def 
3. xyz 

對於我的任務,我想找到一個簡單的解決方案來使用android。我知道我們可以將它保存在sql或文本文件中。什麼是我的任務更簡單的解決方案?爲了保存文本文件,如何區分文件中的兩個字符串?如果有可能,你可以給我代碼嗎?感謝

這是我擰文本文件

String filepath = Environment.getExternalStorageDirectory().getPath(); 
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ; 
FileOutputStream fop = null; 
File file = null; 

try { 
    file =new File(filename); 
    fop=new FileOutputStream(file,true); 
    // if file doesn't exists, then create it 
    if (!file.exists()) { 
     file.createNewFile(); 
    } 

    // get the content in bytes 
    byte[] contentInBytes = filecontent.getBytes(); 

    fop.write(contentInBytes); 
    fop.flush(); 
    fop.close(); 

} catch (IOException e) { 
    e.printStackTrace(); 
} 

但是,輸出是abcdefxyz解決方案。對它們進行分類是非常困難的。

+0

有一點注意。使用recyclerview。它比gridview好得多 –

+0

我建議使用sqlite。還使用recyclerview將是一個更好的選擇。 –

回答

1

那麼如果你有

string[] items={abc,def,xyz}; 

寫入文件

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("filename.txt", Context.MODE_PRIVATE)); 
    for(String data : items) 
    { 
     outputStreamWriter.write(data); 
    } 
     outputStreamWriter.close(); 

從文件讀取

InputStream inputStream = openFileInput("filename.txt"); 

     if (inputStream != null) { 
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
      String receiveString = ""; 
      ArrayList<String> data = new ArrayList<String>(); 

      while ((receiveString = bufferedReader.readLine()) != null) { 
       data.Add(receiveString); 
      } 

      inputStream.close(); 

在網格視圖Adpater使用data的ArrayList

+0

感謝rajan ks。但是,我正在TestThread extends Thread的類中工作。如何使用你的函數openFileOutput? – Jame

相關問題