Android之contentProvider共享数据

Posted 非凡的静静

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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!!!

 

 

以上是关于Android之contentProvider共享数据的主要内容,如果未能解决你的问题,请参考以下文章

Android - IPC之ContentProvider简介

Android学习笔记之ContentProvider

Android之ContentProvider数据存储

Android之ContentProvider使用

Android安卓进阶技巧之——ContentProvider总结

Android面试四大组件之内容提供者ContentProvider