android开发_004:从SQLite读取数据到RecyclerView,并实现多表查询

使用RecyclerView要添加依赖,上篇文章有方法:https://blog.csdn.net/zzq1824837536/article/details/80349498

建立数据库  MyDatabaseHelper.java

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class MyDatabaseHelper extends SQLiteOpenHelper {
    /*integer 整型,real 浮点型,primary key 主键,autoincrement 自增长,text 文本类型,blob 二进制数,*/
    public static final String CREATE_BOOK="create table Book("
        +"id integer primary key autoincrement,"
            +"author text,"
            +"price real,"
            +"pages integer,"+
            "name text)";
    public static final String CREATE_CATEGORY="create table Category("
            +"id integer primary key autoincrement,"
            +"category_name text,"
            +"category_code integer)";
    private Context mContext;

    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext=context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_BOOK);
        sqLiteDatabase.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext,"create success!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("drop table if exists Book");
        sqLiteDatabase.execSQL("drop table if exists Category");
        onCreate(sqLiteDatabase);
    }

}

RecyclerView 适配布局 book_item.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="wrap_content">

    <TextView
        android:id="@+id/book_id"
        android:gravity="center"
        android:layout_weight="1"
        android:text="序号"
        android:layout_width="0dp"
        android:layout_height="50dp" />
    <TextView
        android:id="@+id/book_name"
        android:gravity="center"
        android:layout_weight="1"
        android:text="书名"
        android:layout_width="0dp"
        android:layout_height="50dp" />
    <TextView
        android:id="@+id/book_author"
        android:gravity="center"
        android:layout_weight="1"
        android:text="作者"
        android:layout_width="0dp"
        android:layout_height="50dp" />
    <TextView
        android:id="@+id/book_pages"
        android:gravity="center"
        android:layout_weight="1"
        android:text="页数"
        android:layout_width="0dp"
        android:layout_height="50dp" />
    <TextView
        android:id="@+id/book_price"
        android:gravity="center"
        android:layout_weight="1"
        android:text="价格"
        android:layout_width="0dp"
        android:layout_height="50dp" />
    <TextView
        android:id="@+id/category_name"
        android:gravity="center"
        android:layout_weight="2"
        android:text="种类"
        android:layout_width="0dp"
        android:layout_height="50dp" />
    <TextView
        android:id="@+id/category_code"
        android:gravity="center"
        android:layout_weight="1"
        android:text="编号"
        android:layout_width="0dp"
        android:layout_height="50dp" />

</LinearLayout>

RecyclerView 布局文件 activity_main.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">

    <include layout="@layout/book_item">

    </include>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/Recycler_View"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

显示对象javaBean BookStore.java

public class BookStore {
    private int id;
    private String name;
    private String author;
    private int pages;
    private double price;
    private String category_name;
    private int category_code;

    public BookStore(int id, String name, String author, int pages, double price,String category_name,int category_code){
        this.id=id;
        this.name=name;
        this.author=author;
        this.pages=pages;
        this.price=price;
        this.category_name=category_name;
        this.category_code=category_code;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getAuthor() {
        return author;
    }

    public int getPages() {
        return pages;
    }

    public double getPrice() {
        return price;
    }

    public String getCategory_name() {
        return category_name;
    }

    public int getCategory_code() {
        return category_code;
    }
}

RecyclerView适配器  BookAdapter.java

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder>{
    private List<BookStore> mList;

    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView book_id;
        TextView book_name;
        TextView book_author;
        TextView book_pages;
        TextView book_price;
        TextView category_name;
        TextView category_code;
        public ViewHolder(View view){
            super(view);
            book_id=(TextView)view.findViewById(R.id.book_id);
            book_name=(TextView)view.findViewById(R.id.book_name);
            book_author=(TextView)view.findViewById(R.id.book_author);
            book_pages=(TextView)view.findViewById(R.id.book_pages);
            book_price=(TextView)view.findViewById(R.id.book_price);
            category_name=(TextView)view.findViewById(R.id.category_name);
            category_code=(TextView)view.findViewById(R.id.category_code);
        }
    }
    public BookAdapter(List<BookStore>bookStoresList){
        mList=bookStoresList;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.book_item,parent,false);
        ViewHolder holder=new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        BookStore bookStore=mList.get(position);
        holder.book_id.setText(String.valueOf(bookStore.getId()));
        holder.book_name.setText(bookStore.getName());
        holder.book_author.setText(bookStore.getAuthor());
        holder.book_pages.setText(String.valueOf(bookStore.getPages()));
        holder.book_price.setText(String.valueOf(bookStore.getPrice()));
        holder.category_name.setText(bookStore.getCategory_name());
        holder.category_code.setText(String.valueOf(bookStore.getCategory_code()));
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }


}

