contentProviderSample实现操作数据库

news/2024/7/5 6:40:06

contentProviderSample实现操作数据库并显示在listview控件中。

实现效果和上个实验相同:
点击进入上个实验
本实验在上个实验基础上完成,与上个实验包名略有不同,并且添加了ContentProvider.java文件、修改了MainActivity.java的代码。
ContentProvider.java代码:

package com.henu.contentprovider;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class ContentProvider extends android.content.ContentProvider {

    private MyHelper myHelper;
    private static final int INSERT = 1;
    private static final int DELETE = 2;
    //这里没有更新操作
   // private static final int UPDATE = 3;
    private static final int QUERY = 4;

    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        matcher.addURI("com.henu.rjxy.provider", "insert", INSERT);
        matcher.addURI("com.henu.rjxy.provider", "delete", DELETE);
   //     matcher.addURI("com.henu.rjxy.provider", "update", UPDATE);
        matcher.addURI("com.henu.rjxy.provider", "query", QUERY);

    }

    @Override
    public boolean onCreate() {
        myHelper = new MyHelper(getContext());
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        if (matcher.match(uri) == QUERY) {

            SQLiteDatabase db = myHelper.getReadableDatabase();
            Cursor cursor = db.query("information", null, null, null, null, null, null);
            return  cursor;
        }else {
            throw new IllegalArgumentException("路径不匹配,不能执行查询操作");
        }
    }

    @Nullable
    @Override
    //用不到
    public String getType(@NonNull Uri uri) {
        if (matcher.match(uri) ==QUERY ) {
            return  "vnd.android.cursor.dir/information";
        }
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        if(matcher.match(uri)==INSERT){
            SQLiteDatabase db = myHelper.getWritableDatabase();
            db.insert("information", null, values);
            db.close();
        }else {
            throw new IllegalArgumentException("路径不匹配,不能执行插入操作");
        }
        return uri;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        int no;
        if(matcher.match(uri)==DELETE){
            SQLiteDatabase db = myHelper.getWritableDatabase();
            no=db.delete("information", null, null);
            //删除自增主键id
            db.delete("sqlite_sequence", null, null);
            db.close();
        }else {
            throw new IllegalArgumentException("路径不匹配,不能执行插入操作");
        }
        return no;
    }

    @Override
      //用不到
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }
}

MainActivity.java文件代码:

package com.henu.contentprovider;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ListView viewById;
    private MyHelper myHelper;
    private SimpleCursorAdapter adapter;
    private Cursor cursor;
    //SimpleCursorAdapter所需要的参数
    String from[] = new String[]{"_id", "name", "age"};
    int[] to = new int[]{R.id.tv_id, R.id.tv_name, R.id.tv_age};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myHelper = new MyHelper(this);
        viewById = (ListView) findViewById(R.id.lv);
        //进入程序时显示数据库中的数据
        Show();
    }

    public void save(View v) {
        //获得可读数据库对象
       // SQLiteDatabase db = myHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        EditText et_name = (EditText) findViewById(R.id.et_name);
        EditText et_age = (EditText) findViewById(R.id.et_age);
        values.put("name", et_name.getText().toString().trim());
        values.put("age", et_age.getText().toString());
        //long q = db.insert("information", "name", values);
        Uri uri=Uri.parse("content://com.henu.rjxy.provider/insert");
        ContentResolver contentResolver=getContentResolver();
        contentResolver.insert(uri,values);
        Toast.makeText(this, "数据存入成功", Toast.LENGTH_SHORT).show();
        //数据库发生变化时更新listview
        Show();
    }


    /*
       当SQLite数据库中包含自增列时,会自动建立一个名为 sqlite_sequence 的表。

这个表包含两个列:name和seq。name记录自增列所在的表,seq记录当前序号(下一条记录的编号就是当前序号加1)。

如果想把某个自增列的序号归零,只需要修改 sqlite_sequence表就可以了。
        */
    public void clear(View v) {
       // SQLiteDatabase db = myHelper.getWritableDatabase();
        Uri uri=Uri.parse("content://com.henu.rjxy.provider/delete");
        ContentResolver contentResolver=getContentResolver();
        contentResolver.delete(uri, null, null);
        Toast.makeText(this, "数据库清除成功", Toast.LENGTH_SHORT).show();
        Show();
    }
    //显示数据
    public void Show() {
       ///SQLiteDatabase db = myHelper.getWritableDatabase();
        Uri uri=Uri.parse("content://com.henu.rjxy.provider/query");
        ContentResolver contentResolver=getContentResolver();
        cursor = contentResolver.query(uri,null,null,null,null);
        adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        viewById.setAdapter(adapter);
    }
}

