目录结构如下:
java代码>> Book.java BookActivity.java BookAdapter.java MainActivity.java MyDatabaseHelper.java UpdateBookActivity.javalayout>> activity_book.xml activity_main.xml activity_update_book.xml book_item.xml
Book.java
package com.example.p229;import java.io.Serializable;public class Book implements Serializable{ private int id; private String author; private double price; private int pages; private String name; public Book(int id, String author, double price, int pages, String name) { super(); this.id = id; this.author = author; this.price=price; this.pages = pages; this.name = name; } public Book(String author, double price, int pages, String name) { super(); this.author = author; this.price=price; this.pages = pages; this.name = name; } public Book() { super(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; }}
BookActivity
package com.example.p229;import android.content.DialogInterface;import android.content.Intent;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.preference.DialogPreference;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.ButtonBarLayout;import android.util.Log;import android.view.View;import android.widget.AdapterView;import android.widget.Button;import android.widget.ListView;import android.widget.Toast;import java.util.ArrayList;import java.util.List;public class BookActivity extends AppCompatActivity { private List<Book> bookList = new ArrayList<>(); private ListView lv_book; private MyDatabaseHelper dbhelper; private Button data_clear; private BookAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book); dbhelper = new MyDatabaseHelper(this, "BookStore.db", null, 1); //给数据源赋值 initBooks(); //创建适配器 //获取列表并设置适配器 lv_book = (ListView) findViewById(R.id.lv_book); if (adapter == null) { adapter = new BookAdapter(BookActivity.this, R.layout.book_item, bookList); lv_book.setAdapter(adapter); } else { adapter.notifyDataSetChanged(); } //短时间选中该书触发的事件———弹出修改对话框 lv_book.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Book book = bookList.get(position); showBookInfoDialog(book); // Toast.makeText(BookActivity.this,book.getName(),Toast.LENGTH_SHORT).show(); } }); //长时间选中该书触发的事件———弹出删除对话框 lv_book.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Book book = bookList.get(position); //Toast.makeText(BookActivity.this,book.getName(),Toast.LENGTH_SHORT).show(); showDeleteInfoDialog(book); return false; } }); data_clear = (Button) findViewById(R.id.data_clear); data_clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clear(); } }); } @Override protected void onResume() { super.onResume(); initBooks(); } protected void showBookInfoDialog(final Book book) { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setIcon(R.mipmap.ic_launcher); dialog.setTitle("图书信息"); dialog.setMessage("" + "id:" + book.getId() + "\n作者:" + book.getAuthor() + "\n单价:" + book.getPrice() + "\n页数:" + book.getPages() + "\n书名:" + book.getName() ); dialog.setPositiveButton("修改", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //由当前活动跳转到UpdateBookActivity活动,病传递数据book Intent intent=new Intent(BookActivity.this,UpdateBookActivity.class); intent.putExtra("book",book); startActivity(intent); } }); dialog.setNegativeButton("取消", null); dialog.show(); } protected void showDeleteInfoDialog(final Book book) { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setIcon(R.mipmap.ic_launcher); dialog.setTitle("提示信息"); dialog.setMessage("请问您要删除这条数据吗"); dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //删除图书,首先从数据课表中删除,其次从集合中删除,目的就是让lv能同步显示删除后的状态或结果 SQLiteDatabase db=dbhelper.getWritableDatabase(); int count=db.delete("Book","id=?",new String[]{book.getId()+""}); if(count!=0){ Toast.makeText(BookActivity.this, "数据库中删除成功!!", Toast.LENGTH_SHORT).show(); bookList.remove(book); adapter.notifyDataSetChanged(); } else{ Toast.makeText(BookActivity.this, "没有删除!!", Toast.LENGTH_SHORT).show(); } db.close(); } }); dialog.setNegativeButton("取消", null); dialog.show(); } public void clear() { SQLiteDatabase db = dbhelper.getWritableDatabase(); int count = db.delete("Book", null, null); if (count!= 0) { Toast.makeText(this, "数据库表删除成功!!", Toast.LENGTH_SHORT).show(); bookList.clear(); adapter.notifyDataSetChanged(); } else { Toast.makeText(this, "没有内容可以删除!!", Toast.LENGTH_SHORT).show(); } db.close(); } private void initBooks() { SQLiteDatabase db = dbhelper.getWritableDatabase(); bookList.clear(); //给数据源赋值 Cursor cursor = db.query("Book", null, null, null, null, null, null); //2.进行遍历 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"));// int id=cursor.getInt(cursor.getColumnIndex("id"));// double price=cursor.getDouble(cursor.getColumnIndex("price")); //id列的索引号为0 int id = cursor.getInt(0); String author = cursor.getString(cursor.getColumnIndex("author")); double price = cursor.getDouble(cursor.getColumnIndex("price")); int pages = cursor.getInt(cursor.getColumnIndex("pages")); String name = cursor.getString(cursor.getColumnIndex("name")); //Book book=new Book(id,author,price,pages,name); Book book = new Book(); book.setId(id); book.setName(name); book.setPages(pages); book.setPrice(price); book.setAuthor(author); bookList.add(book); } while (cursor.moveToNext()); } // 3.关闭游标 cursor.close(); db.close(); }}
BookAdapter
package com.example.p229;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import java.util.List;public class BookAdapter extends ArrayAdapter<Book> { private int resourceId; public BookAdapter(Context context, int resource, List<Book> objects) { super(context, resource, objects); resourceId = resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { Book book = getItem(position); View view; ViewHolder viewHolder; if (convertView == null) { //是否有布局缓存,否 view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false); //创建viewHolder viewHolder = new ViewHolder(); //获取ViewHolder的控件 viewHolder.bookId = (TextView) view.findViewById(R.id.book_id); viewHolder.bookAuthor = (TextView) view.findViewById(R.id.book_author); viewHolder.bookPrice = (TextView) view.findViewById(R.id.book_price); viewHolder.bookPages = (TextView) view.findViewById(R.id.book_pages); viewHolder.bookName = (TextView) view.findViewById(R.id.book_name); //将viewHolder对象存储view中 view.setTag(viewHolder); } else {//有缓存 view = convertView; viewHolder = (ViewHolder) view.getTag(); } viewHolder.bookId.setText(book.getId() + ""); viewHolder.bookAuthor.setText(book.getAuthor() + ""); viewHolder.bookPrice.setText(book.getPrice() + ""); viewHolder.bookPages.setText(book.getPages() + ""); viewHolder.bookName.setText(book.getName() + ""); //fruitImage.setImageResource(fruit.getImageId()); // fruitname.setText(fruit.getName()); return view; } class ViewHolder { TextView bookId; TextView bookAuthor; TextView bookPrice; TextView bookPages; TextView bookName; }}
MainActivity
package com.example.p229;import android.content.ContentValues;import android.content.Intent;import android.database.sqlite.SQLiteDatabase;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends AppCompatActivity implements View.OnClickListener { private EditText author_et; private EditText price_et; private EditText pages_et; private EditText name_et; private Button insert_data; private Button query_data; private MyDatabaseHelper dbhelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbhelper = new MyDatabaseHelper(this, "BookStore.db", null, 1); dbhelper.getWritableDatabase(); author_et = (EditText) findViewById(R.id.author_et); price_et = (EditText) findViewById(R.id.price_et); pages_et = (EditText) findViewById(R.id.pages_et); name_et = (EditText) findViewById(R.id.name_et); insert_data = (Button) findViewById(R.id.add_data); insert_data.setOnClickListener(this); query_data = (Button) findViewById(R.id.query_data); query_data.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.add_data: insertData(); break; case R.id.query_data: Intent intent = new Intent(MainActivity.this, BookActivity.class); startActivity(intent); break; } } private void insertData() { SQLiteDatabase db = dbhelper.getWritableDatabase(); ContentValues values = new ContentValues(); String author = author_et.getText().toString(); String name = name_et.getText().toString(); String price = price_et.getText().toString(); String pages = pages_et.getText().toString(); values.put("name", name); values.put("author", author); values.put("price", Double.parseDouble(price)); values.put("pages", Integer.parseInt(pages)); long count = db.insert("Book", null, values); if (count != -1) { Toast.makeText(this, "插入成功!!", Toast.LENGTH_SHORT).show(); author_et.setText(""); name_et.setText(""); price_et.setText(""); pages_et.setText(""); } else { Toast.makeText(this, "插入失败!!", Toast.LENGTH_SHORT).show(); } db.close(); }}
MyDatabaseHelper
package com.example.p229;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.widget.Toast;/** * Created by user on 2019/4/27. */public class MyDatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK="create table Book(" +"id integer primary key autoincrement," + "author text," + "price real," + "pages integer," +"name text)"; 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 db) { db.execSQL(CREATE_BOOK); Toast.makeText(mContext,"成功建表!!",Toast.LENGTH_SHORT).show(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }}
UpdateBookActivity
package com.example.p229;import android.content.ContentValues;import android.content.Intent;import android.database.sqlite.SQLiteDatabase;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class UpdateBookActivity extends AppCompatActivity { private EditText update_author_et; private EditText update_price_et; private EditText update_pages_et; private EditText update_name_et; private MyDatabaseHelper dbhelper; private Book book; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_book); //第一步:获取上一个活动传递过来的序列化book Intent intent=getIntent(); book=(Book)intent.getSerializableExtra("book"); //第二步:获取控件并显示数据 update_author_et=(EditText) findViewById(R.id.update_author_et); update_price_et=(EditText) findViewById(R.id.update_price_et); update_pages_et=(EditText) findViewById(R.id.update_pages_et); update_name_et=(EditText) findViewById(R.id.update_name_et); update_author_et.setText(book.getAuthor()); update_price_et.setText(book.getPrice()+""); update_pages_et.setText(book.getPages()+""); update_name_et.setText(book.getName()); dbhelper=new MyDatabaseHelper(this,"BookStore.db",null,1); } //按照页面上重新输入的信息去库中修改该书 public void updateInfo(View view){ //获取重新输入的信息 String authorStr=update_author_et.getText().toString(); String nameStr=update_name_et.getText().toString(); String priceStr=update_price_et.getText().toString(); String pagesStr=update_pages_et.getText().toString(); //按照获取的信息是否合法决定进行的操作 if(TextUtils.isEmpty(authorStr)||TextUtils.isEmpty(nameStr) ||TextUtils.isEmpty(pagesStr)||TextUtils.isEmpty(priceStr)){ Toast.makeText(this, "数据不完整,重新输入!", Toast.LENGTH_SHORT).show(); } else { //打开数据库 SQLiteDatabase db=dbhelper.getWritableDatabase(); ContentValues values=new ContentValues(); values.put("name",nameStr); values.put("author",authorStr); values.put("pages",Integer.parseInt(pagesStr)); values.put("price",Double.parseDouble(priceStr)); int count=db.update("Book",values,"id=?",new String[]{book.getId()+""}); if(count!=0){ Toast.makeText(this, "修改成功!!", Toast.LENGTH_SHORT).show(); finish(); } else{ Toast.makeText(this, "修改失败!!", Toast.LENGTH_SHORT).show(); } db.close(); } } //关闭页面 public void cancel(View view){ finish(); }}
activity_book.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" ><Button android:id="@+id/data_clear" android:text="清空" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="id" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:text="name" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:text="price" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:text="author" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:text="pages" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> <ListView android:id="@+id/lv_book" android:layout_width="match_parent" android:layout_height="wrap_content"></ListView></LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.p229.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="作者" android:textSize="18dp" /> <EditText android:id="@+id/author_et" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" android:hint="输入作者" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="单价" android:textSize="18dp" /> <EditText android:id="@+id/price_et" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" android:hint="输入单价" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="页数" android:textSize="18dp" /> <EditText android:id="@+id/pages_et" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" android:hint="输入页数" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="书名" android:textSize="18dp" /> <EditText android:id="@+id/name_et" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" android:hint="输入书名" /> </LinearLayout> <Button android:id="@+id/add_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="添加记录" /> <Button android:id="@+id/query_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="显示数据库信息" /></LinearLayout>
activity_update_book.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_update_book" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.p229.UpdateBookActivity"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="作者" android:textSize="18dp" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <EditText android:id="@+id/update_author_et" android:layout_width="0dp" android:layout_weight="4" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="单价" android:textSize="18dp" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <EditText android:id="@+id/update_price_et" android:layout_width="0dp" android:layout_weight="4" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="页数" android:textSize="18dp" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <EditText android:id="@+id/update_pages_et" android:layout_width="0dp" android:layout_weight="4" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="书名" android:textSize="18dp" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <EditText android:id="@+id/update_name_et" android:layout_width="0dp" android:layout_weight="4" android:layout_height="wrap_content" /> </LinearLayout> <Button android:onClick="updateInfo" android:textSize="18sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="修改" /> <Button android:onClick="cancel" android:textSize="18sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="取消" /></LinearLayout>
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="match_parent"><TextView android:id="@+id/book_id" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:id="@+id/book_name" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:id="@+id/book_price" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:id="@+id/book_author" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:id="@+id/book_pages" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /></LinearLayout>
完!