Tutorial details

Android beginner tutorial Part 70 Displaying Content Provider data in a ListView | App Code for Sale | Preview

Android beginner tutorial Part 70 Displaying Content Provider data in a ListView | Android Tutorial

How to create a simple application that displays the contents of the database from our content provider

Overview PAGE TOP

In this tutorial we are going to start creating a simple application that displays the contents of the database from our content provider.

Before we add actual code, let's make sure we have everything prepared correctly.

Firstly, go to the Manifest xml and check the provider node. It should look something like this:

    <provider android:name="myContentProvider" 
        android:authorities="com.kircode.codeforfood_test.mycontentprovider">
    </provider>

Make sure that the authorities is set to the correct URI path. It should basically refer to the content provider class in lowercase symbols.

The myContentProvider class looks like this (made in one of the earlier tutorials):

package com.kircode.codeforfood_test;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;


public class myContentProvider extends ContentProvider {
private static final Uri CONTENT_URI = Uri.parse("content://com.kircode.codeforfood_test.mycontentprovider/contacts");
private SQLiteDatabase db;

public myContentProvider() {
// TODO Auto-generated constructor stub
}

@Override
public int delete(Uri url, String where, String[] whereArgs) {
int retVal = db.delete(myDbHelper.TABLE_NAME, where, whereArgs);
getContext().getContentResolver().notifyChange(url, null);

return retVal;
}

@Override
public String getType(Uri arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public Uri insert(Uri url, ContentValues inValues) {
ContentValues values = new ContentValues(inValues);
long rowId = db.insert(myDbHelper.TABLE_NAME, myDbHelper.NAME, values);

if(rowId > 0){
Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(uri, null);

return uri;
}else{
throw new SQLException("Failed to insert row into " + url);
}
}

@Override
public boolean onCreate() {
db = new myDbHelper(getContext()).getWritableDatabase();
return (db == null) ? false : true;
}

@Override
public Cursor query(Uri url, String[] columns, String selection, String[] selectionArgs,
String sort) {
String orderBy;

if(TextUtils.isEmpty(sort)){
orderBy = myDbHelper.NAME;
}else{
orderBy = sort;
}

Cursor c = db.query(myDbHelper.TABLE_NAME, columns, selection, selectionArgs, null, null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), url);
return c;
}

@Override
public int update(Uri url, ContentValues values, String where, String[] whereArgs) {
int retVal = db.update(myDbHelper.TABLE_NAME, values, where, whereArgs);
getContext().getContentResolver().notifyChange(url, null);

return retVal;
}

}

The myDbHelper class looks like this:

package com.kircode.codeforfood_test;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

public class myDbHelper extends SQLiteOpenHelper implements BaseColumns{

public static final String DB_TEST = "contacts.db";
public static final String TABLE_NAME = "people";
public static final String NAME = "name";
public static final String PHONE = "phone";

public myDbHelper(Context context){
super(context, DB_TEST, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " TEXT, " + PHONE + " TEXT);");

ContentValues values = new ContentValues();

values.put(NAME, "Tom");
values.put(PHONE, "0000001");
db.insert(TABLE_NAME, NAME, values);

values.put(NAME, "John");
values.put(PHONE, "0000002");
db.insert(TABLE_NAME, NAME, values);

values.put(NAME, "Bob");
values.put(PHONE, "0000003");
db.insert(TABLE_NAME, NAME, values);

values.put(NAME, "Joe");
values.put(PHONE, "0000004");
db.insert(TABLE_NAME, NAME, values);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

Now, let's go to the activity_main.xml file (which is the layout for the main activity in the application) and add a ListView with id contactList:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ListView android:id="@+id/contactList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

We'll also need a customrow.xml layout file, which you might already have if you followed my tutorials:

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

     <TextView android:id="@+id/t_name"
         android:textSize="24sp"
         android:textStyle="bold"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"/>

     <TextView android:id="@+id/t_phone"
         android:textSize="24sp"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"/>
 </LinearLayout>

It will be used for displaying items in the list view.

Now go to MainActivity.java class.

First of all, we declare a CONTENT_URI variable:

private static final Uri CONTENT_URI = Uri.parse("content://com.kircode.codeforfood_test.mycontentprovider/contacts");

Then we create a Cursor that selects IDs, NAMEs and PHONEs of all the people:

String[] columns = new String[] {myDbHelper._ID, myDbHelper.NAME, myDbHelper.PHONE};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(CONTENT_URI, columns, null, null, null);

Next, we extract all the table data into a ListAdapter object using a SimpleCursorAdapter constructor:

final ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.customrow, cursor, new String[] {myDbHelper.NAME, myDbHelper.PHONE}, new int[] {R.id.t_name, R.id.t_phone}, 0);

We supply the context, the list item layout, the cursor, the attributes that will be displayed and the text fields in the layout that we will use to display the data. The last parameter determines the flags, which we leave empty this time.

Now, let's Toast the number of rows that we got from the table.

Then apply the adapter to our list:

Toast.makeText(this, "Rows found: " + adapter.getCount(), Toast.LENGTH_SHORT).show();
ListView list = (ListView)findViewById(R.id.contactList);
list.setAdapter(adapter);

Full code:

package com.kircode.codeforfood_test;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity{

private static final Uri CONTENT_URI = Uri.parse("content://com.kircode.codeforfood_test.mycontentprovider/contacts");

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String[] columns = new String[] {myDbHelper._ID, myDbHelper.NAME, myDbHelper.PHONE};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(CONTENT_URI, columns, null, null, null);

final ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.customrow, cursor, new String[] {myDbHelper.NAME, myDbHelper.PHONE}, new int[] {R.id.t_name, R.id.t_phone}, 0);
Toast.makeText(this, "Rows found: " + adapter.getCount(), Toast.LENGTH_SHORT).show();
ListView list = (ListView)findViewById(R.id.contactList);
list.setAdapter(adapter);
}

}

That's all for today!

Thanks for reading!

Reference PAGE TOP

http://kirill-poletaev.blogspot.it/2013/02/android-beginner-tutorial-part-70.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.