Community » Forums » Android - Examples > ContentProvider User Demo
January 19, 2010 4:46:10 AM PST (33 weeks ago). Seen 2,747 times.
Photo Serete Itebete
Member since Dec 23, 2009
Location: Oakland
Posts: 16
Content Providers are the Android platforms way of sharing information betweeen multiple applications through its ContentResolver interface. Each application has access to the SQLite database to maintain their information and this cannot be shared with another application.

In this demo, we use the content provider information avaialable through the getContentResolver() method to get device information with the contentresolver instance and quierying the provided cursor. Apart from query, you can with the related methods, the ability to insert, update, delete and getType (to extract the MIME type).

End result is the list of all the system setting on the user on the android device.



With the SimpleCursorAdapter instance makes use of the row.xml with cursor information to populate the listView withing the main.xml layout.

ContentUserDemo.java
Code:

package org.example.cp;


import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;


public class ContentUserDemo extends Activity {
private static final String TAG = "ContentUserDemo";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Get content provider and cursor
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Settings.System.CONTENT_URI, null, null, null, null);

// Let activity manage the cursor
startManagingCursor(cursor);
Log.d(TAG, "cursor.getCount()=" + cursor.getCount());

// Get the list view
ListView listView = (ListView) findViewById(R.id.listView);
String[] from = { Settings.System.NAME, Settings.System.VALUE };
int[] to = { R.id.textName, R.id.textValue };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listView.setAdapter(adapter);
}
}


Addition to the AndroidManifest.xml

Do not forget to add the following user permission tag <uses-permission android:name="android.permission.READ_CONTACTS" /> To givee your application access to the contacts information.

AndroidManifest.xml

Code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.example.cp" android:versionCode="1" android:versionName="1.0.0">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ContentUserDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>



row.xml

Where the individual row information is populated.
Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:padding="5sp"
android:layout_width="fill_parent">
<TextView
android:layout_height="wrap_content"
android:id="@+id/textName"
android:text="Name"
android:textSize="18sp"
android:layout_width="fill_parent"
android:layout_weight="1"></TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textValue"
android:text="Value"
android:textSize="18sp"
android:gravity="right"></TextView>
</LinearLayout>


main.xml

Where all the rows.xml populate the ListView tag
Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/listView">
</ListView>
</LinearLayout>




ScreenShot


Source
http://marakana.com/static/tutorials/ContentUserDemo.zip
Edited 4 times. Last edit by Wei Ting Chua on Jul 4, 2010 at 1:29:55 AM (about 11 weeks ago).
July 1, 2010 1:12:23 AM PDT (10 weeks ago)
Photo Wei Ting Chua
Student
Student
Member since Jul 1, 2010
Posts: 2
Ive created my own content provider and tried to use this code to show my data from my database in list view, but failed. Can you see whats my problem?

This is my ContentProvider class.

Code:

public class SecrecyContentProvider extends ContentProvider {

private static final String TAG = "SecrecyContentProvider";

private static final String DATABASE_NAME = "123";

private static final int DATABASE_VERSION = 1;

private static final String TABLE_NAME = "entry";

public static final String AUTHORITY = "one.two.SecrecyContentProvider";

private static final int ENTRY = 1;

private static final UriMatcher sUriMatcher;

private static HashMap<String, String> SecrecyProjectionMap;

public static final String KEY_ROWID2 = "_id2";
public static final String KEY_TITLE = "title";
public static final String KEY_ENTRY = "entry";
public static final String KEY_DATE = "date";
public static final String KEY_TIME = "time";

private static final String DATABASE_CREATE_2 =
"create table entry (_id2 integer primary key autoincrement, "
+ "title text,entry text, date text not null, "
+ "time text not null);";

private static class DatabaseHelper extends SQLiteOpenHelper {

DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

}


public void onCreate(SQLiteDatabase db) {

db.execSQL(DATABASE_CREATE_2);

}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{

Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);

}
}

private DatabaseHelper dbHelper;

public int delete(Uri uri, String where, String[] whereArgs) {

SQLiteDatabase db = dbHelper.getWritableDatabase();

int count;

switch (sUriMatcher.match(uri)) {

case ENTRY:

count = db.delete(TABLE_NAME, where, whereArgs);

default:

throw new IllegalArgumentException("Unknown URI " + uri);

}

}

public String getType(Uri uri) {

switch (sUriMatcher.match(uri)) {

case ENTRY:

return DBAdapter.CONTENT_TYPE;

default:

throw new IllegalArgumentException("Unknown URI " + uri);

}

}

public Uri insert(Uri uri, ContentValues initialValues) {

if (sUriMatcher.match(uri) != ENTRY) { throw new IllegalArgumentException("Unknown URI " + uri); }

ContentValues values;

if (initialValues != null) {

values = new ContentValues(initialValues);

} else {

values = new ContentValues();

}

SQLiteDatabase db = dbHelper.getWritableDatabase();

long rowId = db.insert(TABLE_NAME, DBAdapter.KEY_ENTRY, values);

if (rowId > 0) {

Uri noteUri = ContentUris.withAppendedId(DBAdapter.CONTENT_URI, rowId);

getContext().getContentResolver().notifyChange(noteUri, null);

return noteUri;

}

throw new SQLException("Failed to insert row into " + uri);

}


public boolean onCreate() {

dbHelper = new DatabaseHelper(getContext());

return true;

}


public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

switch (sUriMatcher.match(uri)) {

case ENTRY:

qb.setTables(TABLE_NAME);

qb.setProjectionMap(SecrecyProjectionMap);

break;

default:

throw new IllegalArgumentException("Unknown URI " + uri);

}

SQLiteDatabase db = dbHelper.getReadableDatabase();

Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

c.setNotificationUri(getContext().getContentResolver(), uri);

return c;

}



public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {

SQLiteDatabase db = dbHelper.getWritableDatabase();

int count;

switch (sUriMatcher.match(uri)) {

case ENTRY:

count = db.update(TABLE_NAME, values, where, whereArgs);

break;

default:

throw new IllegalArgumentException("Unknown URI " + uri);

}

getContext().getContentResolver().notifyChange(uri, null);

return count;

}

static {

sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

sUriMatcher.addURI(AUTHORITY, TABLE_NAME, ENTRY);

SecrecyProjectionMap = new HashMap<String, String>();
SecrecyProjectionMap.put(DBAdapter.KEY_ROWID2, DBAdapter.KEY_ROWID2);
SecrecyProjectionMap.put(DBAdapter.KEY_TITLE, DBAdapter.KEY_TITLE);
SecrecyProjectionMap.put(DBAdapter.KEY_ENTRY, DBAdapter.KEY_ENTRY);
SecrecyProjectionMap.put(DBAdapter.KEY_DATE, DBAdapter.KEY_DATE);
SecrecyProjectionMap.put(DBAdapter.KEY_TIME, DBAdapter.KEY_TIME);

}
}
July 2, 2010 10:05:30 AM PDT (9 weeks ago)
Photo Marko Gargenta
Marakana, Inc.
Member since Jan 19, 2007
Location: San Francisco
Posts: 95
The answer is in the question "how does it fail?". In other words, look at your logcat and you should see what is going on. It is extremely hard to look at piece of code and eyeball what is wrong. It is extremely easy to run the code, let it fail, than look at the logcat. Java does a great job pinpointing the issue.
July 4, 2010 1:29:55 AM PDT (9 weeks ago)
Photo Wei Ting Chua
Student
Student
Member since Jul 1, 2010
Posts: 2
Tried looking at logcat many times and seek alot of help already. Me and my friends are beginners thats why..... :S

Hmm, thanks anyway.