2012-11-15 73 views
3

數據是否有任何方式來加載從文本文件數據(資產)至ListView的而不是做:讀取文本文件,而不是字符串

// ArrayList中爲列表視圖 的ArrayList>產品;

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Listview Data 
    String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE", 
          "iPhone 4S", "Samsung Galaxy Note 800", 
          "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"}; 

    lv = (ListView) findViewById(R.id.list_view); 
    inputSearch = (EditText) findViewById(R.id.inputSearch); 

    // Adding items to listview 
    adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products); 
    lv.setAdapter(adapter); 

預先感謝您

+0

問題標題犯規你的描述相符。你在哪裏閱讀文本文件。你想在列表中設置什麼? –

+0

http://stackoverflow.com/questions/3344551/how-to-read-text-file-in-android。 http://stackoverflow.com/questions/3316629/how-to-read-file-from-the-phone-memory-in-android。看看鏈接。 – Raghunandan

回答

0

讀一行行從的inputStream

InputStream in = getAssets().open(fileName) 
BufferedReader bin = new BufferedReader(new InputStreamReader(in)); 
bin.readLine(); 
2

一種選擇是具有存儲在JSON格式在文件中的數據陣列。

然後你就可以解析該文件並將其加載到與下面的代碼示例字符串數組:

try { 
     // Load file content 
     InputStream is = getAssets().open(filename); 
     StringBuffer fileContent = new StringBuffer(""); 

     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = is.read(buffer)) != -1) { 
      fileContent.append(new String(buffer)); 
     } 

     // Parse into JSON array 
     JSONArray jsonArray = new JSONArray(fileContent.toString());    

     // Build the string array 
     String[] products = new String[jsonArray.length()]; 
     for(int i=0; i<jsonArray.length(); i++) { 
      products[i] = jsonArray.getString(i); 
     } 
    } catch (IOException e) { 
     // IO error 
    } catch (JSONException e) { 
     // JSON format error 
    } 
相關問題