2011-04-07 95 views
0

我需要关于这个的帮助,我想读取存储在SD卡中的文本文件并将结果存储在ArrayList中以供后续使用,但代码崩溃。Android从sdcsrd读取文本并将其存储在ArrayList中

public class Mytextreader extends Activity { final ArrayList> dataList = new ArrayList>();

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    loadData(); 
    String text = ""; 
    for (int i = 0; i < dataList.size(); i++) { 
     text = text + dataList.get(i).get("name") + ":" 
       + dataList.get(i).get("image") + ":" 
       + dataList.get(i).get("price") + ":" 
       + dataList.get(i).get("barcode") + "\n"; 
    } 
    TextView txv = (TextView) findViewById(R.id.textView01); 
    txv.setText(text); 
} 

private void loadData() { 

    File sdcardDir = Environment.getExternalStorageDirectory(); 
    String sdcard = sdcardDir.getAbsolutePath(); 
    File file = new File(sdcard + "/Downloads/data/data.txt"); 

    // For each entry the following lines are repeated 

    HashMap<String, String> hmap = new HashMap<String, String>(); 
    String text = "", line = ""; 

    BufferedReader br = null; 
    try { 
     br = new BufferedReader(new FileReader(file)); 
     while ((line = br.readLine()) != null) { 
      text = text + line + "\n"; 

     } 
     br.close(); 
    } catch (IOException e) { 
     Log.d("File Read test: Error= ", e.getMessage()); 
    } 

    while (true) { 
     line = text.substring(0, text.indexOf('\n')); 
     text = text.substring(text.indexOf('\n') + 1); 

     hmap.put("name", line.substring(0, line.indexOf(';'))); 
     line = line.substring(line.indexOf(';') + 1); 
     // Toast.makeText(this, line, Toast.LENGTH_LONG).show(); 
     hmap.put("image", line.substring(0, line.indexOf(';'))); 
     line = line.substring(line.indexOf(';') + 1); 
     // Toast.makeText(this, line, Toast.LENGTH_LONG).show(); 
     hmap.put("price", line.substring(0, line.indexOf(';'))); 
     line = line.substring(line.indexOf(';') + 1); 
     // Toast.makeText(this, line, Toast.LENGTH_LONG).show(); 
     hmap.put("barcode", line); 
     dataList.add(hmap); 
     hmap.clear(); 
     if (text.length() == 0) 
      break; 

    } 

} 

}

回答

0

好固定的,文本文件有一个空行,删除该行和代码是确定现在

+0

的Andriod开发一个专门的工作,为黑客像我一样努力奋斗身影了解为什么以及如何,但是我们最终完成了工作并产生了可靠的结果。 – MShalash 2011-04-07 16:50:11

相关问题