{//Blog} Code is poetry

NadineProvider for Android

25 may 2014 | Categories: Android

The idea of Content Provider in Android is great but it's very difficult to use specially for beginners and I don't understand why they make it so complicated, I mean at least give me a simple way to use it instead of make me dive into advance topic just to persist simple data !

NadineProvider is an open source project provides a very simple way to create and use content provider in Android.

Check it out on Github

Extend NadineProvider and implement it's single method getColumns:

package com.mohammedpascal.provider;

public class SampleProvider extends NadineProvider {
    public String[] getColumns(){
        return new String[]{ "username", "password" };
    }
}

This will create a ContentProvider with _id, username, password. The _id is created automatically!

Add provider to AndroidManifest.xml

<provider
    android:name="com.mohammedpascal.provider.SampleProvider"
        android:authorities="com.mohammedpascal.provider.SampleProvider"
        android:exported="false" />

Notice both name and authority are same as the class name:

"com.mohammedpascal.provider.SampleProvider"

How to use it?

//Insert
ContentValues values = new ContentValues();
values.put("username", "mohammed");
values.put("password", "123");
DB.insert(SampleProvider.class, values);

//Query
Cursor cursor = DB.query(SampleProvider.class);

while( cursor.moveToNext() ){
  String _id = DB.getString(cursor, "_id");
    String username = DB.getString(cursor, "username");
    String password = DB.getString(cursor, "password");
    System.out.println(_id+" "+username+" "+password);
}

cursor.close();

//Update
ContentValues changes = new ContentValues();
changes.put("password", "111");
DB.update(SampleProvider.class, changes, "username", "mohammed");

//Delete
DB.delete(SampleProvider.class);

That's it :)

Check it out on Github

Tags: Android   Content Provider  



comments powered by Disqus
Categories
Archives
Popular Tags