SQLite数据库和ListView控件相关案例

 界面管理数据库

运行界面

 要实现这个功能要监听删除按钮的点击事件
 监听对话框的确认按钮点击事件
 ListView的Item设置点击监听事件

单击向上箭头会给相应数据的金额+1
实现这个功能要在BaseAdapter的 getView() 方法中监听该图片的点击事件

界面交互代码

MainActivity

ListView 的 setOnItemClickListener() 方法
  
     用于监听Item的点击事件 使用时 需要传入一个OnItemClickListener 实现类对象 且需要实现onItemClick() 方法

ListView 的 setSelection() 方法

     设置当前选中的条目

package product.itcast.cn.productshow;

import android.accounts.Account;
import android.content.DialogInterface;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
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.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.List;

import product.itcast.cn.productshow.dao.AccountDao;


public class MainActivity extends AppCompatActivity {

    private List<product.itcast.cn.productshow.bean.Account> list;
    private AccountDao dao;
    private EditText nameET;
    private EditText balanceET;
    private MyAdapter adapter;
    private ListView accountLV;
    /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */
    private GoogleApiClient client;

    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);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    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());
    }

    public void add(View v) {
        String name = nameET.getText().toString().trim();
        String balance = balanceET.getText().toString().trim();
        product.itcast.cn.productshow.bean.Account a = new product.itcast.cn.productshow.bean.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("");
    }

    /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    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) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View item = convertView != null ? convertView : View.inflate(getApplicationContext(), R.layout.item, null);

            TextView idTV = (TextView) item.findViewById(R.id.idTV);
            TextView nameTV = (TextView) item.findViewById(R.id.nameTV);
            TextView balanceTV = (TextView) item.findViewById(R.id.balanceTV);

            //final Account a = list.get(position);
            final product.itcast.cn.productshow.bean.Account a = list.get(position);
            //idTV.setText(a.getId + "");
            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() {
                public void onClick(View v) {
                    a.setBalance(a.getBalance() + 1);
                    notifyDataSetChanged();
                    dao.update(a);
                }
            });

            downIV.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    a.setBalance(a.getBalance() - 1);
                    notifyDataSetChanged();
                    dao.update(a);
                }
            });

            deleteIV.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
                        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;
        }
    }

    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();
        }
    }
}

Account类

package product.itcast.cn.productshow.bean;

/** * Created by Administrator on 2017/4/17. */

public class Account {
    private Long id;
    private String name;
    private Integer 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 Integer getBalance(){
        return balance;
    }
    public void setBalance(Integer balance){
        this.balance = balance;
    }

    public Account (Long id, String name, Integer balance){
        super();
        this.id = id;
        this.name = name;
        this.balance = balance;
    }
    public Account(String name, Integer balance){
        super();
        this.name = name;
        this.balance = balance;
    }
    public Account(){
        super();
    }
    public String toString(){
        return "[序号:"+id+",商品名称:"+name+", 余额:"+balance+"]";
    }
}

AccountDao类

用于操作数据

android
package product.itcast.cn.productshow.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 product.itcast.cn.productshow.bean.Account;

/** * Created by Administrator on 2017/4/17. */

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"));
            String name = c.getString(1);
            int balance = c.getInt(2);
            list.add(new Account(id, name, balance));
        }
        c.close();
        db.close();
        return list;
    }
}

MyHelper类

android
package product.itcast.cn.productshow.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/** * Created by Administrator on 2017/4/17. */

public class MyHelper extends SQLiteOpenHelper {
    public MyHelper (Context context) {
        super(context,"itcast.db",null,2);
    }
    public  void onCreate(SQLiteDatabase db) {
        System.out.println("onCreate");
        db.execSQL("CREATE TABLE account(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),balance INTEGER)");
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println("onUpgrade");
    }
}

布局文件

Activity_main.xml

android
<?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:layout_margin="8dp" android:orientation="vertical" tools:context="product.itcast.cn.productshow.MainActivity">

    <LinearLayout  android:id="@+id/addLL" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">

        <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:id="@+id/addIV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="add" 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>

item.xml

TextView用于显示数据库中的某条数据的详细信息
ImageView用于增加减少金额和删除金额

android
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="10dp">

    <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"/>

    <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>

    <TextView  android:id="@+id/balanceTV" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:singleLine="true" android:text="12345" android:textColor="#000000" android:textSize="20sp"/>

    <ImageView  android:id="@+id/deleteIV" android:layout_width="25dp" android:layout_height="25dp" android:src="@android:drawable/ic_menu_delete"/>
</LinearLayout>

你可能感兴趣的:(数据库,sqlite)