包括:商品展示,商品详情,购物车,删除,一键清除,返回
运用sqllist
另外因为一篇写不下 继续可看 源码二
下面是目录
运行样子
下面是源码
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic"
android:supportsRtl="true"
android:theme="@style/Theme.Shop"
tools:targetApi="31">
<activity
android:name=".ShoppingDetailActivity"
android:exported="false" />
<activity
android:name=".ShoppingcartActivit"
android:exported="false" />
<activity
android:name=".ShoppingChannelActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
/database/ShoppingDBHelper
package com.example.shop.database;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.shop.enity.CartInfo;
import com.example.shop.enity.GoodsInfo;
import java.util.ArrayList;
import java.util.List;
public class ShoppingDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME="shopping.db";
public static final String TABLE_GOODS_INFO = "goods_info";
public static final String TABLE_CART_INFO = "cart_info";
public static final String CONTENT = "content";
private static final String TAG="MyApplication";
private static final int DB_VERSION=1;
private static ShoppingDBHelper mHelper=null;
private SQLiteDatabase mRDB=null;
private SQLiteDatabase mWDB=null;
public ShoppingDBHelper( Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static ShoppingDBHelper getInstance(Context context){
if(mHelper==null)mHelper=new ShoppingDBHelper(context);
return mHelper;
}
public SQLiteDatabase openReadLink(){
if(mRDB==null||!mRDB.isOpen()){
mRDB=mHelper.getReadableDatabase();
}
return mRDB;
}
public SQLiteDatabase openWriteLink(){
if(mWDB==null||!mWDB.isOpen()){
mWDB=mHelper.getWritableDatabase();
}
return mWDB;
}
public void closeLink(){
if(mRDB!=null&&mRDB.isOpen()){
mRDB.close();
mRDB=null;
}
if(mWDB!=null&&mWDB.isOpen()){
mWDB.close();
mWDB=null;
}
}
@Override
//数据库第一次被创建时调用该方法
public void onCreate(SQLiteDatabase db) {
//初始化数据库的表结构,执行一条建表的SQL语句
String sql ="create table if NOT EXISTS "+TABLE_GOODS_INFO+"(_id integer primary key autoincrement not null,"+"name varchar not null,"+"description varchar not null,"+
"price float not null,"+
"pic_path varchar not null);";
db.execSQL(sql);
sql ="create table if NOT EXISTS "+TABLE_CART_INFO+"(_id integer primary key autoincrement not null,"+
"goods_id integer not null,"+
"count integer not null);";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertGoodsInfos(List<GoodsInfo> list){//插入多条记录
try {
mWDB.beginTransaction();
for(GoodsInfo info:list){
ContentValues values=new ContentValues();
values.put("name",info.name);
values.put("description",info.description);
values.put("price",info.price);
values.put("pic_path",info.picPath);
mWDB.insert(TABLE_GOODS_INFO,null,values);
}
mWDB.setTransactionSuccessful();
} catch (Exception e){
} finally {
mWDB.endTransaction();
}
}
//查询
public List<GoodsInfo>queryAllGoodsInfo(){
String sql="select * from "+TABLE_GOODS_INFO;
List<GoodsInfo>list=new ArrayList<>();
Cursor cursor= mRDB.rawQuery(sql,null);
while (cursor.moveToNext()){
GoodsInfo info=new GoodsInfo();
info.id=cursor.getInt(0);
info.name=cursor.getString(1);
info.description=cursor.getString(2);
info.price=cursor.getFloat(3);
info.picPath=cursor.getString(4);
list.add(info);
}
cursor.close();
return list;
}
public void insertCartInfo(int gid) {//添加购物车
//不存在
CartInfo cartInfo=queryCartInfoByGoodsId(gid);
ContentValues values=new ContentValues();
values.put("goods_id",gid);
if(cartInfo==null){
values.put("count",1);
mRDB.insert(TABLE_CART_INFO,null,values);
}
else{ //数量加一
values.put("_id",cartInfo.id);
values.put("count",++cartInfo.count);
mWDB.update(TABLE_CART_INFO,values,"_id=?",new String[]{String.valueOf(cartInfo.id)});
}
}
private CartInfo queryCartInfoByGoodsId(int gid) {
//查询
Cursor cursor=mRDB.query(TABLE_CART_INFO,null,"goods_id=?",new String[]{String.valueOf(gid)},null,null,null);
CartInfo info=null;
if(cursor.moveToNext()){
info=new CartInfo();
info.id=cursor.getInt(0);
info.goodsid=cursor.getInt(1);
info.count=cursor.getInt(2);
}
return info;
}
public int countCartInfo() {
int count=0;
// String sql="select sum(count) from"+TABLE_CART_INFO;
// List<CartInfo>list=new ArrayList<>();
// Cursor cursor= mRDB.rawQuery(sql,null);
// count=cursor.getInt(0);
//
// // Cursor cursor=mRDB.rawQuery(sql,null);
// if(cursor.moveToNext()){
// count=cursor.getInt(0);
// Log.d(TAG,String.valueOf(count));
// }
return count;
}
public List<CartInfo> queryAllCartInfo() {//查询购物车信息
List<CartInfo>list=new ArrayList<>();
Cursor cursor=mRDB.query(TABLE_CART_INFO,null,null,null,null,null,null,null);
while(cursor.moveToNext()){
CartInfo info=new CartInfo();
info.id=cursor.getInt(0);
info.goodsid=cursor.getInt(1);
info.count=cursor.getInt(2);
list.add(info);
}
return list;
}
public GoodsInfo queryGoodsInfoById(int goodsid) {
GoodsInfo info=null;
Cursor cursor=mRDB.query(TABLE_GOODS_INFO,null,"_id=?",new String[]{String.valueOf(goodsid)},null,null,null);
if(cursor.moveToNext()){
info=new GoodsInfo();
info.id=cursor.getInt(0);
info.name=cursor.getString(1);
info.description=cursor.getString(2);
info.price=cursor.getFloat(3);
info.picPath=cursor.getString(4);
}
return info;
}
public void deleteCartinfobygoodsid(int goodsid) {//delete one
mWDB.delete(TABLE_CART_INFO,"goods_id=?",new String[]{String.valueOf(goodsid)});
}
public void deleteallcartinfo(){
mWDB.delete(TABLE_CART_INFO,"1=1",null);//条件
}
}
/enity/CartInfo 购物车数据
package com.example.shop.enity;
public class CartInfo {
public int id;
public int count;
public int goodsid;
public CartInfo(){}
public CartInfo(int id,int goodsid,int count){
this.goodsid=goodsid;
this.id=id;
this.count=count;
}
}
/enity/GoodsInfo 商品数据
package com.example.shop.enity;
import com.example.shop.R;
import java.util.ArrayList;
public class GoodsInfo {
public int id;
public String name;
public String description;
public float price;
public String picPath;
public int pic;
private static String[ ]mNameArray={
"iPhone 11","mate 30","mi30","huawei 2","rongyao30s","vivo x30"
};
private static String[]mDescArray={
"Apple iphone 256D|G",
"mate30 iphone 256D|G",
"mi30 iphone 256D|G",
"huawei 2 iphone 256D|G",
"rongyao30s iphone 256D|G",
"vivo x30 iphone 256D|G",
};
private static float[]mPriceArray={100,200,31,221,22,40};
private static int[]mPicArray={
R.drawable.no1,R.drawable.no2,R.drawable.no3,R.drawable.no4,R.drawable.no5,R.drawable.no6
};
public static ArrayList<GoodsInfo>getDefaultList(){
ArrayList<GoodsInfo>goodsList=new ArrayList<>();
for(int i=0;i<mNameArray.length;i++){
GoodsInfo info=new GoodsInfo();
info.id=i;
info.name=mNameArray[i];
info.description=mDescArray[i];
info.price= mPriceArray[i];
info.pic=mPicArray[i];
goodsList.add(info);
}
return goodsList;
}
}
/util/FilUtil 读取数据库数据并显示
package com.example.shop.util;
import android.graphics.Bitmap;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
public class FilUtil {
//保存
public static void saveText(String path,String txt){
BufferedWriter os=null;
try{
os=new BufferedWriter(new FileWriter(path));
os.write(txt);
}catch (Exception e){
e.printStackTrace();
}
finally {
if(os!=null){
try{
os.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
//读取
public static String openText(String path){
BufferedReader is=null;
StringBuilder sb=new StringBuilder();
try{
is= new BufferedReader(new FileReader(path));
String line=null;
while((line=is.readLine())!=null){
sb.append(line);
}
}catch (Exception e){
e.printStackTrace();
}
finally {
if(is!=null){
try{
is.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return path;
}
public static void saveImage(String path, Bitmap bitmap){
FileOutputStream fos=null;
try{
fos=new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
}catch (Exception e){
e.printStackTrace();
}
finally {
if(fos!=null){
try{
fos.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
/util/SharedUtil 轻量级存储
package com.example.shop.util;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Calendar;
public class SharedUtil {
private static SharedUtil mUtil;
private SharedPreferences preferences;
public static SharedUtil getInstance(Context ctx){
if(mUtil==null){
mUtil=new SharedUtil();
mUtil.preferences=ctx.getSharedPreferences("shopping",Context.MODE_PRIVATE);
}
return mUtil;
}
public void writeBoolean(String key,boolean value){//快捷方法
SharedPreferences.Editor editor=preferences.edit();
editor.putBoolean(key,value);
editor.commit();
}
public boolean reaadBoolean(String key,Boolean de){
return preferences.getBoolean(key,de);
}
}
AppWriteActivity
package com.example.shop;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class AppWriteActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_write);
}
}
MainActivity
package com.example.shop;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.lang.ref.Cleaner;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
MyApplication
package com.example.shop;
import android.app.Application;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import androidx.annotation.NonNull;
import com.example.shop.database.ShoppingDBHelper;
import com.example.shop.enity.GoodsInfo;
import com.example.shop.util.FilUtil;
import com.example.shop.util.SharedUtil;
import java.io.File;
import java.util.HashMap;
import java.util.List;
public class MyApplication extends Application {
private static MyApplication mApp;
public HashMap<String,String>infoMap=new HashMap<>();
public int goodsCount;
public static MyApplication getInstance(){//外部调用
return mApp;
}
@Override
public void onCreate() {
super.onCreate();
mApp=this;
initGoodsInfo();
}
private void initGoodsInfo() {//第一次打开
Boolean isFirst=SharedUtil.getInstance(this).reaadBoolean("first",true);
String directory=getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).toString()+ File.separatorChar;
if(isFirst){//打开数据库
List<GoodsInfo>list=GoodsInfo.getDefaultList();
for(GoodsInfo info:list){
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),info.pic);
String path=directory+info.id+".jpg";
FilUtil.saveImage(path,bitmap);
bitmap.recycle();
info.picPath=path;
}
//存储
ShoppingDBHelper dbHelper=ShoppingDBHelper.getInstance(this);
dbHelper.openWriteLink();
dbHelper.insertGoodsInfos(list);
dbHelper.closeLink();
SharedUtil.getInstance(this).writeBoolean("frist",false);
}
}
@Override
public void onTerminate() {
super.onTerminate();
}
@Override
public void onConfigurationChanged(@NonNull Configuration newCondig) {
super.onConfigurationChanged(newCondig);
}
}
ShoppingcartActivit
package com.example.shop;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.shop.database.ShoppingDBHelper;
import com.example.shop.enity.CartInfo;
import com.example.shop.enity.GoodsInfo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ShoppingcartActivit extends AppCompatActivity implements View.OnClickListener {
private TextView tv_count;
private LinearLayout ll_cart;
private ShoppingDBHelper mDBHelper;
public List<CartInfo> mCartList;//购物车
private TextView tv_total_price;
//声明缓存
private Map<Integer,GoodsInfo>mGoodsMap=new HashMap<>();
private LinearLayout ll_empty;
private LinearLayout ll_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppingcart);
TextView tv_title=findViewById(R.id.tv_title);
tv_count=findViewById(R.id.tv_count);
tv_title.setText("购物车");
tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));
ll_cart=findViewById(R.id.ll_cart);
tv_total_price=findViewById(R.id.tv_total_price);
mDBHelper= ShoppingDBHelper.getInstance(this);
findViewById(R.id.iv_back).setOnClickListener(this);
findViewById(R.id.btn_shopping_channel).setOnClickListener(this);
findViewById(R.id.btn_clear).setOnClickListener(this);
findViewById(R.id.btn_settle).setOnClickListener(this);
ll_empty=findViewById(R.id.ll_empty);
ll_content=findViewById(R.id.ll_content);
}
protected void onResume() {
super.onResume();
showCart();
}
private void showCart() {//展示
ll_cart.removeAllViews();//先移除
mCartList=mDBHelper.queryAllCartInfo();
if(mCartList.size()==0)return;
else{
for(CartInfo info:mCartList){
GoodsInfo goods= mDBHelper.queryGoodsInfoById(info.goodsid);
mGoodsMap.put(info.goodsid,goods);//缓存
View view= LayoutInflater.from(this).inflate(R.layout.item_cart,null);
@SuppressLint({"MissingInflatedId", "LocalSuppress"})
ImageView iv_thumb= view.findViewById(R.id.iv_thumb);
@SuppressLint({"MissingInflatedId", "LocalSuppress"})
TextView tv_name=view.findViewById(R.id.tv_name);
@SuppressLint({"MissingInflatedId", "LocalSuppress"})
TextView tv_desc=view.findViewById(R.id.tv_desc);
@SuppressLint({"MissingInflatedId", "LocalSuppress"})
TextView tv_count=view.findViewById(R.id.tv_count);
@SuppressLint({"MissingInflatedId", "LocalSuppress"})
TextView tv_price=view.findViewById(R.id.tv_price);
@SuppressLint({"MissingInflatedId", "LocalSuppress"})
TextView tv_sum=view.findViewById(R.id.tv_sum);
iv_thumb.setImageURI(Uri.parse(goods.picPath));
tv_name.setText(goods.name);
tv_price.setText(String.valueOf((int)goods.price));
tv_count.setText(String.valueOf(info.count));
tv_desc.setText(goods.description);
tv_sum.setText(String.valueOf((int)(info.count*goods.price)));
view.setOnLongClickListener(v -> {//clear 长安删除
AlertDialog.Builder builder=new AlertDialog.Builder(ShoppingcartActivit.this);//长安
builder.setMessage("是否从购物车中删除"+goods.name+"?");
builder.setPositiveButton("是",(dialog, which) -> {
ll_cart.removeView(v);//delete
deleteGoods(info);
});
builder.setNegativeButton("否",null);
builder.create().show();
return true;
});
ll_cart.addView(view);
}
refreshtotalprice();
}
}
private void deleteGoods(CartInfo info) {
MyApplication.getInstance().goodsCount-=info.count;
mDBHelper.deleteCartinfobygoodsid(info.goodsid);//从detebse
CartInfo removed=null;//从list from cart
for(CartInfo cartInfo:mCartList){
if(cartInfo.goodsid==info.goodsid){
removed=cartInfo;
break;
}
}
mCartList.remove(removed);
showCount();
Toast.makeText(this,"已从购物车中删除"+mGoodsMap.get(info.goodsid).name,Toast.LENGTH_SHORT).show();
mGoodsMap.remove(info.goodsid);
refreshtotalprice();
}
private void showCount() {//显示购物车数据
tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));
if(MyApplication.getInstance().goodsCount==0){
ll_empty.setVisibility(View.VISIBLE);
ll_content.setVisibility(View.GONE);
ll_cart.removeAllViews();
}
else{
ll_content.setVisibility(View.VISIBLE);
ll_empty.setVisibility(View.GONE);
}
}
private void refreshtotalprice() {//重新可计算
int totalPrice=0;
for(CartInfo info:mCartList){
GoodsInfo goods=mGoodsMap.get(info.goodsid);
totalPrice+=goods.price*info.count;
}
tv_total_price.setText(String.valueOf(totalPrice));
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.iv_back){
finish();
} else if (v.getId()==R.id.btn_shopping_channel) {
Intent intent=new Intent(this,ShoppingChannelActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else if (v.getId()==R.id.btn_clear) {
mDBHelper.deleteallcartinfo();
MyApplication.getInstance().goodsCount=0;
showCount();
Toast.makeText(this,"购物车已清空",Toast.LENGTH_SHORT).show();
} else {//settle结算
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("结算");
builder.setMessage("下次见");
builder.setPositiveButton("know",null);
builder.create().show();
}
}
}