案例样图:
商品展示的布局文件代码(activity_main.xml):
<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"
android:layout_margin="8dp"
tools:context="cn.edu.bzu.case_sql.MainActivity">
<LinearLayout
android:id="@+id/addLL"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/nameET"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="商品名称"
android:inputType="textPersonName"
/>
<EditText
android:id="@+id/balanceET"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="金额"
android:inputType="number"
/>
|<ImageView
android:onClick="add"
android:id="@+id/addIV"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="@android:drawable/ic_input_add"
/>
LinearLayout>
<ListView
android:id="@+id/accountLV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/addLL"
>
ListView>
LinearLayout>
ListView的item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:orientation="horizontal">
<TextView
android:id="@+id/idTV"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="13"
android:textColor="#000000"
android:textSize="20sp"
/>
<TextView
android:id="@+id/nameTV"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:singleLine="true"
android:text="PQ"
android:textColor="#000000"
android:textSize="20sp"
/>
<TextView
android:id="@+id/balanceTV"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:singleLine="true"
android:text="123456"
android:textColor="#000000"
android:textSize="20sp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="@+id/upIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:src="@android:drawable/arrow_up_float"
/>
<ImageView
android:id="@+id/downIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/arrow_down_float"
/>
LinearLayout>
<ImageView
android:id="@+id/deleteIV"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@android:drawable/ic_menu_delete"/>
LinearLayout>
MyHelper类(创建数据库):
package cn.edu.bzu.case_sql.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.Settings;
/**
* Created by HZY on 2017/4/22.
*/
public class MyHelper extends SQLiteOpenHelper {
public MyHelper(Context context) {
super(context, "itcast.db", null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
System.out.println("onCreate");
db.execSQL("CREATE TABLE account(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),balance INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("onUpgrade");
}
}
Account类的代码:
package cn.edu.bzu.case_sql.bean;
/**
* Created by HZY on 2017/4/21.
*/
public class Account {
private Long id;
private String name;
private Integer balance;
public Account(Long id, String name, Integer balance) {
this.id = id;
this.name = name;
this.balance = balance;
}
public Account(String name, Integer balance) {
this.name = name;
this.balance = balance;
}
public Account() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getBalance() {
return balance;
}
public void setBalance(Integer balance) {
this.balance = balance;
}
@Override
public String toString() {
return "[序号:"+id+",商品名称:"+name+",余额:"+balance+"]";
}
}
AccountDao类的代码(数据库操作):
package cn.edu.bzu.case_sql.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import cn.edu.bzu.case_sql.bean.Account;
/**
* Created by HZY on 2017/4/22.
*/
public class AccountDao {
private MyHelper helper;
public AccountDao(Context context) {
//创建Dao,创建Helper
helper =new MyHelper(context);
}
public void insert(Account account){
//获取数据对象
SQLiteDatabase db=helper.getWritableDatabase();
//用来装载要插入的数据的Map<列名,列的值>
ContentValues values=new ContentValues();
values.put("name",account.getName());
values.put("balance",account.getBalance());
//向表插入数据values
long id=db.insert("account",null,values);
account.setId(id);
db.close();
}
//根据id删除数据
public int delete(long id){
SQLiteDatabase db=helper.getWritableDatabase();
//按条件删除指定表中的数据返回受影响的数据
int count=db.delete("account","_id=?",new String[]{id+""});
db.close();
return count;
}
//更新数据
public int update(Account account){
SQLiteDatabase db=helper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("name",account.getName());
values.put("balance",account.getBalance());
int count=db.update("account",values,"_id=?",new String[]{account.getId()+""});
db.close();
return count;
}
//查询所有数据倒序排列
public List queryAll(){
SQLiteDatabase db=helper.getWritableDatabase();
Cursor c=db.query("account",null,null,null,null,null,"balance DESC");
List list=new ArrayList();
while(c.moveToNext()){
//根据列名获取索引
long id=c.getLong(c.getColumnIndex("_id"));
String name=c.getString(1);
int balance=c.getInt(2);
list.add(new Account(id,name,balance));
}
c.close();
db.close();
return list;
}
}
MainActivity(页面交互代码):
package cn.edu.bzu.case_sql;
import android.content.ContentProviderOperation;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Objects;
//import java.util.stream.DoubleStream;
import cn.edu.bzu.case_sql.bean.Account;
import cn.edu.bzu.case_sql.dao.AccountDao;
public class MainActivity extends AppCompatActivity {
//需要适配的数据集合
private List list;
//数据库增删改查操作类
private AccountDao dao;
//输入姓名的EditText
private EditText nameET;
//输入金额的EditText
private EditText balanceET;
//适配器
private MyAdapter adapter;
//ListView
private ListView accountLV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initView();
dao=new AccountDao(this);
//从数据库中查询出所有数据
list=dao.queryAll();
adapter=new MyAdapter();
accountLV.setAdapter(adapter);//给ListView添加适配器(自动把数据生成条目)
}
//初始化控件
private void initView(){
accountLV=(ListView)findViewById(R.id.accountLV);
nameET=(EditText)findViewById(R.id.nameET);
balanceET=(EditText)findViewById(R.id.balanceET);
//添加监听器,监听条目点击事件
accountLV.setOnItemClickListener(new MyOnItemClickListener());
}
//activity_mian.xml对应ImageView的点击事件触发的方法
public void add(View v){
String name=nameET.getText().toString().trim();
String balance=balanceET.getText().toString().trim();
//三目运算符balance.equals("")则等于0
//如果balance不是空字符串 则进行类型转换
Account a=new Account(name,balance.equals("")?0:Integer.parseInt(balance));
dao.insert(a);
list.add(a);
adapter.notifyDataSetChanged();
//选中最后一个
accountLV.setSelection(accountLV.getCount()-1);
nameET.setText("");
balanceET.setText("");
}
//自定义一个适配器(把数据装到ListView的工具)
private class MyAdapter extends BaseAdapter{
public int getCount(){ //获取条目总数
return list.size();
}
public Object getItem(int position){ //根据位置获取对象
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
//获取一个条目视图
public View getView(int position , View convertView, ViewGroup parent){
//重用convertView
View item=convertView!=null?convertView:View.inflate(
getApplicationContext(),R.layout.item,null);
//获取该视图中的TextView
TextView idTV=(TextView)item.findViewById(R.id.idTV);
TextView nameTV=(TextView)item.findViewById(R.id.nameTV);
TextView balanceTV=(TextView)item.findViewById(R.id.balanceTV);
//根据当前位置获取Account对象
final Account a=list.get(position);
//把Account对象中的数据放到TextView中
idTV.setText(a.getId()+"");
nameTV.setText(a.getName());
balanceTV.setText(a.getBalance()+"");
ImageView upIV=(ImageView)item.findViewById(R.id.upIV);
ImageView downIV=(ImageView) item.findViewById(R.id.downIV);
ImageView deleteIV=(ImageView) item.findViewById(R.id.deleteIV);
//向上箭头的点击事件触发的方法
upIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a.setBalance(a.getBalance()+1);
notifyDataSetChanged();
dao.update(a);
}
});
//向下箭头的点击事件触发的方法
downIV.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
a.setBalance(a.getBalance()-1);
notifyDataSetChanged();
dao.update(a);
}
});
//删除图片的点击事件触发的方法
deleteIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//删除之前先弹出一个对话框
android.content.DialogInterface.OnClickListener listener=
new android.content.DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
list.remove(a);
dao.delete(a.getId());
notifyDataSetChanged();
}
};
//创建对话框
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("确定要删除吗?");//设置标题
//设置确定按钮的文本以及监听器
builder.setPositiveButton("确定",listener);
builder.setNegativeButton("取消",null);
builder.show();//显示对话框
}
});
return item;
}
}
//ListView 的Item点击事件
private class MyOnItemClickListener implements AdapterView.OnItemClickListener{
public void onItemClick(AdapterView>parent,View view,int position,long id){
//获取点击位置上的数据
Account a=(Account) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),a.toString(),Toast.LENGTH_SHORT).show();
}
}
}