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

案例界面:

Android SQLite实现数据持久化存储购买商品小案例_第1张图片Android SQLite实现数据持久化存储购买商品小案例_第2张图片

实现代码:

主界面activity_main实现代码:




    
        
        

        
    
    
    
ListView的item实现代码ware.xml:



    
    
    
    
        
        
    
    
布局分析: 
通过效果图可以看到我们需要两个EditText一个ImageButton和一个ListView。总体布局可以采用相对布局的方式,上面的两个EditText和ImageButton可以包含在一个线性布局里。下面ListView的Item可以用线性布局来实现。 
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 query()
    {
        SQLiteDatabase db=dbHelper.getReadableDatabase();
        Cursor cursor=db.query("ware",null,null,null,null,null,null);
        List list=new ArrayList();
        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 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();
            }
    }
}
}

功能分析: 
通过布局中的按钮调用Onclick方法实现对 数据库 的增删该查。



你可能感兴趣的:(Android SQLite实现数据持久化存储购买商品小案例)