这个问题在这里已有答案:
所以我试着读一个CSV
文件并在ListView
中显示它。我在原始目录中有csv文件,我已成功读取每一行并将其输出到日志中。下一步是获取该数据并在ListView
中显示。我的数据存储在ArrayList
中,所以我试图使用ArrayAdapater
,但我看到了问题标题中看到的错误。
main act vi同意.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
并且从未遇到过这个问题。任何帮助表示赞赏!
你的代码有问题:
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);
/** * 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 "";
}
}
尝试使用getActivity()
而不是getApplicationContext(
)。