清单文件加入的代码:
在application内部加入:

<provider
            android:name="com.henu.contentprovider.ContentProvider"
            android:authorities="com.henu.rjxy.provider"></provider>

实现效果:
在这里插入图片描述

清单文件:
在这里插入图片描述


http://www.niftyadmin.cn/n/3649776.html

相关文章

node.js入门_Node.js中的压缩入门

node.js入门Compression in Node.js and Express decreases the downloadable amount of data that’s served to users. Through the use of this compression, we can improve the performance of our Node.js applications as our payload size is reduced drastically. Nod…

跨域或者Internet访问Remoting[Remoting FAQ]

[Remoting FAQ]跨域或者Internet访问RemotingVersionDateCreatorDescription1.0.0.12006-6-1郑昀Ultrapower草稿继续阅读之前&#xff0c;我们假设您熟悉以下知识&#xff1a;n Remoting[需求]虽然说&#xff0c;Remoting一般都在同一个域内调用&#xff0c;但有时候&a…

Android自定义广播接收

Android自定义广播接收 实现效果&#xff1a; MainActivity.java代码&#xff1a; package com.henu.broadcastsample;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; im…

flutter顶部小部件_使用VoidCallback和Function(x)与Flutter进行小部件通信

flutter顶部小部件In this article we’re going to investigate how we can use callback-style events to communicate between widgets with Flutter. 在本文中&#xff0c;我们将研究如何使用Flutter在回调控件之间使用回调风格的事件进行通信。 Why is this important? …

[MSN谈话]专注、口碑和猎头

[网友]: 我原先做.NET WAP的&#xff0c;你的工作是做哪方面的我: 我什么都作。[网友]: 我觉得我做的算多的了&#xff0c;一看才知道&#xff0c;小巫见大巫了我: 移动增值领域我基本都涉及过。[网友]: 我从网络安全到对日外包&#xff0c;再到asp php网站开发之后.NET wap开发…

Python编写数字转换成中文大写

问题描述&#xff1a;输入一串数字金额&#xff0c;然后打印出它的中文大写。 利用列表下标进行转换。 list1 [零, 壹, 贰, 叁, 肆, 伍, 陆, 柒, 捌, 玖, 拾] list2 [圆, 拾, 佰, 仟, 萬]money str(int(input("请输入金额:"))) # 预防输入0开头的数字 money2 …

[推介]明朝的那些事儿-历史应该可以写得好看

无意连接到了一篇把历史讲述得格外精彩的贴子&#xff0c;号称天涯史上最强贴之一&#xff1a;http://cache.tianya.cn/publicforum/Content/no05/1/34523.shtml &#xff0c;《明朝的那些事儿&#xff0d;历史应该可以写得好看》&#xff0c;写得还真不错&#xff0c;引人入胜…

Python编写2-1000的回文素数

问题描述&#xff1a;找出2-1000的回文素数。 import math for i in range(2, 1001):for j in range(2, int(math.sqrt(i))):if i % j 0:breakelse:m str(i)if m[0] m[-1]:print("%d为回文素数" % i) Python中for循环和else是可以连用的&#xff0c;当for循环执…