移动开发-使用contentprovider的方法类进行数据获取
設計目標:
1、contentprovider是安卓四大組件之一,請使用其方法類進行數據獲取;
2、自建一個provider,然后在另一個app中使用resolver調用這個provider;
3、理論上需要兩個APP進行實驗。
功能說明:
1、contentprovider主要用于在不同的應用程序之間實現數據共享的功能,它提供了一套完整的機制,允許一個程序訪問另一個程序中的數據,同時還能保證被訪數據的安全性。
2、在本次實驗中具體表現為以下效果,在第一個APP:contentprovide中可以切換訪問第二個APP:resolver,resolver可以調用contentprovider。
代碼展示:
項目provider:
MainActivity.java:
package com.example.provider;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);MyDAO myDAO=new MyDAO(this);} }MyContentProvider.java:(出現了構成它生命周期的幾個方法,包括增、刪、改、查、獲得類型getType和創建onCreate,只需要在onCreate中傳值并new一個MyDAO的方法即可。)
package com.example.provider;import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri;public class MyContentProvider extends ContentProvider {private MyDAO myDAO;public MyContentProvider() {}@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs) {// Implement this to handle requests to delete one or more rows.throw new UnsupportedOperationException("Not yet implemented");}@Overridepublic String getType(Uri uri) {// TODO: Implement this to handle requests for the MIME type of the data// at the given URI.throw new UnsupportedOperationException("Not yet implemented");}@Overridepublic Uri insert(Uri uri, ContentValues values) {// TODO: Implement this to handle requests to insert a new row.//getContext().getContentResolver().insert(uri, values);return myDAO.DAOinsert(values);}@Overridepublic boolean onCreate() {// TODO: Implement this to initialize your content provider on startup.Context context=getContext();myDAO=new MyDAO(context);return false;}@Overridepublic Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {// TODO: Implement this to handle query requests from clients.throw new UnsupportedOperationException("Not yet implemented");}@Overridepublic int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {// TODO: Implement this to handle requests to update one or more rows.throw new UnsupportedOperationException("Not yet implemented");} }MyDAO.java:(數據處理層,需要在這里寫一套真正在數據庫上的增刪改查。)
package com.example.provider;import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.net.Uri;public class MyDAO {private Context context;private SQLiteDatabase database;public MyDAO(Context context){this.context=context;MyDBhelper dBhelper =new MyDBhelper(context,"JOJODB",null,1);database=dBhelper.getReadableDatabase();}public Uri DAOinsert(ContentValues contentValues){long rowid=database.insert("student",null,contentValues);Uri uri=Uri.parse("content://JOJO.provider2/student");Uri inserturi= ContentUris.withAppendedId(uri,rowid);context.getContentResolver().notifyChange(inserturi,null);return inserturi;} }MyDBhelper.java:
package com.example.provider;import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log;import androidx.annotation.Nullable;public class MyDBhelper extends SQLiteOpenHelper {public MyDBhelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {super(context, name, factory, version);Log.d("JOJO","MyDBhelper...");}@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {sqLiteDatabase.execSQL("create table student(" +"id integer primary key autoincrement,name varchar,age integer)");Log.d("JOJO","onCreate...");}@Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {Log.d("JOJO","onUpgrade...");} }Manifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"package="com.example.provider"><applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.Provider"tools:targetApi="31"><providerandroid:name=".MyContentProvider"android:authorities="JOJO.provider2"android:enabled="true"android:exported="true"></provider><activityandroid:name=".MainActivity"android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>resovler項目:
MainActivity.java:
package com.example.resovler;import androidx.appcompat.app.AppCompatActivity;import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ContentResolver resolver=getContentResolver();ContentValues values=new ContentValues();values.put("name","JOJO");values.put("age",20);Uri uri=Uri.parse("content://JOJO.provider2/student");Button button = findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {resolver.insert(uri,values);}});} }activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="resovler"android:textSize="45dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.526"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintVertical_bias="0.363" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="insert"android:textSize="45dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.555"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintVertical_bias="0.587" /></androidx.constraintlayout.widget.ConstraintLayout>效果展示:
運行進入resovler項目界面
點擊INSETR按鈕
在provider項目的數據庫中增添信息
源碼倉庫:?Lzr2002/LZR (github.com)
?
總結
以上是生活随笔為你收集整理的移动开发-使用contentprovider的方法类进行数据获取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 半导体封装设备行业挤入一位国产选手:已实
- 下一篇: linux视频采集软件,嵌入式LINUX