名門Android(9)-データベースサポート(SQLite)を結んで、


有名なAndroid(9)-データベースサポート(SQLite)を結んで、コンテンツ提供器(ContentProvider)はAndroidでSQLite、ContentProviderを使って紹介しています。  データベースサポート(SQLite)-Android開発プラットフォームは、SQLiteデータベースを操作する関連APIコンテンツ提供器(ContentProvider)-データをアプリケーション間で共有する必要がある場合、他のアプリケーションがこのURIを通じて指定されたデータ1、SQLiteのDemo Databaselperjava.にアクセスできるように、プログラムの中でContentProvider定義URIを提供する。
   
package com.webabcd.SQLite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

//        Helper  
public class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context, String name, CursorFactory cursorFactory, int version) {
        super(context, name, cursorFactory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO       ,       
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO           
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        
        // TODO                
    }
}


Main.java

   
package com.webabcd.SQLite;

import java.util.Random;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {

    private DatabaseHelper dbHelper;

    private static final String DATABASE_NAME = "db.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "employee";

    TextView txtMsg;

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

        dbHelper = new DatabaseHelper(this, DATABASE_NAME, null,
                DATABASE_VERSION);

        txtMsg = (TextView) this.findViewById(R.id.txtMsg);

        Button btn1 = (Button) this.findViewById(R.id.btn1);
        btn1.setText("   ");
        btn1.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                CreateTable();
            }
        });

        Button btn2 = (Button) this.findViewById(R.id.btn2);
        btn2.setText("   3    ");
        btn2.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                insertItem();
            }
        });

        Button btn3 = (Button) this.findViewById(R.id.btn3);
        btn3.setText("      ");
        btn3.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                deleteItem();
            }
        });

        Button btn4 = (Button) this.findViewById(R.id.btn4);
        btn4.setText("      ");
        btn4.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                updateItem();
            }
        });

        Button btn5 = (Button) this.findViewById(R.id.btn5);
        btn5.setText("      ");
        btn5.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                showItems();
            }
        });

        Button btn6 = (Button) this.findViewById(R.id.btn6);
        btn6.setText("   ");
        btn6.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                dropTable();
            }
        });
    }

    //      
    private void CreateTable() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
                + " (ID INTEGER PRIMARY KEY, Name VARCHAR, Age INTEGER);";
        try {
            db.execSQL(sql);
            txtMsg.append("       
"); } catch (SQLException ex) { txtMsg.append("
" + ex.toString() + "
"); } } // private void insertItem() { SQLiteDatabase db = dbHelper.getWritableDatabase(); try { Random random = new Random(); for (int i = 0; i < 3; i++) { String sql = "insert into " + TABLE_NAME + " (name, age) values ('name" + String.valueOf(i) + "', " + random.nextInt() + ")"; // execSQL() - sql db.execSQL(sql); } txtMsg.append(" 3
"); } catch (SQLException ex) { txtMsg.append("
" + ex.toString() + "
"); } } // private void deleteItem() { try { SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete(TABLE_NAME, " id < 999999", null); txtMsg.append("
"); } catch (SQLException e) { txtMsg.append("
"); } } // private void updateItem() { SQLiteDatabase db = dbHelper.getWritableDatabase(); try { ContentValues values = new ContentValues(); values.put("name", " "); db.update(TABLE_NAME, values, "id<?", new String[] { "3" }); txtMsg.append("
"); } catch (SQLException e) { txtMsg.append("
"); } } // private void showItems() { SQLiteDatabase db = dbHelper.getReadableDatabase(); try { String[] column = { "id", "name", "age" }; Cursor cursor = db.query(TABLE_NAME, column, null, null, null, null, null); Integer num = cursor.getCount(); txtMsg.append(" " + Integer.toString(num) + "
"); cursor.moveToFirst(); while (cursor.getPosition() != cursor.getCount()) { txtMsg.append(Integer.toString(cursor.getPosition()) + "," + String.valueOf(cursor.getString(0)) + "," + cursor.getString(1) + "," + String.valueOf(cursor.getString(2)) + "
"); cursor.moveToNext(); } } catch (SQLException ex) { txtMsg.append("
" + ex.toString() + "
"); } } // private void dropTable() { SQLiteDatabase db = dbHelper.getWritableDatabase(); String sql = "DROP TABLE IF EXISTS " + TABLE_NAME; try { db.execSQL(sql); txtMsg.append("
"); } catch (SQLException ex) { txtMsg.append("
" + ex.toString() + "
"); } } } 2、ContentProvider Demo MyUser.java package com.webabcd.contentprovider; import android.net.Uri; import android.provider.BaseColumns; // ContentProvider public class MyUser { // _id 。 BaseColumn _id public static final class User implements BaseColumns { // CONTENT_URI public static final Uri CONTENT_URI = Uri.parse("content://com.webabcd.MyContentProvider"); // public static final String USER_NAME = "USER_NAME"; } } MyContentProvider.java package com.webabcd.contentprovider; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.http.util.EncodingUtils; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; // ContentProvider ContentProvider( ) public class MyContentProvider extends ContentProvider { private File file; private FileOutputStream out; private FileInputStream in; // ContentProvider @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } @Override public String getType(Uri uri) { // TODO Auto-generated method stub return null; } // ContentProvider @Override public Uri insert(Uri uri, ContentValues values) { try { out = new FileOutputStream(file); out.write(values.getAsString(MyUser.User.USER_NAME).getBytes()); out.close(); int rowId = 0; Uri rowUri = ContentUris.appendId( MyUser.User.CONTENT_URI.buildUpon(), rowId).build(); getContext().getContentResolver().notifyChange(rowUri, null); return rowUri; } catch (Exception e) { return null; } } // @Override public boolean onCreate() { try { // :/data/data/ / // SD :/sdcard file = new File("/data/data/com.webabcd.contentprovider/", "demo.txt"); if (!file.exists()) file.createNewFile(); return true; } catch (Exception ex) { return false; } } // ContentProvider @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String content; try { in = new FileInputStream(file); int length = (int) file.length(); byte[] buffer = new byte[length]; in.read(buffer, 0, length); content = EncodingUtils.getString(buffer, "UTF-8"); in.close(); String[] columns = new String[] { MyUser.User._ID, MyUser.User.USER_NAME }; MatrixCursor cur = new MatrixCursor(columns); String[] values = new String[] { "0", content }; cur.moveToFirst(); cur.addRow(values); return cur; } catch (Exception e) { return null; } } // ContentProvider @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } } Main.java package com.webabcd.contentprovider; import java.util.Random; import android.app.Activity; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.Contacts; import android.provider.Contacts.People; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; /* * ContentProvider : * content://media/internal/images URI * content://contacts/people/ URI * content://contacts/people/45 URI ( ID 45 ) */ public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn1 = (Button) this.findViewById(R.id.btn1); btn1.setText(" "); btn1.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { Random random = new Random(); insertRecords("name" + String.valueOf(random.nextInt()), String .valueOf(random.nextInt())); } }); Button btn2 = (Button) this.findViewById(R.id.btn2); btn2.setText(" "); btn2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { displayRecords(); } }); Button btn3 = (Button) this.findViewById(R.id.btn3); btn3.setText(" "); btn3.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { deleteRecords(); } }); Button btn4 = (Button) this.findViewById(R.id.btn4); btn4.setText(" "); btn4.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { // ,id People._ID , displayRecords() id int id = 0; updateRecord(id, " name"); } }); Button btn5 = (Button) this.findViewById(R.id.btn5); btn5.setText(" MyContentProvider"); btn5.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { insertRecord2MyContentProvider("webabcd"); } }); Button btn6 = (Button) this.findViewById(R.id.btn6); btn6.setText(" MyContentProvider"); btn6.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { displayRecord2MyContentProvider(); } }); } // ContentProvider private void insertRecords(String name, String phoneNum) { ContentValues values = new ContentValues(); values.put(People.NAME, name); Uri uri = getContentResolver().insert(People.CONTENT_URI, values); Log.d("MyDebug", uri.toString()); Uri numberUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); Log.d("MyDebug", numberUri.toString()); values.clear(); values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE); values.put(People.NUMBER, phoneNum); getContentResolver().insert(numberUri, values); } // ContentProvider private void displayRecords() { String[] columns = new String[] { People._ID, People.NAME, People.NUMBER }; Uri contacts = People.CONTENT_URI; Log.d("MyDebug", contacts.toString()); Cursor cur = managedQuery(contacts, columns, // null, // WHERE null, // WHERE null // Order-by ); if (cur.moveToFirst()) { String id = null; String name = null; String phoneNo = null; while (cur.getPosition() != cur.getCount()) { id = cur.getString(cur.getColumnIndex(People._ID)); name = cur.getString(cur.getColumnIndex(People.NAME)); phoneNo = cur.getString(cur.getColumnIndex(People.NUMBER)); Toast.makeText(this, id + " / " + name + " / " + phoneNo, Toast.LENGTH_SHORT).show(); cur.moveToNext(); } } } // ContentProvider private void deleteRecords() { Uri uri = People.CONTENT_URI; Log.d("MyDebug", uri.toString()); getContentResolver().delete(uri, null, null); // getContentResolver().delete(uri, "NAME=" + "'name'", null); } // ContentProvider private void updateRecord(int recordNo, String name) { Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, recordNo); Log.d("MyDebug", uri.toString()); ContentValues values = new ContentValues(); values.put(People.NAME, name); getContentResolver().update(uri, values, null, null); } // ContentProvider private void insertRecord2MyContentProvider(String name) { ContentValues values = new ContentValues(); values.put(MyUser.User.USER_NAME, name); getContentResolver().insert(MyUser.User.CONTENT_URI, values); } // ContentProvider private void displayRecord2MyContentProvider() { String[] columns = new String[] { MyUser.User.USER_NAME }; Uri uri = MyUser.User.CONTENT_URI; Cursor cur = managedQuery(uri, columns, null, null, null); while (cur.getPosition() != cur.getCount()) { String id = cur.getString(cur.getColumnIndex(People._ID)); String name = cur.getString(cur.getColumnIndex(MyUser.User.USER_NAME)); Toast.makeText(this, id + " / " + name, Toast.LENGTH_SHORT).show(); cur.moveToNext(); } } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.webabcd.contentprovider" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Main" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- ContentProvider" --> <provider android:name="MyContentProvider" android:authorities="com.webabcd.MyContentProvider" /> </application> <uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission> <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission> <uses-sdk android:minSdkVersion="3" /> </manifest>