开发者

Android Adapter for 2 Database Sources

I have 2 Android Databases in my app. For the sake of an example, lets say Database #1 is called JOBS and has the following columns: "Jobs Primary Key" - "Job Title" - "Job Description"

Database #2 is called PEOPLE and has the following columns: "People Primary Key" - "First Name" - "Last Name" - "Jobs ID Key"

(Yes I know these are not the greatest of designs from a database perspective, this is just to help paint a picture for my question).

Within a ListView, I'd like to display columns "First Name" - "Last Name" - "Job T开发者_如何学运维itle" (1 column from Database #1, 2 columns from Database #2). Using a SimpleCursorAdapter, is it possible to somehow accomplish this?

If I don't use a SimpleCursorAdapter, the only way that I can think to accomplish this is to use an ArrayAdapter, where I use a StringBuilder to concatenate the 3 columns together, and fill the ListView, but I'm wondering if there is a better way to accomplish this.


Yes, this is possible — assuming you mean two tables in one database, rather than two separate databases.

You just need to query your database to join the info from the two tables together.

For example, something (completely untested) like this:
String[] columns = { "first_name", "last_name", "title" };
SQLiteDatabase db = mDbOpenHelper.getReadableDatabase();
Cursor c = db.query("person LEFT OUTER JOIN job ON person.job_id = job.id", columns, null, null, null, null, null);

Then you can pass the Cursor to the Adapter as usual.


I can't seem to comment, but you'll want to use LEFT OUTER JOIN instead of JOIN (in Christopher's answer) if you want people without jobs to show up too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