SQLite实现数据持久化存储小案例之购买商品

数据实现持久化保存的一个小小的案例

效果图如下:
1这里写图片描述

布局分析:
通过效果图可以看到我们需要两个EditText一个ImageButton和一个ListView。总体布局可以采用相对布局的方式,上面的两个EditText和ImageButton可以包含在一个线性布局里。下面ListView的Item可以用线性布局来实现。
功能分析:
通过布局中的按钮调用Onclick方法实现对数据库的增删该查。

实现代码:

主界面activity_main实现代码:

<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="bzu.edu.cn.cartview.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="商品名称"
            android:layout_weight="1"
            android:inputType="textPersonName"/>
        <EditText
            android:id="@+id/sum"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="金额"
            android:layout_weight="1"
            />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_input_add"
            android:id="@+id/add"
            android:onClick="add"
            android:layout_weight="0" />
    </LinearLayout>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ware">
    </ListView>
</LinearLayout>

ListView的item实现代码ware.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <TextView
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:layout_marginLeft="20sp"
        android:layout_marginTop="15dp"
        android:textSize="30sp"/>
    <TextView
        android:id="@+id/warename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="15dp"
        android:text="毛巾"
        android:textSize="30sp"/>
    <TextView
        android:id="@+id/money"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="100"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="15dp"
        android:textSize="30sp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="70dp">
        <ImageButton
            android:id="@+id/up"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp"
            android:src="@android:drawable/arrow_up_float"/>
        <ImageButton
            android:id="@+id/down"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="-14dp"
            android:src="@android:drawable/arrow_down_float"
            />
    </LinearLayout>
    <ImageButton
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_menu_delete"
        />
</LinearLayout>

数据库帮助类DbHelper实现代码:

package bzu.edu.cn.cartview;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.Settings;
import android.widget.Toast;

/**
 * Created by 海贼宝宝 on 2017/4/18.
 */

public class DbHelper extends SQLiteOpenHelper {

    public DbHelper(Context context) {
        super(context, "Ware.db", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("onCreate");
        db.execSQL("CREATE TABLE ware(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),money INTEGER)");


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           db.execSQL("drop table if exists ware");
           onCreate(db);

    }
}

持久化类Ware实现代码:

package bzu.edu.cn.cartview;

/**
 * Created by 海贼宝宝 on 2017/4/17.
 */

public class Ware {
    private int id;
    private String warename;
    private int  money;

    public Ware(int id, String warename, int money) {
        this.id = id;
        this.warename = warename;
        this.money = money;
    }

    public Ware(String warename, int money) {
        this.warename = warename;
        this.money = money;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getWarename() {
        return warename;
    }

    public void setWarename(String warename) {
        this.warename = warename;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
    public String toString(){
        return "[序号:"+id+",商品名称:"+warename+",金额:"+money+"]";
    }
}

对数据库操作类WareDao实现代码:

package bzu.edu.cn.cartview;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 海贼宝宝 on 2017/4/18.
 */

public class WareDao {
    private DbHelper dbHelper;
    private Ware ware;

    public WareDao(Context context) {
        dbHelper = new DbHelper(context);
    }
    public void insert(Ware ware)
    {
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        ContentValues contentValues=new ContentValues();
        contentValues.put("name",ware.getWarename());
        contentValues.put("money",ware.getMoney());
        int id= (int) db.insert("ware",null,contentValues);
        ware.setId(id);
        db.close();
    }
    public int delete(int id)
    {
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        int count=db.delete("ware","id=?",new String[]{id+""});
        db.close();
        return count;
    }
    public int update(Ware ware)
    {
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        ContentValues contentValues=new ContentValues();
        contentValues.put("name",ware.getWarename());
        contentValues.put("money",ware.getMoney());
        int count=db.update("ware",contentValues,"id=?",new String[]{ware.getId()+""});
        db.close();
        return count;
    }
    public List<Ware> query()
    {
        SQLiteDatabase db=dbHelper.getReadableDatabase();
        Cursor cursor=db.query("ware",null,null,null,null,null,null);
        List<Ware> list=new ArrayList<Ware>();
        while (cursor.moveToNext())
        {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name=cursor.getString(1);
            String money=cursor.getString(2);
            list.add(new Ware(id,name,Integer.parseInt(money)));
        }
        cursor.close();
        db.close();
        return list;
    }
}

实现主要功能的MainActivity代码:

package bzu.edu.cn.cartview;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;


public class MainActivity extends AppCompatActivity {

    private ListView ware1;
    private WareAdapter wareAdapter;
    private List<Ware> wareList;
    private EditText et_name,et_money;
    private WareDao wareDao;
    private TextView tv_id;
    private TextView tv_name;
    private TextView tv_money;
   private int i = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*获取控件*/
        ware1=(ListView) findViewById(R.id.ware);
        et_name=(EditText)findViewById(R.id.name);
        et_money=(EditText)findViewById(R.id.sum);

        wareDao=new WareDao(MainActivity.this);
        wareList = wareDao.query();
        wareAdapter = new WareAdapter();
        ware1.setAdapter(wareAdapter);

    }
    public void add(View view){
        String name = et_name.getText().toString();
        String money = et_money.getText().toString();
        Ware ware = new Ware(name, Integer.parseInt(money));
        wareDao.insert(ware);
        wareList.add(ware);
        wareAdapter.notifyDataSetChanged();
        ware1.setSelection(ware1.getCount() - 1);
        et_money.setText("");
        et_name.setText("");
    }

    private class WareAdapter extends BaseAdapter {
        public int getCount() {
            return wareList.size();
        }

        public Object getItem(int position) {
            return wareList.get(position);
        }
        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View item = convertView != null ? convertView : View.inflate(
                    getApplicationContext(), R.layout.ware, null
            );
            TextView t1 = (TextView) item.findViewById(R.id.id);
            TextView t2 = (TextView) item.findViewById(R.id.warename);
            TextView t3 = (TextView) item.findViewById(R.id.money);
            final Ware w = wareList.get(position);
            t1.setText(w.getId() + "");
            t2.setText(w.getWarename());
            t3.setText(w.getMoney() + "");
            ImageButton up = (ImageButton) item.findViewById(R.id.up);
            ImageButton down = (ImageButton) item.findViewById(R.id.down);
            ImageButton delete = (ImageButton) item.findViewById(R.id.delete);
            up.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    w.setMoney(w.getMoney() - 1);
                    notifyDataSetChanged();
                    wareDao.update(w);
                }
            });
            down.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    w.setMoney(w.getMoney() - 1);
                    notifyDataSetChanged();
                    wareDao.update(w);
                }
            });
            delete.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    final DialogInterface.OnClickListener listener = new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            wareList.remove(w);
                            wareDao.delete(w.getId());
                            notifyDataSetChanged();
                        }
                    };
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("确定要删除吗?");
                    builder.setPositiveButton("确定", listener);
                    builder.setNegativeButton("取消", null);
                    builder.show();
                }
            });
            return item;
        }
        private class MyOnItemClickListener implements AdapterView.OnItemClickListener {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){
                Ware w = (Ware) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(),w.toString(),Toast.LENGTH_SHORT).show();
            }
    }
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值