Reputation: 736
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
Upvotes: 3
Views: 734
Reputation: 18670
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
}
Upvotes: 2
Reputation: 2132
Read line by line from inputStream
InputStream in = getAssets().open(fileName)
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
bin.readLine();
Upvotes: 0