Android: Display Multiple Pieces of Cursor Data Together in TextViews instead of a ListView

南楼画角 提交于 2019-12-13 06:32:36

问题


I am able to accomplish pulling a random row of different column indexes and populate a ListView in my Main Activity with the data using a custom ArrayAdapter (List<String>). I want to take that same data and use it to populate a single textview (or LinearLayout containing two TextViews) in the Main Activity. That TextView(s) would be in this format:

String Int:Int Entry

BookName Chapter#:Entry# Entry

I have the following code to pull my random information from my SQLite Database and it works:

public List<String> getEntry() {
    List<String> list = new ArrayList<>();
    Cursor cursor = database.rawQuery("SELECT * FROM bookdatabase ORDER BY RANDOM() LIMIT 1", null);
    cursor.moveToFirst();
    while (cursor != null && cursor.getCount() > 0 & !cursor.isAfterLast()) {
        list.add(cursor.getString(3));
        list.add(cursor.getString(4));
        list.add(cursor.getString(5));
        list.add(cursor.getString(6));
        cursor.moveToNext();
    }
    cursor.close();
    return list;
}

Here is my custom adapter that works to show the data in a ListView:

 public EntryAdapter(Context context, int resource1, List<String> entries) {
    super(context, resource1, entries);
    mContext = context;
    mResource1 = resource1;
    mEntries = entries;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View listItem = convertView;
    if (listItem == null) {
        listItem = LayoutInflater.from(mContext).inflate(mResource1, parent, false);
    }
    TextView entryTextView = (TextView) listItem.findViewById(R.id.bookName);
    entryTextView.setText(mEntries.get(position));

    return listItem;
}

Here is where I am trying access it from my main activity to populate a TextView which currently works to show it in a ListView:

 databaseAccess.open();
    mEntry = databaseAccess.getEntry();
    databaseAccess.close();
    mEntryAdapter = new EntryAdapter(this, 
    R.layout.entry_item, mEntry);
    this.mEntryListView.setAdapter(mEntryAdapter);

Thank you, in advance.


回答1:


After much research, I solved my problem. I ended up using the information contained in one post on stack over flow and another on GitHub; both about CursorAdapters. Bottom line, I created a cursor adapter instead of an array adapter and it woks perfectly. The posts are here in case anyone encounters this same problem:

Cursor adapter and sqlite example

https://github.com/codepath/android_guides/wiki/Populating-a-ListView-with-a-CursorAdapter



来源:https://stackoverflow.com/questions/52786983/android-display-multiple-pieces-of-cursor-data-together-in-textviews-instead-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!