當(dāng)前位置:首頁 > IT技術(shù) > 移動平臺 > 正文

android使用SQlite數(shù)據(jù)庫存儲書名和作者
2021-09-16 11:41:31

實(shí)現(xiàn)效果圖:

?

(1)activity_main

?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bookname">
    </EditText>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bookauthor">
    </EditText>

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/booklist">
    </ListView>
</LinearLayout>

(3)MainActivity

?

public class MainActivity extends AppCompatActivity implements OnItemClickListener{

    private BookDB mBookDB;
    private Cursor mCursor;
    private EditText bookName;
    private EditText bookAuthor;
    private ListView bookList;
    private int BOOK_ID=0;

    private static final int MENU_ADD = Menu.FIRST;
    private static final int MENU_DELETE = Menu.FIRST+1;
    private static final int MENU_UPDATE = Menu.FIRST+2;



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(Menu.NONE, MENU_ADD, 0, "ADD");
        menu.add(Menu.NONE, MENU_DELETE, 0, "DELETE");
        menu.add(Menu.NONE, MENU_UPDATE, 0, "UPDATE");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        super.onOptionsItemSelected(item);
        switch(item.getItemId()){
            case MENU_ADD:
                add();
                break;
            case MENU_DELETE:
                delete();
                break;
            case MENU_UPDATE:
                update();
                break;

        }
        return true;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sqlite_activity);
        setUpViews();
    }
    public void setUpViews(){
        mBookDB = new BookDB(this);
        //進(jìn)入這個界面 直接查詢數(shù)據(jù)庫
        mCursor = mBookDB.select();

        bookName = (EditText)findViewById(R.id.bookname);
        bookAuthor = (EditText)findViewById(R.id.bookauthor);
        bookList  = (ListView)findViewById(R.id.booklist);
//     System.out.println(bookName);
//     System.out.println(bookAuthor);
//     System.out.println(bookList);
        BookListAdapter adapter =  new BookListAdapter(SQLiteDatabaseDemo.this,mCursor);
        bookList.setAdapter(adapter);

        bookList.setOnItemClickListener(SQLiteDatabaseDemo.this);

    }

    //listview點(diǎn)擊事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        mCursor.moveToPosition(position);
        BOOK_ID = mCursor.getInt(0);
        bookName.setText(mCursor.getString(1));
        bookAuthor.setText(mCursor.getString(2));

    }

    public void add(){
        //獲取輸入的內(nèi)容
        String bookname = bookName.getText().toString();
        String author = bookAuthor.getText().toString();

        if(bookname.equals("")||author.equals("")) return;


        mBookDB.add(bookname, author);
        //Requery 方法是通過重新查詢窗體或控件的數(shù)據(jù)源更新基于指定窗體的數(shù)據(jù)
        mCursor.requery();
        //對listview自動刷新
        bookList.invalidateViews();
        bookName.setText("");
        bookAuthor.setText("");
        Toast.makeText(this, "add success", Toast.LENGTH_SHORT).show();


    }
    public void delete(){
        String bookname = bookName.getText().toString();
        String author = bookAuthor.getText().toString();
        if(BOOK_ID == 0) return;
        mBookDB.delete(BOOK_ID);
        mCursor.requery();
        // //對listview自動刷新
        bookList.invalidateViews();
        bookName.setText("");
        bookAuthor.setText("");
        Toast.makeText(this, "delete success", Toast.LENGTH_SHORT).show();
    }
    public void update(){
        String bookname = bookName.getText().toString();
        String author = bookAuthor.getText().toString();
        if(bookname.equals("")||author.equals("")) return;
        mBookDB.update(BOOK_ID, bookname, author);
        mCursor.requery();
        bookList.invalidateViews();
        bookName.setText("");
        bookAuthor.setText("");
        Toast.makeText(this, "update success", Toast.LENGTH_SHORT).show();


    }
    public class BookListAdapter extends BaseAdapter{
        private Context mContext;
        private Cursor mCursor;
        public BookListAdapter(Context context,Cursor cursor){
            mContext = context;
            mCursor = cursor;
        }
        @Override
        public int getCount() {
            //數(shù)據(jù)庫數(shù)據(jù)條目
            return mCursor.getCount();
        }
        @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) {
            mCursor.moveToPosition(position);
            TextView mTextView = new TextView(mContext);
            mTextView.setText("序號"+mCursor.getString(1)+"內(nèi)容"+mCursor.getString(2));
            return mTextView;
        }
    }

}

(1)數(shù)據(jù)庫工具類BookDB

?

public class BookDB extends SQLiteOpenHelper{
    //數(shù)據(jù)庫名稱
    private final static String DATABASE_NAME = "BOOKS.db";
    //數(shù)據(jù)庫版本號
    private final static int DATABASSE_VERSION=1;
    //表名
    private final static String TABLE_NAME = "books_table";
    //書籍名稱
    private final static String BOOK_NAME = "book_name";
    ///書籍的id
    private final static String BOOK_ID = "book_id";
    //作者
    private final static String BOOK_AUTHOR = "book_author";

    //構(gòu)造方法
    public BookDB(Context context) {
        //上下文   數(shù)據(jù)庫名稱  工廠類  數(shù)據(jù)庫的版本號
        super(context, DATABASE_NAME,null,DATABASSE_VERSION);

    }

    //第一次進(jìn)來  如果沒有 則創(chuàng)建數(shù)據(jù)庫  如果有就打開
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE "+ TABLE_NAME+" ("+BOOK_ID+
                " INTEGER primary key autoincrement,"+BOOK_NAME+" text,"+BOOK_AUTHOR+" text);";
        //執(zhí)行數(shù)據(jù)庫
         db.execSQL(sql);
    }

    //數(shù)據(jù)庫更新
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "DROP TABLE IF EXISTS "+TABLE_NAME;
        db.execSQL(sql);
        onCreate(db);

    }

    //查詢數(shù)據(jù)庫內(nèi)容
    public Cursor select(){
        //申請數(shù)據(jù)庫的權(quán)限 讀寫
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
        return cursor;


    }

    //添加
    public long add(String bookname,String author){
        SQLiteDatabase db = this.getWritableDatabase();
        //添加數(shù)據(jù)  鍵值對
        ContentValues cv =new ContentValues();
        cv.put(BOOK_NAME, bookname);
        cv.put(BOOK_AUTHOR, author);

        long row = db.insert(TABLE_NAME, null, cv);
        return row;

    }

    //根據(jù)id刪除
    public void delete(int id){
        SQLiteDatabase db = this.getWritableDatabase();
        String where = BOOK_ID+ "=?";
        String[] whereValue = {Integer.toString(id)};
        db.delete(TABLE_NAME, where, whereValue);

    }
    //更新
    public void update(int id,String bookname,String bookauthor){
        SQLiteDatabase db =this.getWritableDatabase();
        ContentValues cv =new ContentValues();
        cv.put(BOOK_NAME, bookname);
        cv.put(BOOK_AUTHOR, bookauthor);
        String where = BOOK_ID+"=?";
        String[] whereValue = {Integer.toString(id)};
        db.update(TABLE_NAME, cv, where, whereValue);

    }

}

?

?

?



本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務(wù)立即開通 >