从文本文件而不是String中读取数据

时间:2012-11-15 12:34:42

标签: android listview

有没有办法将数据从文本文件(在资产中)加载到listview而不是:

// ListView的ArrayList     的ArrayList> productList的;

@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);

提前谢谢

2 个答案:

答案 0 :(得分: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
    }

答案 1 :(得分:0)

从inputStream逐行读取

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