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

2

2 Answers 2

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
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Read line by line from inputStream

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.