Android 自定義Listview 如何綁定Sqlite數據庫數據

首先我們需要有個加載的文件,這個佈局文件裏面的bills.xml,這個佈局裏面有個Listview控件。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"
                 android:background="#FFFFFF">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:id="@+id/linearLayout3"
        android:orientation="horizontal"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="false"
        android:background="#444eb9"
        android:weightSum="1"
        android:gravity="center_vertical">

        <ImageView
            android:layout_width="80dp"
            android:layout_height="30dp"
            android:id="@+id/imageviewBack"
            android:src="@drawable/back"
            android:background="#444eb9"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="賬單"
            android:id="@+id/textView2"
            android:layout_gravity="center_vertical"
            android:background="#444eb9"
            android:layout_marginLeft="80dp"
            android:textColor="#FFFFFF"
            android:textStyle="bold"
            android:editable="false"
            android:enabled="false"
            android:hint="size"
            android:textIsSelectable="false"
            android:textSize="20dp"/>
    </LinearLayout>
    <ListView
        android:id="@+id/list_bills"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="#ffffff"
        android:dividerHeight="1dip"
        android:layout_below="@+id/linearLayout3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#fbf5f5"/>
</RelativeLayout>

接下來就是自定義的listview的佈局文件billsitem.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="no data"
        android:id="@+id/texttime"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginRight="28dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:gravity="center"/>

    <ImageView
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:id="@+id/imagetype"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/texttime"
        android:padding="10dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="no data"
        android:id="@+id/textfee"
        android:layout_marginLeft="61dp"
        android:layout_marginStart="61dp"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/textremarks"
        android:layout_alignStart="@+id/textremarks"
        android:layout_marginTop="10dp"
        android:gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:id="@+id/textremarks"
        android:layout_alignBottom="@+id/imagetype"
        android:layout_toRightOf="@+id/imagetype"
        android:layout_toEndOf="@+id/imagetype"
        android:layout_marginLeft="34dp"
        android:layout_marginStart="34dp"
        android:gravity="center"/>
</RelativeLayout>

接下來就是Android裏面的activity了,這接上代碼:

package com.bank;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by zhouchenglin on 2016/4/1.
 */
public class BillsActivity extends Activity implements View.OnClickListener {

        //列舉數據的ListView
        private ListView mlistbills;
        // 適配器
        private SimpleAdapter mlistbillsAdapter;
        //數據庫
        private MySQLiteHelper mMysql;
        private SQLiteDatabase mDataBase;
        private ImageView imageviewback;

