How to parse a CSV file into an array in Android Studio

I am wondering how to parse a CSV file and just store the contents in an array. My csv file looks something like this:

1,bulbasaur,1,7,69,64,1,1 2,ivysaur,2,10,130,142,2,1 

I only need names, so the second field. I want to save all these elements in csv to an array or arraylist string.

Any ideas how to do this?

Any help would be greatly appreciated!

+7
java android arrays parsing csv
source share
3 answers

Where to place the CSV file in Android Create a folder called "raw" inside the "res" folder and put the CSV file in it.

How to read a CSV file , Nothing special with its Android. We are all going to use our standard Java code. It is better to use our own code instead of switching to the API. The next class is a utility for reading a CSV file and can be used from an Android application. In which array we will store the elements of the csv file. In this example, this is a scorelist arraylist.

 public class CSVFile { InputStream inputStream; public CSVFile(InputStream inputStream){ this.inputStream = inputStream; } public List read(){ List resultList = new ArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); try { String csvLine; while ((csvLine = reader.readLine()) != null) { String[] row = csvLine.split(","); resultList.add(row); } } catch (IOException ex) { throw new RuntimeException("Error in reading CSV file: "+ex); } finally { try { inputStream.close(); } catch (IOException e) { throw new RuntimeException("Error while closing input stream: "+e); } } return resultList; } } 

So, how to load a CSV file from a raw folder and use the above utility to read?

 InputStream inputStream = getResources().openRawResource(R.raw.stats); CSVFile csvFile = new CSVFile(inputStream); List scoreList = csvFile.read(); 

MainActivity.java

 public class MainActivity extends Activity { private ListView listView; private ItemArrayAdapter itemArrayAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); itemArrayAdapter = new ItemArrayAdapter(getApplicationContext(), R.layout.item_layout); Parcelable state = listView.onSaveInstanceState(); listView.setAdapter(itemArrayAdapter); listView.onRestoreInstanceState(state); InputStream inputStream = getResources().openRawResource(R.raw.stats); CSVFile csvFile = new CSVFile(inputStream); List scoreList = csvFile.read(); for(String[] scoreData:scoreList ) { itemArrayAdapter.add(scoreData); } } } 

ItemArrayAdapter.java

 public class ItemArrayAdapter extends ArrayAdapter { private List scoreList = new ArrayList(); static class ItemViewHolder { TextView name; TextView score; } public ItemArrayAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } @Override public void add(String[] object) { scoreList.add(object); super.add(object); } @Override public int getCount() { return this.scoreList.size(); } @Override public String[] getItem(int index) { return this.scoreList.get(index); } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; ItemViewHolder viewHolder; if (row == null) { LayoutInflater inflater = (LayoutInflater) this.getContext(). getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.item_layout, parent, false); viewHolder = new ItemViewHolder(); viewHolder.name = (TextView) row.findViewById(R.id.name); viewHolder.score = (TextView) row.findViewById(R.id.score); row.setTag(viewHolder); } else { viewHolder = (ItemViewHolder)row.getTag(); } String[] stat = getItem(position); viewHolder.name.setText(stat[0]); viewHolder.score.setText(stat[1]); return row; } } 

activity_mail.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.javapapers.android.csvfileread.app.MainActivity"> <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/listView" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" /> </RelativeLayout> 

item_layout.xml

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/name" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_marginLeft="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/score" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_marginRight="20dp" /> </RelativeLayout> 

For all source code, you can link to this link javapapers.com/wp-content/uploads/2014/07/CSVFileRead.zip

I think this will help

+9
source share

Disclaimer: I have never worked with Android, but I know Java, so hopefully anyway.

As the saying goes, you can try something like this.

 Scanner scanner = new Scanner(new File("file.csv")); ArrayList<String> pokemon = new ArrayList<>(); while(scanner.hasNextLine()) { pokemon.add(scanner.nextLine().split(",")[1]); } scanner.close(); 
+1
source share

Android does not create a raw folder by default. Create a raw folder under res / raw in your project. copy the CSV file into it. save the CSV file name in lower case and convert it to text format. my CSV file name is welldata.scv WellData is a getter and setter model class. wellDataList is an ArrayList array for storing data.

 private void readData() { InputStream is = getResources().openRawResource(R.raw.welldata); BufferedReader reader = new BufferedReader( new InputStreamReader(is, Charset.forName("UTF-8"))); String line = ""; try { while ((line = reader.readLine()) != null) { //set splitter String[] tokens = line.split(","); //read the data WellData wellData = new WellData(); wellData.setOwner(tokens[0]); wellData.setApi(tokens[1]); wellData.setLongitude(tokens[2]); wellData.setLatitude(tokens[3]); wellData.setProperty(tokens[4]); wellData.setWellName(tokens[5]); wellDataList.add(wellData); Log.d("MainActivity" ,"Just Created " +wellData); } } catch (IOException e1) { Log.e("MainActivity", "Error" + line, e1); e1.printStackTrace(); } 

}}

0
source share

All Articles