因此,我尝试读取CSV
文件并在ListView
中显示它。我已经在原始目录中找到了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
了很多次,并且从未遇到过这个问题。任何帮助表示赞赏!
答案 0 :(得分:0)
您的代码存在以下问题:
private final List<Sample> coordArray = new ArrayList<>();
类型为Sample
,而ArrayAdapter
类型为“字符串”。
ArrayAdapter
期望与List
具有相同的类型,然后将其放入构造函数中,您的解决方案具有相同的类型,例如:
List<Sample> coordArray = new ArrayList<Sample>();
ArrayAdapter<Sample> adapter = new ArrayAdapter<Sample>(getApplicationContext(), android.R.layout.simple_list_item_1, coordArray);
答案 1 :(得分:0)
/** * Constructor * * @param context The current context. * @param resource The resource ID for a layout file containing a TextView to use when * instantiating views. * @param objects The objects to represent in the ListView. */ public ArrayAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<T> objects) { this(context, resource, 0, objects); }
您可以看到ArrayAdapter的构造函数收到一个T列表(T是泛型类型)。因为您指定的通用类型是String
,但是列表中每个项目的类型都是Sample
,所以编译器会显示错误。
首先更改您的代码
final ArrayAdapter<Sample> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, coordArray);
然后覆盖toString
类中的Sample
方法,因为当列表视图显示Sample
的列表时,它将在每个toString
对象上调用Sample
方法默认情况下。
class Sample{
// Your code goes here
@Override
public String toString() {
// TODO: Return a string will be displayed on list view for this object, it can be a properties for example.
return "";
}
}
答案 2 :(得分:-1)
尝试使用getActivity()
代替getApplicationContext(
)。