我从数据库中检索数据,并使用名为AddDetails的类添加到Arraylist。在AddDetails类中,我正在分配所有值。然后我将ArrayList发送到活动类,我需要在ListView中显示该数据。现在,当将数据从ArrayList复制到Array时,我收到类似未找到类的错误,或者在列表视图上显示时,它只显示一些垃圾值。
代码如下:
private class SearchTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler();
String Place = etSearch.getText().toString();
AddDetails details = new AddDetails(Place);
alSearchResult = db.searchResultByPlace(details);
arrStr = new String[alSearchResult.size()];
try
{
arrStr = (String[]) alSearchResult.toArray();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchActivity.this, android.R.layout.simple_list_item_multiple_choice, arrStr);
lsSearchResult.setAdapter(adapter);
}
catch(Exception e)
{
Log.e("Error:" + e.toString());
}
return null;
}
protected ArrayList<AddDetails> searchResultByPlace(AddDetails details)
{
ArrayList<AddDetails> alSearchData = null;
try
{
String place = details.getPlace();
Cursor c = mDataBase.rawQuery("SELECT * FROM " + ESTATE_DETAILS + " WHERE " + strSearchType + " = " + "'" + place + "'", null);
c.moveToFirst();
if(c.getCount() > 0)
{
alSearchData = new ArrayList<AddDetails>();
if (c.moveToFirst())
{
do {
details = new AddDetails();
details.setID(Integer.parseInt(c.getString(0)));
details.setPlace(c.getString(1));
details.setArea(c.getString(2));
details.setType(c.getString(3));
details.setPhoneNumber(c.getString(4));
// Adding contact to list
alSearchData.add(details);
} while (c.moveToNext());
}
}
c.close();
}
catch(SQLException e)
{
Log.e("Error:", e.toString());
}
return alSearchData;
}
答案 0 :(得分:1)
更改
arrStr = (String[]) alSearchResult.toArray();
与
arrStr = alSearchResult.toArray(new String[0]);
答案 1 :(得分:1)
请不要在后台线程中访问listView lsSearchResult。将结果传递给onPostExecute()。
尝试使用以下代码:
private class SearchTask extends AsyncTask<Void, Void, ArrayList<String>>{
@Override
protected ArrayList<String> doInBackground(Void... arg0) {
DatabaseHandler db = new DatabaseHandler();
String Place = etSearch.getText().toString();
AddDetails details = new AddDetails(Place);
alSearchResult = db.searchResultByPlace(details);
return alSearchResult;
}
protected void onPostExecute(ArrayList<String> result) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SearchActivity.this,android.R.layout.simple_list_item_1, result);
lsSearchResult.setAdapter(arrayAdapter);
}
答案 2 :(得分:0)
ArrayList<String> stock_list = new ArrayList<String>();
stock_list.add("stock1");
stock_list.add("stock2");
String[] stockArr = new String[stock_list.size()];
stockArr = stock_list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
这有助于arraylist进行数组转换也可以直接使用arraylist与arrayadapter无需将其转换为数组