3

is there any way to load data from text file( in assets) to listview instead of doing:

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

thank you in advance

Ziri
  • 718
  • 7
  • 16
  • question title doesnt matches your description. Where have you read the text file. what do you want to set in the list.? – Sahil Mahajan Mj Nov 15 '12 at 12:40
  • 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. Take a look at the links. – Raghunandan Nov 15 '12 at 14:17

2 Answers2

2

One option is to have the data array stored in JSON format in your file.

Then you can parse this file and load it into an array of strings with the following code sample:

    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
    }
sdabet
  • 18,360
  • 11
  • 89
  • 158
0

Read line by line from inputStream

InputStream in = getAssets().open(fileName)
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
bin.readLine();
Yahor10
  • 2,123
  • 1
  • 13
  • 13