我正在研究内容提供者。我为插入数据及其工作编写了代码我想从内容提供者检索数据并将其显示在其他活动中我不知道如何进行任何人都可以帮助我解决示例代码吗?
MainActivity.Java
package com.example.cpdemo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//---add a book---
ContentValues values = new ContentValues(); values.put(BookProvider.TITLE((EditText)findViewById(R.id.txtTitle)).getText().toString());
values.put(BookProvider.ISBN, ((EditText)findViewById(R.id.txtISBN)).getText().toString());
Uri uri = getContentResolver().insert(BookProvider.CONTENT_URI, values);
String str= getContentResolver().getType(Uri.parse("content://com.contentprovider.demo/books"));
Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG).show();
}
});
Button btnRetrieve = (Button) findViewById(R.id.btnRetrieve);
btnRetrieve.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//---retrieve the titles---
Uri allTitles = Uri.parse(
"content://com.contentprovider.demo/books/2");
Cursor c = getContentResolver().query(allTitles, null, null, null, null);
int i = getContentResolver().delete(allTitles, null, null);
// instead of that use Loader FreamWork from Android 3.0
}
}
BookProvider.java
package com.example.cpdemo;
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 BookProvider extends ContentProvider {
public static final String PROVIDER_NAME = "com.contentprovider.demo";
public static final Uri CONTENT_URI =
Uri.parse("content://"+ PROVIDER_NAME + "/books");
public static final String _ID = "_id";
public static final String TITLE = "title";
public static final String ISBN = "isbn";
private static final int BOOKS = 100;
private static final int BOOK_ID = 200;
private static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "books", BOOKS);
uriMatcher.addURI(PROVIDER_NAME, "books/#", BOOK_ID);
}
//---for database use---
private SQLiteDatabase booksDB;
private static final String DATABASE_NAME = "Books";
private static final String DATABASE_TABLE = "titles";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table " + DATABASE_TABLE +
" (_id integer primary key autoincrement, "
+ "title text not null, isbn 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)
{
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 titles");
onCreate(db);
}
}
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
int count=0;
switch (uriMatcher.match(arg0)){
case BOOKS:
count = booksDB.delete(DATABASE_TABLE,arg1, arg2);
break;
case BOOK_ID:
String id = arg0.getPathSegments().get(1);
count = booksDB.delete(DATABASE_TABLE,
_ID + " = " + id +
(!TextUtils.isEmpty(arg1) ? " AND (" +arg1 + ')' : ""),arg2);
break;
default: throw new IllegalArgumentException("Unknown URI " + arg0);
}
getContext().getContentResolver().notifyChange(arg0, null);
return count;
}
//Returns the MIME type of the data at the given URI
@Override
public String getType(Uri arg0) {
Log.d("hello","with in the getType method");
switch (uriMatcher.match(arg0)){
//---get all books---
case BOOKS:
return "vnd.android.cursor.dir/vnd.contentprovider.books ";
//---get a particular book---
case BOOK_ID:
Log.d("hello","with in the getType method_1");
return "vnd.android.cursor.item/vnd.contentprovider.books ";
default:
throw new IllegalArgumentException("Unsupported URI: " + arg0);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
Log.d("hello","we are in insert block");
//---add a new book---
long rowID = booksDB.insert(DATABASE_TABLE,"",values);
//---if added successfully---
if (rowID>0)
{
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
//---notify register to change the content URI ---
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);
booksDB = dbHelper.getWritableDatabase();
return (booksDB == null)? false:true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
//tablename1 ;;;; id , name
//tablename2 ::: ide ,name
//map.put(tablename1.name,name AS NewName);
//map.put(tablename2.name,name AS exname);
//sqlBuilder.setProjectionMap(map)
//c.getValues(tablename1.name);
//String str = tablename1 left Outer join tablename2 on tablename1.id == tablename2.id;
sqlBuilder.setTables(DATABASE_TABLE);
if (uriMatcher.match(uri) == BOOK_ID)
//---if getting a particular book---
Log.d("hi","we are in query block1");
sqlBuilder.appendWhere(_ID + "= " + uri.getPathSegments().get(1));
Log.d("hi","we are in query block2");
//if (sortOrder==null || sortOrder=="")
//sortOrder = TITLE;
Log.d("hi","we are in query block3");
Cursor c = sqlBuilder.query(booksDB,projection,selection,selectionArgs,
null,
null,
null);
Log.d("hi","we are in query block4");
//---register to watch a content URI for changes---
c.setNotificationUri(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 BOOKS:
count = booksDB.update(DATABASE_TABLE,values,selection,selectionArgs);
break;
case BOOK_ID:
count = booksDB.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;
}
}