如何在 Android Studio 中将 CSV 文件解析为数组 [英] How to parse CSV file into an array in Android Studio

查看:35
本文介绍了如何在 Android Studio 中将 CSV 文件解析为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何解析 CSV 文件并将内容存储到数组中.我的 csv 文件看起来像这样:

i'm wondering how to parse a CSV file and just store the contents into 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

我只想要名字,所以第二个字段.我想将 csv 中的所有这些项目存储到字符串数组或数组列表中.

I only want the names, so the second field. I want to store all of these items in the csv into an array or arraylist of string.

任何想法如何做到这一点?

Any ideas how to do this?

任何帮助将不胜感激!

推荐答案

CSV 文件在 Android 中的放置位置在res"文件夹中创建一个名为raw"的文件夹并将CSV文件放入其中.

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

如何读取 CSV 文件,自从它的 Android 以来没什么特别的.我们将使用我们的标准 Java 代码.最好使用我们自己的代码而不是去 API.下面的类是一个读取 CSV 文件的实用程序,它可以在 Android 应用程序中使用.我们将在哪个数组中存储 csv 文件项在这些示例中,它是 scorelist arraylist .

How to read CSV file, Nothing special since its Android. All we are going to use our standard Java code. Its better to use our own code instead of going to an API. Following class is an utility to read CSV file and it can be used from within the Android application. In which array we will store items of csv file In these example it is 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;
    }
}

那么如何从raw"文件夹中加载 CSV 文件并使用上述实用程序读取它?

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

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>

对于整个源代码,您可以参考这些链接 javapapers.com/wp-content/uploads/2014/07/CSVFileRead.zip

For the whole source code you can refers to these link javapapers.com/wp-content/uploads/2014/07/CSVFileRead.zip

我认为它会有所帮助

这篇关于如何在 Android Studio 中将 CSV 文件解析为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