109-自製Android Content Provider(行動裝置進階應用)

1. AndroidManifest.xml

  • 重點程式碼

<provider
     android:name="InfoProvider"
     android:authorities="COM.TQC.GAD01" > 
</provider>
2. main.xml(GAD01.java)

<?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">

    <Button
        android:id="@+id/btnInitial"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Initial in Form1" />

    <Button
        android:id="@+id/btnChange"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change in Form1" />

    <Button
        android:id="@+id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show in Form1" />

    <Button
        android:id="@+id/btnDelete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete in Form1" />


</LinearLayout>

3. GAD01.java

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class GAD01 extends Activity {

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

Button btnInitial = (Button) findViewById(R.id.btnInitial);
Button btnChange = (Button) findViewById(R.id.btnChange);
Button btnShow = (Button) findViewById(R.id.btnShow);
Button btnDelete = (Button) findViewById(R.id.btnDelete);

btnInitial.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// initial some data
initialData();
}
});

btnChange.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// update Data to
// "name: updated raw data in Form1 ,value:this is updated raw data in Form1"
UpdateData(1, "updated raw data in Form1",
"this is updated raw data in Form1");
}
});

btnShow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {

// get data and show data in LogCat
Infos datas = new Infos();

datas = Getdata(1);
Log.d("Form1", "vvv");
Log.d("Form1", "id : " + datas.id + " name : " + datas.name
+ " value : " + datas.value);
Log.d("Form1", "vvv");
}
});

btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// delete data
DeleteData(1);
}
});
}

public class Infos {
public String id;
public String name;
public String value;
}

public void initialData() {
// inserdata with
// id: 1
// name: Raw Data in Form1
// value: this is Raw Data 1 in Form1
this.InsertData(1, "Raw Data in Form1", "this is Raw Data 1 in Form1");
Toast.makeText(this, "Add initial data.", Toast.LENGTH_LONG);
}

public void InsertData(int id, String name, String value) {
ContentValues values = new ContentValues();
// values.put();
values.put(InfoProvider._ID, id);
values.put(InfoProvider.NAME, name);
values.put(InfoProvider.VALUE, value);
// getContentResolver().insert()
getContentResolver().insert(InfoProvider.CONTENT_URI, values);
}

public void UpdateData(int id, String name, String value) {
ContentValues editedValues = new ContentValues();
// editvalues.put();
editedValues.put(InfoProvider.NAME, name);
editedValues.put(InfoProvider.VALUE, value);
// getContentResolver().update();
getContentResolver().update(
Uri.parse("content://COM.TQC.GAD01/Info/" + id), editedValues,
null, null);
}

public void DeleteData(int id) {
getContentResolver().delete(
Uri.parse("content://COM.TQC.GAD01/Info/" + id), null, null);
}

public Infos Getdata(int id) {

Infos infos = new Infos();
Uri getdata = Uri.parse("content://COM.TQC.GAD01/Info/"
+ String.valueOf(id));
Cursor c = managedQuery(getdata, null, null, null, "_ID asc");

// get data procedure
if (c.moveToFirst()) {
do {
infos.id = c.getString(c.getColumnIndex(InfoProvider._ID));
infos.name = c.getString(c.getColumnIndex(InfoProvider.NAME));
infos.value = c.getString(c.getColumnIndex(InfoProvider.VALUE));
} while (c.moveToNext());
}
return infos;
}

}

4. InfoProvider.java

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class InfoProvider extends ContentProvider {
public static final String PROVIDER_NAME = "COM.TQC.GAD01";

public static final Uri CONTENT_URI = Uri.parse("content://"
+ PROVIDER_NAME + "/Info");

public static final String _ID = "_id";
public static final String NAME = "name";
public static final String VALUE = "value";

private static final int INFOS = 1;
private static final int INFOS_ID = 2;

private static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "Info", INFOS);
uriMatcher.addURI(PROVIDER_NAME, "Info/#", INFOS_ID);
}

// ---for database use---
private SQLiteDatabase InfoDB;
private static final String DATABASE_NAME = "Info";
private static final String DATABASE_TABLE = "Infos";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table Infos (_id text not null , name text not null, value text not null);";

// private static final String DATABASE_CREATE =
// "create table Infos (_id integer primary key autoincrement , name text not null, value text not null);";

private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
// create database use db.execSQL(
db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Content provider database",
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Infos");
onCreate(db);
}
}

@Override
public int delete(Uri uri, String arg1, String[] arg2) {
// arg0 = uri
// arg1 = selection
// arg2 = selectionArgs
int count = 0;
switch (uriMatcher.match(uri)) {
case INFOS:
InfoDB.delete(DATABASE_TABLE, arg1, arg2);
break;
case INFOS_ID:
InfoDB.delete(DATABASE_TABLE, _ID + "="
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(arg1) ? "AND (" + arg1 + ")" : ""),
arg2);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
// ---get all books---
case INFOS:
return "vnd.android.cursor.dir/COM.TQC.GAD01";
// ---get a particular book---
case INFOS_ID:
return "vnd.android.cursor.item/COM.TQC.GAD01";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}

@Override
public Uri insert(Uri uri, ContentValues values) {

long rowID = InfoDB.insert(DATABASE_TABLE, "", values);

if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Failed to insert row into " + uri);
}

@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
InfoDB = dbHelper.getWritableDatabase();
return (InfoDB == null) ? false : true;
}

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

SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
sqlBuilder.setTables(DATABASE_TABLE);

if (uriMatcher.match(uri) == INFOS_ID)

sqlBuilder.appendWhere(_ID + " = " + uri.getPathSegments().get(1));

if (sortOrder == null || sortOrder == "")
sortOrder = NAME;

Cursor c = sqlBuilder.query(InfoDB, projection, selection,
selectionArgs, null, null, sortOrder);
c.setNotificationUri(this.getContext().getContentResolver(), uri);
return c;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case INFOS:
InfoDB.update(DATABASE_TABLE, values, selection, selectionArgs);
break;
case INFOS_ID:
InfoDB.update(
DATABASE_TABLE,
values,
_ID
+ "="
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(selection) ? "AND ("
+ selection + ")" : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

}

5. main.xml(GAD01_2.java)

<?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">

    <Button
        android:id="@+id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show in Form2" />


</LinearLayout>

6. GAD01_2.java

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class GAD01_2 extends Activity {

public static final String _ID = "_id";
public static final String NAME = "name";
public static final String VALUE = "value";

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

Button btnShow = (Button) findViewById(R.id.btnShow);

btnShow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {

// get data and show data in LogCat
Infos datas = new Infos();
datas = Getdata(1);
Log.d("Form2", "vvv");
Log.d("Form2", "id : " + datas.id + " name : " + datas.name
+ " value : " + datas.value);
Log.d("Form2", "vvv");
}
});
}

public class Infos {
public String id;
public String name;
public String value;
}

public Infos Getdata(int id) {

Infos infos = new Infos();
Uri getdata = Uri.parse("content://COM.TQC.GAD01/Info/"
+ String.valueOf(id));
Cursor c = managedQuery(getdata, null, null, null, "_ID asc");

// get data procedure
if (c.moveToFirst()) {
do {
infos.id = c.getString(c.getColumnIndex(_ID));
infos.name = c.getString(c.getColumnIndex(NAME));
infos.value = c.getString(c.getColumnIndex(VALUE));
} while (c.moveToNext());
}
return infos;
}

}

沒有留言: