[英]Android - Force close if i click item on ListView
我需要您的幫助來修復我的代碼。
我的意圖是,如果我單擊ListView上的項目,它將帶我進入action_view。
問題是如果我單擊ListView上的項目,我將被強制關閉。
我認為問題出在onItemClick方法中,您能提供更好的方法來完成它嗎?
這是我的代碼:
public class HotelList extends ListActivity{
hotelHelper dbHotelHelper;
protected Cursor cursor;
protected ListAdapter adapter;
ListView numberList;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.hotellist);
numberList = (ListView)findViewById(android.R.id.list);
numberList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
String selectedItem = (String) getListAdapter().getItem(position);
String query = "SELECT lat, long FROM hoteltbl WHERE name = '" + selectedItem + "'";
SQLiteDatabase dbs = dbHotelHelper.getReadableDatabase();
Cursor result = dbs.rawQuery(query, null);
result.moveToFirst();
double lat = result.getDouble(result.getColumnIndex("lat"));
double longi = result.getDouble(result.getColumnIndex("long"));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&saddr=&daddr="+lat+","+longi));
startActivity(intent);
}
});
dbHotelHelper = new hotelHelper(this);
try{
dbHotelHelper.createDataBase();
}
catch (Exception ioe){
Log.e("err","Unable to create database");
}
view();
}
private void view() {
// TODO Auto-generated method stub
SQLiteDatabase db = dbHotelHelper.getReadableDatabase();
try{
cursor = db.rawQuery("SELECT * FROM hoteltbl", null);
adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"name"},
new int[] {android.R.id.text1}
);
numberList.setAdapter(adapter);
}
catch (Exception e){
Log.e("error",e.toString());
}
}
}
在項目單擊內部,您有多種可能導致異常的方式,“異常”將導致您的應用強制關閉代碼,而異常不會被處理
我正在列出可能導致異常的原因,請檢查以下內容
String selectedItem = (String) getListAdapter().getItem(position);
在這里,您可能會遇到類型對話問題,您正在轉換String不支持的內容
SQLiteDatabase dbs = dbHotelHelper.getReadableDatabase();
Cursor result = dbs.rawQuery(query, null);
result.moveToFirst();
double lat = result.getDouble(result.getColumnIndex("lat"));
double longi = result.getDouble(result.getColumnIndex("long"));
對於您的信息,SimpleCursorAdapter構造函數在API級別11中已棄用。不建議使用此選項,因為它會導致在應用程序的UI線程上執行游標查詢,因此可能導致響應速度較慢甚至是“應用程序無響應”錯誤。 或者,將LoaderManager與CursorLoader一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.