我的ListView有點問題,它在OnItemLongClickListener中時既不會給我正確的位置也不會提供id。位置和ID在ListView中始終返回相同的值
ListView正確顯示所有條目,但在長條目單擊它時,會返回條目總數作爲位置(與我單擊的項無關)和所有條目的最高ID。 由於這是這個問題,我無法獲得條目的正確標識(我在自定義適配器中有)。我究竟做錯了什麼?
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
//Here I want to delete the selected entry..
//both position and id are returning the same value:
// when there are three items in the list, the position would be three for all entries,
// while the id would be the value of the latest entry.
showDeleteSingleEntryDialog(id);
return true;
}
});
我填充列表視圖與使用的AsyncTask如下(通過調用的AsyncTask在我的片段內OnCreateView)
private class DisplayEntriesAsyncTask extends AsyncTask<Void,Void,Void>{
Cursor data;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
data = mDatabaseHelper.getDiaryEntriesCurrentUser(userID);
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
listData = new ArrayList<>();
if (data == null || data.getCount() < 1) {
mTextView.setText("Keine Einträge vorhanden!");
} else {
try {
while (data.moveToNext()){
listData.add(data.getString(1));
}
} catch (CursorIndexOutOfBoundsException e){
//...
}
}
adapter = new DiaryCursorAdapter(getContext(), data);
mListView.setAdapter(adapter);
}
}
最後,這裏是我的自定義適配器
public class DiaryCursorAdapter extends CursorAdapter {
Context context;
private long ident;
public DiaryCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
this.context = context;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ident = cursor.getLong(0);
TextView title = (TextView) view.findViewById(R.id.listitem_title);
title.setText(cursor.getString(1));
TextView location = (TextView) view.findViewById(R.id.listitem_location);
location.setText(cursor.getString(3));
TextView date = (TextView) view.findViewById(R.id.listitem_date);
date.setText(cursor.getString(4));
TextView content = (TextView) view.findViewById(R.id.listitem_content);
content.setText(cursor.getString(2));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
return layoutInflater.inflate(R.layout.listview_diary_entries, parent, false);
//return view;
}
@Override
public long getItemId(int position) {
return ident;
}}
我試圖在沒有AsyncTask的情況下填充列表視圖。 順便說一句,在相應的佈局文件中的ListView的父母是一個LinearLayout(不是滾動視圖,因爲我發現是一個可能的問題)。
run [this](https://pastebin.com/raw/SkAPUhuk),你在logcat上看到了什麼? – pskink
@pskink我在哪裏獲得方法'getContentResolver'? – Andreas
將代碼放置到「Activity#onCreate」中# – pskink