2016-07-16 35 views
7

Tôi tự hỏi cách phân tích cú pháp tệp CSV và chỉ lưu trữ nội dung vào một mảng. Tệp csv của tôi trông giống như sau:Cách phân tích cú pháp tệp CSV thành một mảng trong Android Studio

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

Tôi chỉ muốn tên, vì vậy trường thứ hai. Tôi muốn lưu trữ tất cả các mục này trong csv vào một mảng hoặc mảng danh sách chuỗi.

Bất kỳ ý tưởng nào về cách thực hiện việc này?

Bất kỳ trợ giúp nào sẽ được đánh giá rất nhiều!

Trả lời

9

Nơi để đặt các tập tin CSV trong Android Tạo một thư mục có tên là “thô” bên trong “res” thư mục và đặt các tập tin CSV trong đó.

Cách đọc tệp CSV, Không có gì đặc biệt kể từ Android của nó. Tất cả chúng ta sẽ sử dụng mã Java chuẩn của chúng ta. Tốt hơn nên sử dụng mã của riêng chúng ta thay vì đi đến một API. Sau lớp là một tiện ích để đọc tệp CSV và nó có thể được sử dụng từ bên trong ứng dụng Android. Trong đó mảng chúng tôi sẽ lưu trữ các mục của tệp csv Trong ví dụ này, đó là danh sách mảng phân cách.

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; 
    } 
} 

Vậy làm cách nào để tải tệp CSV từ thư mục “thô” và sử dụng tiện ích trên để đọc?

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> 

Đối với mã nguồn hoàn toàn, bạn có thể đề cập đến những liên kết javapapers.com/wp-content/uploads/2014/07/CSVFileRead.zip

Tôi nghĩ rằng nó sẽ giúp

1

Tuyên bố từ chối trách nhiệm: Tôi chưa bao giờ làm việc với Android, nhưng tôi biết Java, vì vậy hy vọng tất cả đều giống nhau.

Điều đó đang được nói, bạn có thể thử một cái gì đó như thế này.

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

Android bằng cách mặc định không tạo ra các thư mục nguyên Tạo một thư mục thô dưới res/raw trong dự án của bạn. sao chép tệp CSV của bạn trong đó. giữ tên của tệp CSV thấp hơn và chuyển đổi thành định dạng văn bản khi được yêu cầu. tên tệp CSV của tôi là welldata.scv WellData - nó là lớp mô hình với getter và setter. wellDataList là ArrayList để lưu trữ dữ liệu.

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(); 
} 

}}

Các vấn đề liên quan