商品展示案例
开发一个购物车,需要将购物车里的商品以列表的形式展示,并且还需要对购物车的商品进行增、删、改、查等操作。要实现这些功能就需要使用ListView和SQList数据库
1.创建程序
程序对应的布局文件activity_main.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: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.shopshow.MainActivity">
<LinearLayout
android:id="@+id/addLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="商品名称"
android:layout_weight="1"
android:id="@+id/nameET" />
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="金额"
android:layout_weight="1"
android:id="@+id/balanceET" />
<ImageView
android:onClick="add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_input_add"
android:id="@+id/addIV" />
</LinearLayout>
<ListView
android:id="@+id/accountLV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/addLL">
</ListView>
</LinearLayout>
2.创建ListView Item 布局
item.xml创建了三个TextView和三个ImageView,具体代码如下:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:text="13"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/idTV"
android:layout_weight="1"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:text="PQ"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/nameTV"
android:layout_weight="2"
android:singleLine="true"
android:textColor="#000000"
android:textSize="20sp"/>
<TextView
android:text="12345"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/balanceTV"
android:layout_weight="2"
android:singleLine="true"
android:textColor="#000000"
android:textSize="20sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@android:drawable/arrow_up_float"
android:id="@+id/upIV"
android:layout_marginBottom="2dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@android:drawable/arrow_down_float"
android:id="@+id/downIV" />
</LinearLayout>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
app:srcCompat="@android:drawable/ic_menu_delete"
android:id="@+id/delectIV" />
</LinearLayout>
3.创建一个名为dao的包,并在该包下定义一个MyHelper.java类继承自SQLiteOpenHelper,代码如下:
package cn.edu.bzu.shopshow.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.Settings;
/**
* Created by Administrator on 2017/4/28.
*/
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");
}
}
4.创建Account.java
创建一个bean包用于存放Javabean类,在该包下定义一个Account,具体代码如下:
package cn.edu.bzu.shopshow.bean;
/**
* Created by Administrator on 2017/4/28.
*/
public class Account {
private long id;
private String name;
private int balance;
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 int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public Account(long id, String name, int balance) {
super();
this.id = id;
this.name = name;
this.balance = balance;
}
public Account(String name, int balance) {
super();
this.name = name;
this.balance = balance;
}
public Account(){
super();
}
public String toString(){
return "[序号:"+id+",商品名称:"+name+",余额:"+balance+"]";
}
}
5.创建数据操作逻辑类
前面创建了数据库和Javabean,接下来需要编写数据逻辑编辑类。再创建一个AccountDao.java类用于数据操作,具体代码如下:
package cn.edu.bzu.shopshow.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.renderscript.Sampler;
import java.util.ArrayList;
import java.util.List;
import cn.edu.bzu.shopshow.bean.Account;
/**
* Created by Administrator on 2017/4/28.
*/
public class AccountDao {
private MyHelper helper;
public AccountDao(Context context){
helper=new MyHelper(context);
}
public void insert(Account account){
SQLiteDatabase db=helper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("name",account.getName());
values.put("balance",account.getBalance());
long id=db.insert("account",null,values);
account.setId(id);
db.close();
}
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<Account> queryAll(){
SQLiteDatabase db=helper.getReadableDatabase();
Cursor c=db.query("account",null,null,null,null,null,"balance DESC");
List<Account> list=new ArrayList<Account>();
While(c.moveToNext()){
long id=c.getLong()(c.getColumnIndex("_id"));
Stringname=c.getString(1);
int?balance=c.getInt(2);
list.add(new?Account(id,name,balance));
}
c.close();
db.close();
return?list;
}
}
6.编写页面交互代码(MainActivity)
数据库的操作完成后需要页面与数据库进行交互,用于实现将数据库中的数据以ListView的形式展示在页面上,具体代码如下:
packagecn.edu.bzu.productshow;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
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 cn.edu.bzu.productshow.Bean.Account;
import java.util.List;
import java.util.Locale;
import cn.edu.bzu.productshow.Dao.AccountDao;
public class MainActivity extends Activity{
//需要适配的数据集合
private List<Account> list;
//需要增删改查操作类
private AccountDao dao;
//输入姓名的edittext
private EditText nameET;
//输入金额的edittex
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_main.xml对应的inageview的点击事件触发的方法
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);
}
public long getItemId(int position)//根据位置获取id
{
return position;
}
//获取一个条目视图
public View getView(int?position,View convertView,ViewGroup parent)
{
//重用converView
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 upTV=(ImageView)item.findViewById(R.id.upIV);
ImageView downTV=(ImageView)item.findViewById(R.id.downIV);
ImageView deleteTV=(ImageView)item.findViewById(R.id.deleteIV);
//向上箭头的事件触发方法
upTV.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
a.setBalance(a.getBalance()+1);
notifyDataSetChanged();
dao.update(a);
}
});<pre class="html"name="code">//向下箭头的事件触发方法
upTV.setOnClickListener(new View.OnClickListener(){
@Override
public?void?onClick(View v){
a.setBalance(a.getBalance()-1);
notifyDataSetChanged();
dao.update(a);
}
});
deleteTV.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//删除数据之前首先弹出一个对话框
android.content.DialogInterface.OnClickListener listener=new android.content.DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
list.remove(a);//从集合删除
dao.delete(a.getId());//从数据库删除
notifyDataSetChanged();//刷新界面
}
};
//创建对话框
Builder builder=new Builder(MainActivity.this);
builder.setTitle("确定要删除吗");//设置标题
//设置确定按钮的文本以及监听器
builder.setPositiveButton("确定",listener);
builder.setNegativeButton("取消",null);
builder.show();
}
});
return item;
}
}
//Listview的item点击事件
private class MyOnItemClickListener implements OnItemClickListener{
public void onItemClick(AdapterView< > parent,View view,int position,long id)
{
//获取点击位置上的数据
a=(Account) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),a.toString(),Toast.LENGTH_SHORT).show();
}
}
}