主页面布局文件activity_main2.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/Create_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="创建数据库"
        />

    <Button
        android:id="@+id/Add_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加数据"
        />

    <Button
        android:id="@+id/Update_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="更新数据"/>

    <Button
        android:id="@+id/Delete_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除数据"/>

    <Button
        android:id="@+id/Query_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询数据"/>
</LinearLayout>

启动活动Main2Activity.java

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class Main2Activity extends AppCompatActivity {
    private Button bt1,bt2,bt3,bt4,bt5;
    private MyDatabaseHelper databaseHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        databaseHelper=new MyDatabaseHelper(this,"BookStore.db",null,2);
        setContentView(R.layout.activity_main2);
        bt1=(Button)findViewById(R.id.Create_button);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                databaseHelper.getWritableDatabase();//先检测程序中有无这个数据库,如果没有,则创建
            }
        });
        bt2=(Button)findViewById(R.id.Add_button);
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db=databaseHelper.getWritableDatabase();
                ContentValues values=new ContentValues();//获取ContentValues对象
                values.put("name","The Da Code");
                values.put("author","Dan");
                values.put("pages",454);
                values.put("price",46.69);
                db.insert("Book",null,values);//插入第一条数据
                values.clear();

                values.put("name","The Lost Symbol");
                values.put("author","Lost");
                values.put("pages",996);
                values.put("price",82.65);
                db.insert("Book",null,values);//插入第二条数据
                values.clear();

                values.put("name","Thinking");
                values.put("author","Dell");
                values.put("pages",4516);
                values.put("price",100.65);
                db.insert("Book",null,values);//插入第三条数据
                values.clear();

                values.put("category_name","computer");
                values.put("category_code",156);
                db.insert("Category",null,values);
                values.clear();

                values.put("category_name","animal");
                values.put("category_code",456);
                db.insert("Category",null,values);
            }
        });
        bt3=(Button)findViewById(R.id.Update_button);
        bt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db=databaseHelper.getWritableDatabase();
                ContentValues values=new ContentValues();
                values.put("price",10.99);
                db.update("Book",values,"name=?",new String[]{"The Da Code"});
            }
        });
        bt4=(Button)findViewById(R.id.Delete_button);
        bt4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db=databaseHelper.getWritableDatabase();
                db.delete("Book","pages > ?",new String[]{"500"});//删除页数超过500的书
            }
        });
        bt5=(Button)findViewById(R.id.Query_button);
        bt5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                SQLiteDatabase db=databaseHelper.getWritableDatabase();//获取数据库对象
//                Cursor cursor=db.query("Book",null,null,null,null,null,null);//查询Book表中的所有数据
//                if(cursor.moveToFirst()){
//                    do{
//                        String name=cursor.getString(cursor.getColumnIndex("name"));
//                        String author=cursor.getString(cursor.getColumnIndex("author"));
//                        int pages=cursor.getInt(cursor.getColumnIndex("pages"));
//                        double price=cursor.getDouble(cursor.getColumnIndex("price"));
//                        Log.d("MainActivity","Book name is:"+name);
//                        Log.d("MainActivity","Book author is:"+author);
//                        Log.d("MainActivity","Book page is:"+pages);
//                        Log.d("MainActivity","Book price is:"+price);
//                    }while(cursor.moveToNext());
//                }
//                cursor.close();
                Intent intent=new Intent(Main2Activity.this,MainActivity.class);
                startActivity(intent);
            }
        });
    }
}

数据显示界面 MainActivity.java

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<BookStore> BookList=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initBook();
        RecyclerView recyclerView=(RecyclerView)findViewById(R.id.Recycler_View);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        BookAdapter bookAdapter=new BookAdapter(BookList);
        recyclerView.setAdapter(bookAdapter);
    }
    private void initBook(){
        String sqlSelect="SELECT * FROM Book INNER JOIN Category ON Book.id=Category.id  ";
        //扫描数据库,将信息放入booklist
        MyDatabaseHelper mdb = new MyDatabaseHelper(this, "BookStore.db", null, 2);//打开数据库
        SQLiteDatabase sd = mdb.getReadableDatabase();//获取数据库
        Cursor cursor=sd.rawQuery(sqlSelect,new String[]{});
        while(cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex("id"));
            String name=cursor.getString(cursor.getColumnIndex("name"));
            String author=cursor.getString(cursor.getColumnIndex("author"));
            int pages=cursor.getInt(cursor.getColumnIndex("pages"));
            double price=cursor.getDouble(cursor.getColumnIndex("price"));
            String category_name=cursor.getString(cursor.getColumnIndex("category_name"));
            int category_code=cursor.getInt(cursor.getColumnIndex("category_code"));
            BookStore bookStore=new BookStore(id,name,author,pages,price,category_name,category_code);
            BookList.add(bookStore);
        }
        cursor.close();

    }
}

运行截图:


  • 20
    点赞
  • 78
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您想了解关于使用Android Studio实现SQLite数据库操作、SharedPreferences存储数据和文件存储的具体步骤,我可以为您提供一些指导。 首先,我们需要在Android Studio中创建一个新的项目。然后,在项目的build.gradle文件中添加以下依赖项: ```groovy dependencies { implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'androidx.constraintlayout:constraintlayout:2.1.0' implementation 'androidx.recyclerview:recyclerview:1.2.1' implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.preference:preference:1.1.1' } ``` 然后,在layout文件夹中创建一个布局文件,用于显示SQLite数据和SharedPreferences数据。在这个布局文件中,您可以使用RecyclerView和CardView组件来显示SQLite数据,使用PreferenceFragment组件来显示SharedPreferences数据。 接下来,我们可以通过以下步骤来创建SQLite数据库并执行增删改查操作: 1. 定义数据库架构:我们需要定义数据库的表和列,以及它们的数据类型和约束。 2. 创建数据库帮助类:我们需要创建一个类,继承自SQLiteOpenHelper,并实现onCreate()和onUpgrade()方法。onCreate()方法用于创建数据库和表,onUpgrade()方法用于升级数据库版本。 3. 执行增删改查操作:我们可以使用SQLiteDatabase类的insert()、delete()、update()和query()方法来执行增删改查操作。 以下是一个示例代码,用于创建SQLite数据库并执行增删改查操作: ```java public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "mydb.db"; private static final int DATABASE_VERSION = 1; private static final String TABLE_NAME = "mytable"; private static final String COLUMN_ID = "id"; private static final String COLUMN_NAME = "name"; private static final String COLUMN_AGE = "age"; private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_AGE + " INTEGER)"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } public boolean insertData(String name, int age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_NAME, name); values.put(COLUMN_AGE, age); long result = db.insert(TABLE_NAME, null, values); return result != -1; } public Cursor getAllData() { SQLiteDatabase db = this.getWritableDatabase(); return db.rawQuery("SELECT * FROM " + TABLE_NAME, null); } public boolean updateData(String id, String name, int age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_ID, id); values.put(COLUMN_NAME, name); values.put(COLUMN_AGE, age); int result = db.update(TABLE_NAME, values, "id=?", new String[]{id}); return result > 0; } public boolean deleteData(String id) { SQLiteDatabase db = this.getWritableDatabase(); int result = db.delete(TABLE_NAME, "id=?", new String[]{id}); return result > 0; } } ``` 接下来,我们可以使用以下代码来执行SQLite数据库的增删改查操作: ```java DatabaseHelper dbHelper = new DatabaseHelper(this); // 插入数据 dbHelper.insertData("Tom", 20); // 查询数据 Cursor cursor = dbHelper.getAllData(); while (cursor.moveToNext()) { String id = cursor.getString(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.d("TAG", "id: " + id + ", name: " + name + ", age: " + age); } // 更新数据 dbHelper.updateData("1", "Jerry", 21); // 删除数据 dbHelper.deleteData("1"); ``` 接下来,我们可以使用以下步骤来实现SharedPreferences的存储数据: 1. 获取SharedPreferences对象:我们可以通过Context类的getSharedPreferences()方法或PreferenceManager类的getDefaultSharedPreferences()方法来获取SharedPreferences对象。 2. 编辑SharedPreferences对象:我们可以使用SharedPreferences.Editor类的putString()、putInt()、putBoolean()等方法来编辑SharedPreferences对象。 3. 提交SharedPreferences编辑:我们可以使用SharedPreferences.Editor类的commit()或apply()方法来提交SharedPreferences编辑。 以下是一个示例代码,用于实现SharedPreferences的存储数据: ```java SharedPreferences sharedPreferences = getSharedPreferences("my_preferences", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("name", "Tom"); editor.putInt("age", 20); editor.commit(); ``` 最后,我们可以使用以下步骤来实现文件存储: 1. 获取文件的输入输出流:我们可以使用Context类的openFileInput()和openFileOutput()方法来获取文件的输入输出流。 2. 写入文件数据:我们可以使用输出流将数据写入文件。 3. 读取文件数据:我们可以使用输入流将数据从文件读取出来。 以下是一个示例代码,用于实现文件存储: ```java String fileName = "my_file"; String content = "Hello World"; // 写入文件数据 try { FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE); fos.write(content.getBytes()); fos.close(); } catch (IOException e) { e.printStackTrace(); } // 读取文件数据 try { FileInputStream fis = openFileInput(fileName); byte[] buffer = new byte[1024]; int len = fis.read(buffer); String result = new String(buffer, 0, len); fis.close(); Log.d("TAG", "file content: " + result); } catch (IOException e) { e.printStackTrace(); } ``` 以上就是关于使用Android Studio实现SQLite数据库操作、SharedPreferences存储数据和文件存储的详细步骤,如果您有任何问题或疑问,请随时向我提出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值