Android之contentProvider共享數據


一、實驗內容 在先前實驗8內容的基礎上對功能進行修改,將數據庫中學生信息表的數據共享給其他應用程序使用。 二、實驗步驟 1.編寫應用程序1,直接在實驗8編寫好的應用程序中加入新的功能,創建並注冊一個contentProvider,將數據庫中學生信息表的增刪查改等操作功能共享給其他應用程序使用。(共享數據的URI地址請根據程序的具體信息自行指定) 2.編寫應用程序2,界面如圖1所示,利用程序1提供的共享操作對數據庫進行相應的增加、刪除、修改。 3.編寫應用程序3,界面如圖2所示,對程序1的共享數據進行觀察監聽,只要數據庫中的共享數據有任何的變化,在界面輸出提示信息“有程序改變了您的數據庫!”,並且直接對更改后的數據內容進行查詢並顯示在界面中。

 

 

開始實習了,天天加班到12點以后,一點時間都沒有了,就寫的很倉促,簡單的能實現就行了,

這次先給上截圖

 

 

加班去了,就不多講了直接上代碼。代碼粘貼復制就能用,

第一個homework_9_1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:text=" 學號 : "/>
        <EditText
            android:id="@+id/Stdudent_ID"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:text=" 姓名 : "/>
        <EditText
            android:id="@+id/Stdudent_NAME"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="102dp"
            android:layout_height="match_parent"
            android:text="性別" />

        <RadioGroup
            android:id="@+id/Student_SEX"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/Student_BOY"
                android:layout_width="118dp"
                android:layout_height="match_parent"
                android:text="男" />

            <RadioButton
                android:id="@+id/Student_GIRL"
                android:layout_width="110dp"
                android:layout_height="match_parent"
                android:text="女" />
        </RadioGroup>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:text=" 班級 : "/>
        <EditText
            android:id="@+id/Student_CLASS"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/Stdudent_ADD"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="添加" />
        <Button
            android:id="@+id/Stdudent_MV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="修改" />
        <Button
            android:id="@+id/Stdudent_RM"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="刪除" />
        <Button
            android:id="@+id/Stdudent_FIND"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="查詢" />
    </LinearLayout>



</LinearLayout>

第二個homework_9_2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/Student_ALL"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"/>

</LinearLayout>

還有第三個homework_five_2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

然后是主要的java文件了

