【问题标题】:read data from text file instead of String从文本文件而不是字符串中读取数据
【发布时间】:2012-11-15 12:34:41
【问题描述】:

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

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

提前谢谢你

【问题讨论】:

标签: android listview


【解决方案1】:

一种选择是将数据数组以 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
    }

【讨论】:

    【解决方案2】:

    从inputStream逐行读取

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多