首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法解析构造函数上下文( ArrayAdapter,int,java.util.List)

无法解析构造函数上下文( ArrayAdapter,int,java.util.List)
EN

Stack Overflow用户
提问于 2018-09-18 02:58:21
回答 2查看 1.9K关注 0票数 0

所以我尝试读入一个CSV文件,并在ListView中显示它。我已经在raw目录中获得了csv文件,并且我已经成功地读取了每一行,并将其输出到日志中。下一步是获取数据并将其显示在ListView中。我的数据存储在ArrayList中,所以我尝试使用ArrayAdapater,但出现了问题标题中显示的错误。

MainActvity.java:

    private final List<Sample> coordArray = new ArrayList<>();

private void readGPSData() {
    // Read the raw csv file
    InputStream is = getResources().openRawResource(R.raw.rawgps);
    // Reads text from character-input stream, buffering characters for efficient reading
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(is, Charset.forName("UTF-8"))
    );
    // Initialization
    String line = "";
    // Initialization
    try {
        // Step over headers
        reader.readLine();
        // If buffer is not empty
        while ((line = reader.readLine()) != null) {
            Log.d("MyActivity","Line: " + line);
            // use comma as separator columns of CSV
            String[] tokens = line.split(",");
            // Read the data
            Sample sample = new Sample();
            // Setters
            sample.setLat(tokens[0]);
            sample.setLon(tokens[1]);

            // Adding object to a class
            coordArray.add(sample);
            final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, coordArray);
            listView.setAdapter(adapter);
            // Log the object
            Log.d("My Activity", "Just created: " + sample);
        }

    } catch (IOException e) {
        // Logs error with priority level
        Log.wtf("MyActivity", "Error reading data file on line" + line, e);

        // Prints throwable details
        e.printStackTrace();
    }
}

我已经使用ArrayAdapter很多次了,从来没有遇到过这个问题。如有任何帮助,我们不胜感激!

EN

回答 2

Stack Overflow用户

发布于 2018-09-18 03:55:06

你的代码的问题是:

private final List<Sample> coordArray = new ArrayList<>();

Sample类型,而ArrayAdapter是"String“类型。

ArrayAdapter期望与List具有相同的类型,然后将其放入构造函数中,解决方案是具有相同的类型,例如:

List<Sample> coordArray = new ArrayList<Sample>();
ArrayAdapter<Sample> adapter = new ArrayAdapter<Sample>(getApplicationContext(), android.R.layout.simple_list_item_1, coordArray);
票数 0
EN

Stack Overflow用户

发布于 2018-09-18 03:46:12

尝试使用getActivity()而不是getApplicationContext()。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52374175

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档