Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an SQLite DB in android with a cursorloader?

I'm setting up my app so that people can create groups of their friends. When a group is created, it writes 2 tables to the SQL database. The first table has a group name and a group id. The second table has 2 columns, a group id and a user id. This is working fine.

However, now I want to be able to read from the database. I'm using a listview fragment with a cursorloader but I'm having trouble getting the information to display. I want to list all the group names from the first table in my list view.

My problem is that, when I first used the cursorloader to list my contacts, I was using a Uri from the content provider in the onCreateLoader method. Specifically I had CONTENT_URI from the ContactsContracts.Contacts class.

Example of cursorloader with contentprovider:

@Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {     Uri contentUri = ContactsContract.Contacts.CONTENT_URI;     return new CursorLoader(getActivity(),contentUri,PROJECTION,SELECTION,ARGS,ORDER); } 

However, without using a content provider, I don't know what to put in the onCreateLoader method because return new CursorLoader(...) requires a Uri in the second argument.

Any suggestion on how I might be able to display my database data in a listview?

fragment class code:

public class GroupListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {  CursorAdapter mAdapter; private OnItemSelectedListener listener; private static final String[] PROJECTION ={GroupContract.GroupDetails.COLUMN_NAME_GROUP_NAME}; private static final String SELECTION = null; final String[] FROM = {GroupContract.GroupDetails.COLUMN_NAME_GROUP_NAME}; final int[] TO = {android.R.id.text1}; private static final String[] ARGS = null; private static final String ORDER = null; private Cursor c;   @Override public void onCreate(Bundle savedInstanceState){     super.onCreate(savedInstanceState);     mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1,null,FROM,TO,0 );     ReadDBAsync readDB = new ReadDBAsync();     readDB.execute(); }  @Override public void onActivityCreated(Bundle savedInstanceState){     super.onActivityCreated(savedInstanceState);     setListAdapter(mAdapter);     getLoaderManager().initLoader(0,null,this); }  @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {     Uri contenturi = Uri.parse("content://preamble.oneapp");     Uri tableuri = Uri.withAppendedPath(contenturi,GroupContract.GroupDetails.TABLE_NAME);     return new CursorLoader(getActivity(),tableuri,PROJECTION,SELECTION,ARGS,ORDER); }  @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {     mAdapter.swapCursor(cursor); }  @Override public void onLoaderReset(Loader<Cursor> cursorLoader) {     mAdapter.swapCursor(null); }   private class ReadDBAsync extends AsyncTask<Void,Void,String> {      @Override     protected String doInBackground(Void... voids) {          ContractDBHelpers mDBHelper = new ContractDBHelpers(getActivity());         SQLiteDatabase db = mDBHelper.getReadableDatabase();         String returnvalue = "database read";         c = db.query(GroupContract.GroupDetails.TABLE_NAME,PROJECTION,null,null,null,null,null);         return returnvalue;     }      @Override     protected void onPostExecute(String result){         Toast.makeText(getActivity(), result, Toast.LENGTH_LONG).show();     } }  } 
like image 442
Terence Chow Avatar asked Aug 20 '13 04:08

Terence Chow


People also ask

How retrieve data from SQLite database Android and display it in a table?

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.

Can SQLite read and write at same time?

First, by default, multiple processes can have the same SQLite database open at the same time, and several read accesses can be satisfied in parallel. In case of writing, a single write to the database locks the database for a short time, nothing, even reading, can access the database file at all.


1 Answers

Android Guide suggests to create a ContentProvider when you want to share your data with other applications. If you don't need this, you can just override method loadInBackgroud() of the CursorLoader class. For example write like this in your onCreateLoader:

return new CursorLoader( YourContext, null, YourProjection, YourSelection, YourSelectionArgs, YourOrder )            {                @Override                public Cursor loadInBackground()                {                    // You better know how to get your database.                    SQLiteDatabase DB = getReadableDatabase();                    // You can use any query that returns a cursor.                    return DB.query( YourTableName, getProjection(), getSelection(), getSelectionArgs(), null, null, getSortOrder(), null );                }            }; 
like image 88
wholeman Avatar answered Oct 02 '22 15:10

wholeman