我想在點擊項目後從數據庫中獲取項目的id,然後我想將此id發送到其他活動。通過Android中的getItemAtPosition方法獲取id
我得到一個錯誤:
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.myPackage.Place
該錯誤是由線造成:
Place mPlace = (Place)(lv.getItemAtPosition(position));
當然,如果我改變下面的行線,應用程序工作,但我越來越在屏幕上顯示單行的名稱,而不是id。
String str = (String)(lv.getItemAtPosition(position));
這是我的完整代碼。
public class VisitedPlaces extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
.
.
.
fillTheList();
displayResultList();
}
public void fillTheList(){
DataBaseHelper dbHelper = new DataBaseHelper(this.getApplicationContext());
List<Place> placesList = new ArrayList<>();
String sql = "SELECT _id, Name, Description, Latidute, Longtidute FROM Places WHERE Visited=1";
placesList = dbHelper.getAllPlaces(sql);
for (Place place : placesList){
results.add(place.getPlaceName());
}
}
public void displayResultList() {
ListView lv = getListView();
lv.addHeaderView(tvNew);
lv.setTextFilterEnabled(true);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, results));
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String str = (String)(lv.getItemAtPosition(position));
Place mPlace = (Place)(lv.getItemAtPosition(position)); //HERE IS A PROBLEM
int mID = mPlace.getID();
Toast.makeText(getApplicationContext(),"Click ListItem: " + mID + ", " + id + ", " , Toast.LENGTH_LONG).show();
goToPlaceDescriptions(view, id);
}
});
}
public void goToPlaceDescriptions(View v, long id) {
Intent intent = new Intent(this, PlaceDescriptions.class);
intent.putExtra("id", id);
startActivity(intent);
}
}
can somebode help me?
您有一個String類型的ArrayAdapter,您可能想要創建自己的類型爲Place的ArrayAdapter。 或者你可以做的一件事就是放置mPlace = placesList.get(position); – mlaHackingIsMagic 2015-01-09 22:41:59