3

有没有办法将数据从文本文件(在资产中)加载到列表视图而不是这样做:

// ArrayList for Listview 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);

先感谢您

4

2 回答 2

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
    }
于 2012-11-15T12:47:02.640 回答
0

从 inputStream 中逐行读取

InputStream in = getAssets().open(fileName)
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
bin.readLine();
于 2012-11-15T12:41:18.050 回答