第一個MainActivity

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private EditText Student_ID;
    private EditText Student_NAME;
    private EditText Student_CLASS;
    private RadioGroup Student_SEX;
    private RadioButton Student_BOY;
    private RadioButton Student_GIRL;
    private Button Stdudent_ADD;
    private Button Stdudent_MV;
    private Button Stdudent_RM;
    private Button Stdudent_FIND;
    private ListView Student_ALL;

    ArrayList<String> stringArrayList = new ArrayList<String>();

    private  String newId;
    private static final String TAG = "MainActivity";

    String[] data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homework_9_1);

        //1.對學號姓名班級進行實例化
        Student_ID = (EditText) findViewById(R.id.Stdudent_ID);
        Student_NAME = (EditText) findViewById(R.id.Stdudent_NAME);
        Student_CLASS = (EditText) findViewById(R.id.Student_CLASS);
        //2.實例化和監聽性別選項
        Student_SEX = (RadioGroup) findViewById(R.id.Student_SEX);
        Student_BOY = (RadioButton) findViewById(R.id.Student_BOY);
        Student_GIRL = (RadioButton) findViewById(R.id.Student_GIRL);



        Stdudent_ADD = (Button) findViewById(R.id.Stdudent_ADD);//增
        Stdudent_ADD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String id = Student_ID.getText().toString();
                String name = Student_NAME.getText().toString();
                String classes = Student_CLASS.getText().toString();
                String sex = "0";
                if (Student_GIRL.isChecked()){
                    sex = "女";
                }
                if(Student_BOY.isChecked()){
                    sex = "男";
                }
                //創建期待匹配的uri

                //獲得ContentResolver對象,調用方法
                if (id.equals(null)){
                    Toast.makeText(MainActivity.this,"id不可為空!!!",Toast.LENGTH_SHORT).show();//這個判斷是假的,不管是不是空,都會點擊成功的
                }else {
                    Uri uri1 = Uri.parse("content://com.example.ContentProvider/information");
                    ContentValues values1 = new ContentValues();
                    values1.put("id",id);
                    values1.put("name",name);
                    values1.put("class",classes);
                    values1.put("sex",sex);
                    getContentResolver().insert(uri1,values1);
                    Toast.makeText(MainActivity.this,"有數據修改了您的數據庫!!!",Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(MainActivity.this,SecondActivity.class)); //為了實現第三個要求,實在沒時間寫了,就想了個騷操作,不監聽啥的,就直接跳轉了就完了
                }

            }
        });

        Stdudent_RM = (Button) findViewById(R.id.Stdudent_RM);//刪
        Stdudent_RM.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String id = Student_ID.getText().toString();
                if (id!=null){//這個判斷是假的,不管是不是空,都會點擊成功的
                    Uri uri2 = Uri.parse("content://com.example.ContentProvider/information");
                    getContentResolver().delete(uri2,"id=?",new String[]{id});
                    Toast.makeText(MainActivity.this,"有數據修改了您的數據庫!!!",Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(MainActivity.this,SecondActivity.class));//為了實現第三個要求,實在沒時間寫了,就想了個騷操作,不監聽啥的,就直接跳轉了就完了
                }else {
                    Toast.makeText(MainActivity.this,"id不可為空!!!",Toast.LENGTH_SHORT).show();
                }
            }
        });

        Stdudent_MV = (Button) findViewById(R.id.Stdudent_MV);//改
        Stdudent_MV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String id = Student_ID.getText().toString();
                final String name = Student_NAME.getText().toString();
                final String classes = Student_CLASS.getText().toString();
                String sex = "0";
                if (Student_GIRL.isChecked()){
                    sex = "女";
                }
                if(Student_BOY.isChecked()){
                    sex = "男";
                }
                if(id!=null){//這個判斷是假的,不管是不是空,都會點擊成功的
                    Uri uri3 =Uri.parse("content://com.example.ContentProvider/information");
                    ContentValues values1 = new ContentValues();
                    ContentValues values2 = new ContentValues();
                    ContentValues values3 = new ContentValues();
                    ContentValues values4 = new ContentValues();
                    values1.put("id",id);
                    values2.put("name",name);
                    values3.put("class",classes);
                    values4.put("sex",sex);
                    getContentResolver().update(uri3,values1,"id=?",new String[]{id});
                    getContentResolver().update(uri3,values2,"id=?",new String[]{id});
                    getContentResolver().update(uri3,values3,"id=?",new String[]{id});
                    getContentResolver().update(uri3,values4,"id=?",new String[]{id});
                    Toast.makeText(MainActivity.this,"有數據修改了您的數據庫!!!",Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(MainActivity.this,SecondActivity.class));//為了實現第三個要求,實在沒時間寫了,就想了個騷操作,不監聽啥的,就直接跳轉了就完了
                }else {
                    Toast.makeText(MainActivity.this,"id不可為空!!!",Toast.LENGTH_SHORT).show();
                }

            }
        });

        Stdudent_FIND = (Button) findViewById(R.id.Stdudent_FIND);//查
        Stdudent_FIND.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,SecondActivity.class));
            }
        });

    }

}

第二個SecondActivity

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AlertDialog;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class SecondActivity extends AppCompatActivity {

    private ListView Student_ALL;
    String[] data;
    ArrayList<String> stringArrayList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homework_9_2);
        final DatabaseHelper databaseHelper = new DatabaseHelper(this,"ciec.db",null,2);

        Student_ALL = (ListView) findViewById(R.id.Student_ALL);

        Uri uri = Uri.parse("content://com.example.ContentProvider/information");
        Cursor cursor = getContentResolver().query(uri,new String[]{"id","name","sex","class"},null,null,null);
        String textview_data = "";
        //利用游標遍歷所有數據對象
        //為了顯示全部,把所有對象連接起來,放到TextView中
        while(cursor.moveToNext()){
            String qwe = cursor.getString(cursor.getColumnIndex("id"));
            String asd = cursor.getString(cursor.getColumnIndex("name"));
            String zxc = cursor.getString(cursor.getColumnIndex("sex"));
            String qaz = cursor.getString(cursor.getColumnIndex("class"));
            textview_data = qwe + "--" + asd +"--" + zxc +"--" + qaz;
            stringArrayList.add(textview_data);
        }
        //利用arraylist,保存數據,然后在轉換成String[]數組
        String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
        data = stringArray;
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,R.id.LS);//新建並配置ArrayAapeter
        MyBaseAdapter mAdapter = new MyBaseAdapter();
        Student_ALL.setAdapter(mAdapter);
    }

    class MyBaseAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return data.length;
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(convertView == null){
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.homework_five_2,parent,false);
                holder = new ViewHolder();
                holder.mTextView = (TextView) convertView.findViewById(R.id.tv);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mTextView.setText(data[position]);
            return convertView;
        }
        class ViewHolder {
            TextView mTextView;
        }
    }
}

