首先要创建一个数据库 对其进行增 、删、改、查
这里 我先创建3个
1,适配器 (Recycleview ) (先在build.gradle里导包)
compile 'com.android.support:recyclerview-v7:26.1.0'
2,Maintivity;
3,创建数据库MySQLiteHelper
在Maintivity里 我们对数据库进行了创建表 和 数据库的查询,添加,随机
package com.example.myapplication13;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.myapplication13.adaper.Myadaper;
import com.example.myapplication13.db.MySQLiteHelper;
import com.example.myapplication13.entity.Myedityclass;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MySQLiteHelper myHelper;
private Button creat_btn;
private EditText edit_tianjia;
private Button btn_tianjia;
private RecyclerView recyclerView;
private Button suiji;
private Button quanbu;
private List myedityclassList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binID();
myHelper = new MySQLiteHelper(this, "student.db", null, 1);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
}
private void binID() {
creat_btn=findViewById(R.id.creat_btn);
edit_tianjia=findViewById(R.id.edit_tianjia);
btn_tianjia=findViewById(R.id.btn_tianjia);
recyclerView=findViewById(R.id.main_recyc_view);
suiji=findViewById(R.id.suiji);
quanbu=findViewById(R.id.quanbu);
creat_btn.setOnClickListener(this);
edit_tianjia.setOnClickListener(this);
btn_tianjia.setOnClickListener(this);
recyclerView.setOnClickListener(this);
suiji.setOnClickListener(this);
quanbu.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.creat_btn:
//创建表
myHelper.getWritableDatabase();
break;
case R.id.btn_tianjia:
SQLiteDatabase sqldb = myHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", edit_tianjia.getText().toString());
sqldb.insert("student", null, values);
Toast.makeText(MainActivity.this,"添加成功",Toast.LENGTH_SHORT).show();
break;
//列表里随机出现一条数据库信息
myedityclassList.clear();
SQLiteDatabase sqldb1 = myHelper.getReadableDatabase();
Cursor mcursor = sqldb1.query("student"+" ORDER BY RANDOM() LIMIT 1",null,null,null, null, null, null);
if (mcursor.moveToFirst()) {
//遍历
do {
String name = mcursor.getString(mcursor.getColumnIndex("name"));
int id = mcursor.getInt(mcursor.getColumnIndex("id"));
Log.e("MainActivity", "onClick: " + name);
Myedityclass myedityclass=new Myedityclass(name,id);
myedityclassList.add(myedityclass);
Myadaper adaper = new Myadaper(myedityclassList,MainActivity.this);
recyclerView.setAdapter(adaper);
} while (mcursor.moveToNext());
}
mcursor.close();
break;
case R.id.quanbu:
//全部显示数据库信息
myedityclassList.clear();
SQLiteDatabase sqldb2 = myHelper.getReadableDatabase();
Cursor mcursor1 = sqldb2.query("student",null,null,null, null, null, null);
if (mcursor1.moveToFirst()) {
//遍历
do {
String name = mcursor1.getString(mcursor1.getColumnIndex("name"));
int id = mcursor1.getInt(mcursor1.getColumnIndex("id"));
Log.e("MainActivity", "onClick: " + name);
Myedityclass myedityclass=new Myedityclass(name,id);
myedityclassList.add(myedityclass);
Myadaper adaper = new Myadaper(myedityclassList,MainActivity.this);
recyclerView.setAdapter(adaper);
} while (mcursor1.moveToNext());
}
mcursor1.close();
break;
default:
break;
}
}
}
xml布局:(这里我用的是recycleview来 获取查询)
<RelativeLayout 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"
android:orientation="vertical"
tools:context="com.example.myapplication13.MainActivity">
<Button
android:text="创建"
android:id="@+id/creat_btn"
android:layout_width="match_parent"
android:layout_height="50dp" />
<LinearLayout
android:layout_below="@id/creat_btn"
android:id="@+id/main22"
android:layout_gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp">
<EditText
android:background="@drawable/search_edit"
android:gravity="center"
android:hint="请输入添加内容"
android:id="@+id/edit_tianjia"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
/>
<Button
android:id="@+id/btn_tianjia"
android:text="添加"
android:layout_width="wrap_content"
android:layout_height="50dp" />
LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_recyc_view"
android:layout_below="@id/main22"
android:layout_above="@id/main_11"
>
android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_alignParentBottom="true"
android:id="@+id/main_11"
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:id="@+id/suiji"
android:text="随机显示"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="50dp" />
<Button
android:id="@+id/quanbu"
android:text="全部列出"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="50dp" />
LinearLayout>
RelativeLayout>
给Recycleview 一个行布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:layout_gravity="center"
android:gravity="center"
android:text="我是一只小小鸟"
android:background="@drawable/title_bg"
android:id="@+id/edit_name"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="40dp"
android:textSize="20dp" />
<Button
android:id="@+id/btn_delet"
android:layout_width="60dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:text="删除" />
<Button
android:id="@+id/btn_xiugai"
android:layout_width="60dp"
android:layout_height="50dp"
android:text="修改" />
LinearLayout>
效果图:
创建数据库的类 继承SQLiteOpenHelper:
package com.example.myapplication13.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
/**
* Created by lenovo on 2018/3/27.
*/
public class MySQLiteHelper extends SQLiteOpenHelper {
private String createSQL = "create table student(" +
"id integer primary key autoincrement not null ," +
"name text )";
private Context context;
public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(createSQL);
Toast.makeText(context,"成功",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
在适配器里面 填写 数据库的删除与修改:
package com.example.myapplication13.adaper;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication13.MainActivity;
import com.example.myapplication13.db.MySQLiteHelper;
import com.example.myapplication13.R;
import com.example.myapplication13.entity.Myedityclass;
import java.util.List;
import static android.content.ContentValues.TAG;
/**
* Created by lenovo on 2018/3/27.
*/
public class Myadaper extends RecyclerView.Adapter.ViewHolder> {
private List qmyedityclassList;
private Context context;
public Myadaper(List myedityclassList, Context context) {
this.qmyedityclassList = myedityclassList;
this.context = context;
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView edit_name;
Button btn_delet;
Button btn_xiugai;
public ViewHolder(View itemView) {
super(itemView);
edit_name = itemView.findViewById(R.id.edit_name);
btn_delet = itemView.findViewById(R.id.btn_delet);
btn_xiugai = itemView.findViewById(R.id.btn_xiugai);
}
}
@Override
public Myadaper.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(Myadaper.ViewHolder holder, final int position) {
Myedityclass myedityclass = qmyedityclassList.get(position);
holder.edit_name.setText(myedityclass.getName());
holder.btn_delet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inint(position);
}
private void inint(final int position) {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
builder.setTitle("删除提醒");
builder.setMessage("你确定要删除" + qmyedityclassList.get(position).getName() + "吗");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MySQLiteHelper mySQLiteHelper = new MySQLiteHelper(context, "student.db", null, 1);
SQLiteDatabase sqLiteDatabase = mySQLiteHelper.getWritableDatabase();
sqLiteDatabase.delete("student", "name=?", new String[]{qmyedityclassList.get(position).getName()});
qmyedityclassList.remove(position);
notifyDataSetChanged();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
});
holder.btn_xiugai.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
imimt(position);
}
private void imimt(final int position) {
final EditText editText = new EditText(context);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("修改" + qmyedityclassList.get(position).getName());
builder.setView(editText);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MySQLiteHelper mySQLiteHelper = new MySQLiteHelper(context, "student.db", null, 1);
SQLiteDatabase sqLiteDatabase = mySQLiteHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", editText.getText().toString());
sqLiteDatabase.update("student", values, "name=?", new String[]{qmyedityclassList.get(position).getName()});
qmyedityclassList.get(position).setName(editText.getText().toString());
notifyDataSetChanged();
Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
});
}
@Override
public int getItemCount() {
return qmyedityclassList.size();
}
}
实现的效果如图:
我们通过一个类 来继承ContentProvider 并且实现它的6个方法:
1,onCreate()
初始化内容提供器的时候调用,通常会这里完成数据库的创建和升级等操作,返回true表示内容提供器初始化成功,返回false则表示失败。
2,query()
从内容提供器中查询数据。使用uri参数来确定查询哪些行,sortOrder参数用于对结果进行排序。查询的结果存放阿紫Cursor对象中返回。
3,insert()
向内容提供器中添加一条数据,使用uri参数来确定要添加到的表,待添加的数据保存在valus参数中,添加完成后,返回一个用于表示这条新记录的URL。
4,update()
更新内容提供器中已有的数据。使用uri参数来确定更新安一张表中的数据,新数据保存在values参数中,selection和selectionArg参数用于约束更新哪些行,受影响的行数将作为返回值返回。
5,delete()
从内容提供器中删除数据。使用uri参数来确定删除哪一张表中的数据,selection和selectionArgs参数用于约束删除哪些行,被删除的行数将作为返回值返回。
6,getType()
根据传入的内容uri来返回相应的MIME类型。
通过AndroidManifest.xml 里写一个provider标签,来验证两个app之间的链接
<provider
android:name=".DatabaseProvider"
android:authorities="com.lenovo.studentdemo.provider"
android:enabled="true"
android:exported="true" />
在此app里创建一个类来继承 ContentProvider:
package com.example.myapplication13;
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.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.example.myapplication13.db.MySQLiteHelper;
import com.example.myapplication13.entity.Myedityclass;
import java.util.List;
import static android.content.ContentValues.TAG;
public class DatabaseProvider extends ContentProvider {
public static final int STUDENT=0;
public static final int STUDENT_ITEM=1;
public static final int TEACHER=2;
public static final int TEACHER_ITEM=3;
private static final String AUTHORITY="com.lenovo.studentdemo.provider";
private static UriMatcher uriMatcher;
private MySQLiteHelper mySQLiteHelperl;
static {
uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY,"student",STUDENT);
uriMatcher.addURI(AUTHORITY,"student",STUDENT_ITEM);
uriMatcher.addURI(AUTHORITY,"student",TEACHER);
uriMatcher.addURI(AUTHORITY,"student",TEACHER_ITEM);
}
@Override
public boolean onCreate() {
Log.e(TAG, "onCreate: "+"************" );
return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
Log.e(TAG, "query: "+"************" );
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
Log.e(TAG, "getType: "+"************" );
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
switch (uriMatcher.match(uri)){
case STUDENT:
MySQLiteHelper mySQLiteHelper=new MySQLiteHelper(getContext(),"student.db",null,1);
SQLiteDatabase sqldb = mySQLiteHelper.getWritableDatabase();
sqldb.insert("student", null, contentValues);
break;
case STUDENT_ITEM:
break;
case TEACHER:
break;
case TEACHER_ITEM:
break;
}
return null;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
MySQLiteHelper mySQLiteHelper = new MySQLiteHelper(getContext(), "student.db", null, 1);
SQLiteDatabase sqLiteDatabase = mySQLiteHelper.getWritableDatabase();
sqLiteDatabase.delete("student",s ,strings);
return 0;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
return 0;
}
}
再创建一个app 定义两个button 和一个修改editview :
package com.example.myapplication17;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText ed_create;
private Button delete_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button_btn);
ed_create=findViewById(R.id.ed_create);
delete_btn=findViewById(R.id.delete_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name=ed_create.getText().toString();
Uri uri=Uri.parse("content://com.lenovo.studentdemo.provider");
ContentResolver resolver=getContentResolver();
ContentValues contentValues=new ContentValues();
contentValues.put("name",name);
resolver.insert(uri,contentValues);
}
});
delete_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name=ed_create.getText().toString();
Uri uri=Uri.parse("content://com.lenovo.studentdemo.provider");
ContentResolver resolver=getContentResolver();
resolver.delete(uri,"name=?",new String[]{name});
}
});
}
}
xml 图:
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.myapplication17.MainActivity">
<EditText
android:id="@+id/ed_create"
android:layout_width="match_parent"
android:layout_height="50dp"
/>
<Button
android:id="@+id/button_btn"
android:text="添加"
android:layout_width="match_parent"
android:layout_height="50dp" />
<Button
android:layout_marginTop="50dp"
android:id="@+id/delete_btn"
android:text="删除"
android:layout_width="match_parent"
android:layout_height="50dp" />
LinearLayout>
实现效果为: