亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取同一個對象到Android ListView

獲取同一個對象到Android ListView

LEATH 2023-10-19 14:54:03
我嘗試在 Android 中開發我的第一個應用程序,但遇到了一個錯誤。我需要從 SQLite 數據庫獲取對象并在 ListView 中顯示它們。這是我的適配器的代碼:public class ReminderListAdapter extends ArrayAdapter<Reminder> {private Context mContext;private int mResource;public ReminderListAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Reminder> objects) {    super(context, resource, objects);    mContext = context;    mResource = resource;}@NonNull@Overridepublic View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {    int id = getItem(position).getId();    String name = getItem(position).getName();    String hour = getItem(position).getHour();    String date = getItem(position).getDate();    LayoutInflater inflater = LayoutInflater.from(mContext);    convertView = inflater.inflate(mResource, parent, false);    TextView resId = convertView.findViewById(R.id.textId);    TextView resName = convertView.findViewById(R.id.textName);    TextView resHour = convertView.findViewById(R.id.textHour);    TextView resDate = convertView.findViewById(R.id.textDate);    resId.setText(String.valueOf(id));    resName.setText(name);    resHour.setText(hour);    resDate.setText(date);    return convertView;}這是我需要從數據庫發布對象的活動代碼:public class EditActivity extends AppCompatActivity {DBHelper dbHelper;SQLiteDatabase database;private ListView listView;private TextView countRem;private String count;ArrayList<Reminder> ReminderList = new ArrayList<>();@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_edit);    dbHelper = new DBHelper(this);    database = dbHelper.getWritableDatabase();    listView =(ListView) findViewById(R.id.ListOfReminders);    countRem =(TextView) findViewById(R.id.textView);結果,我在列表視圖中得到相同的輸出。對象1:ID:0,名稱:1,小時:2,日期:3。該數據與數據庫中的數據不匹配。而且,這個輸出適用于每個對象。有什么錯誤嗎?如果這是一個愚蠢的錯誤,我很抱歉,這是第一個應用程序。
查看完整描述

1 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

cursor.getColumnIndex(...)只返回行的列索引。要獲取該列中的值,您有以下幾種選擇:

  • 如果事先知道數據類型,則可以直接調用cursor. 例如,如果該列DBHelper.KEY_NAME包含String,我們可以直接使用查詢該列中的值cursor.getString(cursor.getColumnIndex(DBHelper.KEY_NAME))

  • 如果不這樣做,您可以嘗試調用cursor.getType(int columnIndex)以獲取基礎類型,然后根據返回值在游標上調用適當的方法。

簡而言之,代碼的問題在于您獲取的是列索引getColumnIndex) 而不是列getFloat、getIntgetString):

    ...

    int idIndex = cursor.getColumnIndex(DBHelper.KEY_ID);

    int nameIndex = cursor.getColumnIndex(DBHelper.KEY_NAME);

    int hourIndex = cursor.getColumnIndex(DBHelper.KEY_HOUR);

    int dateIndex = cursor.getColumnIndex(DBHelper.KEY_DATE);

    String name = cursor.getString(nameIndex);

    String hour = cursor.getString(hourIndex);

    String date = cursor.getString(dateIndex);

  ...


查看完整回答
反對 回復 2023-10-19
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號