第三個MyContentProvider

package com.example.app;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

public class MyContentProvider extends ContentProvider {

    private DatabaseHelper myDBHelpter;
    private static final String TAG = "DatabaseProvider";

    //添加整形常亮
    public static final int USER_DIR = 0;
    public static final int USER_ITEM = 1;
    //創建authority
    public static final String AUTHORITY = "com.example.ContentProvider";
    //創建UriMatcher對象
    private static UriMatcher uriMatcher;
    static {
        //實例化UriMatcher對象
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        //可以實現匹配URI的功能
        //參數1:authority 參數2:路徑 參數3:自定義代碼
        uriMatcher.addURI(AUTHORITY, "information", USER_DIR);
        uriMatcher.addURI(AUTHORITY, "information/#", USER_ITEM);
    }

    public MyContentProvider() {
        Log.e(TAG, "DatabaseProvider: ");
    }

    @Override
    public boolean onCreate() {
        // TODO: Implement this to initialize your content provider on startup.
        myDBHelpter = new DatabaseHelper(getContext(),"information",null,1);
        return false;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO: Implement this to handle requests to insert a new row.
        SQLiteDatabase db = myDBHelpter.getWritableDatabase();
        switch (uriMatcher.match(uri)){
            case USER_DIR:
            case USER_ITEM:
                //參數1:表名  參數2:沒有賦值的設為空   參數3:插入值
                long valuse = db.insert("information",null,values);
                break;
            default:
                break;
        }
        return null;
        //throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        SQLiteDatabase db = myDBHelpter.getWritableDatabase();
        int deleteInt = 0;
        //匹配uri
        switch (uriMatcher.match(uri)){
            case USER_DIR:
                //參數1:表名   參數2:約束刪除列的名字   參數3:具體行的值
                deleteInt = db.delete("information","id=?",selectionArgs);
                break;
            case USER_ITEM:
                String deletID = uri.getPathSegments().get(1);
                deleteInt = db.delete("information","id=?",new String[]{deletID});
                break;
            default:
        }
        return deleteInt;
        //throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        SQLiteDatabase db = myDBHelpter.getWritableDatabase();
        int updateRow = 0;
        switch (uriMatcher.match(uri)){
            case USER_DIR:
                updateRow = db.update("information",values,selection,selectionArgs);
                break;
            case USER_ITEM:
                String updateId = uri.getPathSegments().get(1);
                updateRow = db.update("information",values,"id=?",new String[]{updateId});
                break;
            default:
        }
        return updateRow;
        //throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // TODO: Implement this to handle query requests from clients.
        SQLiteDatabase db = myDBHelpter.getWritableDatabase();
        Cursor cursor = null;
        switch (uriMatcher.match(uri)){
            case USER_DIR:
                //參數1:表名  其他參數可借鑒上面的介紹
                cursor = db.query("information",projection,selection,selectionArgs,null,null,sortOrder);
                break;
            case USER_ITEM:
                String queryId = uri.getPathSegments().get(1);
                cursor = db.query("information",projection,"id=?",new String[]{queryId},null,null,sortOrder);
                break;
            default:
        }
        return cursor;
        //throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public 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");
    }
}

還有個數據庫DatabaseHelper

 
         
package com.example.app;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.*;

public class DatabaseHelper extends SQLiteOpenHelper {
private Context context;
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
super(context,name,factory,version);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) { //建表//帶全部參數的構造函數,此構造函數必不可少,name為數據庫名稱
db.execSQL("CREATE TABLE information(\n" +
" id INTEGER PRIMARY KEY NOT NULL,\n" +
" name TEXT NOT NULL,\n" +
" sex TEXT NOT NULL,\n" +
" class TEXT NOT NULL\n" +
" )");
db.execSQL("INSERT into information(id,name,sex,class) VALUES (202001,\"張三\",\"男\",\"嵌入式1班\");");
db.execSQL("INSERT into information(id,name,sex,class) VALUES (202002,\"王樂\",\"男\",\"嵌入式1班\");");
db.execSQL("INSERT into information(id,name,sex,class) VALUES (202003,\"劉小慧\",\"女\",\"網編1班\");");
}

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

}
//只有conCreate()和onUpgrade是抽象方法,所以重寫,


}
 

 

以上就是全部代碼

然后我把結構也放上來

 

 

 

 

 好了,這次就寫到這兒了,代碼以后再完善

 

加油!未來天天007!!!

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM