半期考试 二三题 (书籍维护 数据库)

Posted 春招进大厂的梦想家

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了半期考试 二三题 (书籍维护 数据库)相关的知识,希望对你有一定的参考价值。

结构:

主活动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">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="btnAdd"
        android:text="Add"
        tools:ignore="OnClick" />

</LinearLayout>

MainActivity2 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=".MainActivity2">


    <EditText
        android:id="@+id/book_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入书名:" />

    <EditText
        android:id="@+id/book_price"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入价格:"
        android:inputType="number"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <Button
                android:id="@+id/button_cancel"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:onClick="cancel"
                android:text="取消"
                tools:ignore="OnClick" />

        </LinearLayout>

        <Button
            android:id="@+id/button_ok"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="confirm"
            android:text="确定"
            tools:ignore="OnClick" />

    </LinearLayout>

</LinearLayout>

书籍实体类

package com.example.second;

import java.io.Serializable;

public class Book implements Serializable 
    private String bookName;
    private float bookPrice;
    private int bookID;

    public int getBookID() 
        return bookID;
    

    public void setBookID(int bookID) 
        this.bookID = bookID;
    
    public Book( String bookName, float bookPrice) 

        this.bookName = bookName;
        this.bookPrice = bookPrice;
    


    public Book(int bookID, String bookName, float bookPrice) 
        this.bookID = bookID;
        this.bookName = bookName;
        this.bookPrice = bookPrice;
    

    public String getBookName() 
        return bookName;
    

    public void setBookName(String bookName) 
        this.bookName = bookName;
    

    public float getBookPrice() 
        return bookPrice;
    

    public void setBookPrice(float bookPrice) 
        this.bookPrice = bookPrice;
    


数据库操作类:

package com.example.second;

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

import androidx.annotation.Nullable;

public class SQLHelper extends SQLiteOpenHelper 

    public static final String BookTable = "book";

    public SQLHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) 
        super(context, name, factory, version);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL("create table book(_id integer primary key autoincrement,name text,price text)");
    

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

    


主活动 .java

package com.example.second;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SimpleCursorAdapter;

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

public class MainActivity extends AppCompatActivity 


    private SimpleCursorAdapter adpter;
    private SQLiteDatabase db;
    private SQLHelper sqlHelper;
    private Cursor cursor;

    private ListView listView;
    private List<Book> bookList = new ArrayList<>();

    private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intent = new Intent(MainActivity.this,MainActivity2.class);
        listView = findViewById(R.id.listView);
        sqlHelper = new SQLHelper(this,"book.db",null,1);
        db = sqlHelper.getWritableDatabase();//创建数据库
        readDB();
        cursor = db.query("book",null,null,null,null,null,null);

        adpter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,new String[]"name","price",new int[]android.R.id.text1,android.R.id.text2, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listView.setAdapter(adpter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) 
                PopupMenu popupMenu = new PopupMenu(MainActivity.this, view);
                popupMenu.inflate(R.menu.main_menu);
                popupMenu.show();

                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() 
                    @Override
                    public boolean onMenuItemClick(MenuItem item) 
                        switch (item.getItemId())
                            case R.id.edit:
                                intent.putExtra("position",position);
                                intent.putExtra("bookToUpdate",bookList.get(position));
                                //  startActivityForResult(intent,1);
                                break;
                            case R.id.delete:
                                String bookName = bookList.get(position).getBookName();
                                db.delete(SQLHelper.BookTable,"name=?",new String[]bookName);
                                reload();
                                break;
                        
                        return true;
                    
                );
            
        );
    

    private void readDB()
        Cursor c = sqlHelper.getReadableDatabase().rawQuery("select * from book", null);
        int columnSize = c.getColumnCount();
        while(c.moveToNext())
            for(int i=0;i<columnSize;i++)
                bookList.add(new Book(c.getInt(0),c.getString(1),c.getFloat(2)));
            
        
    
    private void reload()
        Cursor cursor = db.query(SQLHelper.BookTable,null,null,null,null,null,null,null);
        adpter.swapCursor(cursor);
    

    public void btnAdd(View v)
        //Intent intent = new Intent(MainActivity.this,Main2Activity.class);
        startActivityForResult(intent,1);
    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode ==1)
            if(resultCode==RESULT_OK)
                Book book = (Book) data.getSerializableExtra("book");
                int position = (Integer)data.getIntExtra("position",0);
                if(book!=null)
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("name",book.getBookName());
                    contentValues.put("price",book.getBookPrice());

                    db.insert(SQLHelper.BookTable,null,contentValues);
                    reload();
                    readDB();
                
            
        
    

MainActivity2 .java

package com.example.second;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity2 extends AppCompatActivity 


    private EditText book_name;
    private EditText book_price;
    private int position;

    private  String bookName;
    private String bookPrice;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        book_name = findViewById(R.id.book_name);
        book_price = findViewById(R.id.book_price);
    

    public void cancel(View view) 
        book_name.setText("");
        book_price.setText("");
        // 结束当前窗口的生命周期
        finish();
    

    public void confirm(View v)

        bookName = book_name.getText().toString();
        bookPrice = book_price.getText以上是关于半期考试 二三题 (书籍维护 数据库)的主要内容,如果未能解决你的问题,请参考以下文章

半期考试 二三题 (书籍维护 数据库)

半期考试 二三题 (书籍维护 数据库)

半期考试之 SQLite操作

半期考试之 SQLite操作

半期考试 之 文件存储

半期考试 之 文件存储