        // 存儲數據的數組列表
        ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();

        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.bills);

                mlistbills = (ListView) this.findViewById(R.id.list_bills);
                imageviewback = (ImageView) this.findViewById(R.id.imageviewBack);
                imageviewback.setOnClickListener(this);

                GetData();
                mlistbillsAdapter = new SimpleAdapter(
                        this,
                        listData,
                        R.layout.billsitem,
                        new String[]{"Time", "Type", "Fee", "Remarks"},
                        new int[]{R.id.texttime, R.id.imagetype, R.id.textfee, R.id.textremarks}
                );
                //賦予數據
                mlistbills.setAdapter(mlistbillsAdapter);

                //響應
                mlistbills.setOnCreateContextMenuListener(listviewLongPress);
        }

        //從數據庫獲得適配器數據

        public void GetData() {
                mMysql = new MySQLiteHelper(this, "finance.db", null, 1);
                mDataBase = mMysql.getReadableDatabase();

                Cursor cursor = mDataBase.rawQuery("select * from finance", null);
                cursor.moveToFirst();
                int columnsSize = cursor.getColumnCount();
                int number = 0;
                while (number < cursor.getCount()) {

                        //  cursor.move(i);
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        String budget = cursor.getString(cursor.getColumnIndex("Budget"));
                        map.put("ID", cursor.getString(cursor.getColumnIndex("ID")));
                        map.put("Fee", cursor.getDouble(cursor.getColumnIndex("Fee")));
                        map.put("Time", cursor.getString(cursor.getColumnIndex("Time")));
                        if (budget.equals("收入"))
                                map.put("Fee", "+" + cursor.getString(cursor.getColumnIndex("Fee")));
                        else
                                map.put("Fee", "-" + cursor.getString(cursor.getColumnIndex("Fee")));
                        map.put("Remarks", cursor.getString(cursor.getColumnIndex("Remarks")));

                        if ((cursor.getString(cursor.getColumnIndex("Type"))).equals("衣")) {
                                map.put("Type", R.drawable.cloth);
                        } else if ((cursor.getString(cursor.getColumnIndex("Type"))).equals("食")) {
                                map.put("Type", R.drawable.chart);
                        } else if ((cursor.getString(cursor.getColumnIndex("Type"))).equals("住")) {
                                map.put("Type", R.drawable.zhu);
                        } else if ((cursor.getString(cursor.getColumnIndex("Type"))).equals("行")) {
                                map.put("Type", R.drawable.getmoney);
                        } else if ((cursor.getString(cursor.getColumnIndex("Type"))).equals("其他")) {
                                map.put("Type", R.drawable.getmoney);
                        }

                        cursor.moveToNext();
                        listData.add(map);
                        number++;
                        System.out.println(listData);
                }

                cursor.close();
                mDataBase.close();
                mMysql.close();
        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.imageviewBack:
                                this.finish();
                                break;
                        default:
                                break;
                }

        }

        // 長按事件響應
        View.OnCreateContextMenuListener listviewLongPress = new View.OnCreateContextMenuListener() {
                @Override
                public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                        // TODO Auto-generated method stub
                        final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
                        new AlertDialog.Builder(BillsActivity.this)
                    /* 彈出窗口的最上頭文字 */
                                .setTitle("刪除當前數據")
                    /* 設置彈出窗口的圖式 */
                                .setIcon(android.R.drawable.ic_dialog_info)
                    /* 設置彈出窗口的信息 */
                                .setMessage("確定刪除當前記錄")
                                .setPositiveButton("是",
                                        new DialogInterface.OnClickListener() {
                                                public void onClick(
                                                        DialogInterface dialoginterface, int i) {
                                                        // 獲取位置索引
                                                        int mListPos = info.position;
                                                        // 獲取對應HashMap數據內容
                                                        HashMap<String, Object> map = listData.get(mListPos);
                                                        // 獲取id
                                                        int id = Integer.valueOf((map.get("ID").toString()));

                                                        // 獲取數組具體值後,可以對數據進行相關的操作,例如更新數據
                                                        String[] whereArgs = new String[]{String.valueOf(id)};
                                                        //獲取當前數據庫
                                                        mMysql = new MySQLiteHelper(BillsActivity.this, "finance.db", null, 1);
                                                        mDataBase = mMysql.getReadableDatabase();
                                                        try {
                                                                mDataBase.delete("Finance", "ID=?", whereArgs);
                                                                listData.remove(mListPos);
                                                                mlistbillsAdapter.notifyDataSetChanged();
                                                        } catch (Exception e) {
                                                                Log.e("刪除出錯了", "error");
                                                        } finally {
                                                                mDataBase.close();
                                                                mMysql.close();
                                                        }
                                                }
                                        }
                                ).setNegativeButton(
                                "否",
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialoginterface, int i) {
                                        }
                                }
                        ).show();
                }
        };
}


對於數據裏面的操作,我前面的文章有講,這個實現的流程就是先獲得數據,在將數據適配器的數據反映到控件上去。主要是要將對應關係搞清楚,控件的類型和內容。
後面的響應事件,常按listview就會彈出對話框,進行刪除操作。其他的R.drawable.XX表示的是圖片資源,可以自行添加.

http://blog.csdn.net/richnaly/article/details/7790246

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章