在android中的sqlite数据库中显示listview中的数据

时间:2015-05-21 09:08:08

标签: android sqlite listview

我正在创建一个listview活动来从sqlite数据库中检索数据 数据库类为..

package com.example.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MyDBHandler extends SQLiteOpenHelper{
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "productDB.db";
    public static final String TABLE_PRODUCTS = "products";
    public static final String TABLE_STUDENT = "students";

    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_PRODUCTNAME = "productname";
    public static final String COLUMN_QUANTITY = "quantity";

    public static final String COLUMN_ROLLNO = "_rollno";
    public static final String COLUMN_STUDENTNAME = "studentname";
    public static final String COLUMN_CONTACT = "contact";  
    SQLiteDatabase data=this.getWritableDatabase();
    SQLiteDatabase data1 =this.getReadableDatabase();
    Product product;
    Detail detail;
    public MyDBHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {       
        try {
            // Create table Place
            String CREATE_STUDENTS_TABLE = "CREATE TABLE " +
                    TABLE_STUDENT + "("
                    + COLUMN_ROLLNO + " INTEGER PRIMARY KEY," + COLUMN_STUDENTNAME 
                    + " TEXT," + COLUMN_CONTACT + " INTEGER" + ");";

            db.execSQL(CREATE_STUDENTS_TABLE);
            // Create table Reminder
            String CREATE_PRODUCTS_TABLE = "CREATE TABLE " +
                      TABLE_PRODUCTS + "("
                      + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_PRODUCTNAME 
                      + " TEXT," + COLUMN_QUANTITY + " INTEGER" + ");";           
              db.execSQL(CREATE_PRODUCTS_TABLE);        
        } catch (SQLException se) {
            Log.v("DatabaseHandler Oncreate SQLException",
                    Log.getStackTraceString(se));
        } catch (Exception e) {
            Log.v("DatabaseHandler Oncreate Exception",
                    Log.getStackTraceString(e));
            }
        Log.d("database","table created");      
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
        // Drop table Place
                    String placeTableDropQuery = "DROP TABLE IF EXISTS " + TABLE_PRODUCTS;
                    db.execSQL(placeTableDropQuery);
                    // Drop table Reminder
                    String ReminderTableDropQuery = "DROP TABLE IF EXISTS "
                            + TABLE_STUDENT;
                    db.execSQL(ReminderTableDropQuery);
                    // Upgrade database
                    onCreate(db);
                } catch (SQLException se) {
                    Log.v("DatabaseHandler onUpgrade SQLException",
                            Log.getStackTraceString(se));
                } catch (Exception e) {
                    Log.v("DatabaseHandler onUpgrade Exception",
                            Log.getStackTraceString(e));
                }
    }   
    public String addProduct(Product product) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(COLUMN_PRODUCTNAME, product.getProductName());
            values.put(COLUMN_QUANTITY, product.getQuantity());
            db.insert(TABLE_PRODUCTS, null, values);
            db.close();
            return "Record insert succussfully...";
        } catch (SQLiteException se) {
            Log.v("DatabaseHandler insertStudentRecord Exception",
                    Log.getStackTraceString(se));
            return se.getMessage();
        } catch (Exception e) {
            Log.v("DatabaseHandler insertStudentRecord Exception",
                    Log.getStackTraceString(e));
            return e.getMessage();
        } finally{
            db.close();
        }        
}   
    public String addProduct(Detail product) {      
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(COLUMN_STUDENTNAME, product.getName());
            values.put(COLUMN_CONTACT, product.getNo());
            db.insert(TABLE_STUDENT, null, values);
            db.close();
            return "Record insert succussfully...";
        } catch (SQLiteException se) {
            Log.v("DatabaseHandler insertTeacherRecord Exception",
                    Log.getStackTraceString(se));
            return se.getMessage();
        } catch (Exception e) {
            Log.v("DatabaseHandler insertTeacherRecord Exception",
                    Log.getStackTraceString(e));
            return e.getMessage();
        } finally{
            db.close();
        }
    }
    public Product findProduct(String productname) {
        String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + " =  \"" + productname + "\"";      
        SQLiteDatabase db = this.getWritableDatabase();     
        Cursor cursor = db.rawQuery(query, null);       
        Product product = new Product();        
        if (cursor.moveToFirst()) {
            cursor.moveToFirst();
            product.setID(Integer.parseInt(cursor.getString(0)));
            product.setProductName(cursor.getString(1));
            product.setQuantity(Integer.parseInt(cursor.getString(2)));
            cursor.close();
        } else {
            product = null;
        }
            db.close();
        return product;
    }
    public Detail findDetail(int studentname) {
        String query = "Select * FROM " + TABLE_STUDENT + " WHERE " + COLUMN_ROLLNO + " =  \"" + studentname + "\"";
        SQLiteDatabase db = this.getWritableDatabase();     
        Cursor cursor = db.rawQuery(query, null);       
        Detail detail = new Detail();       
        if (cursor.moveToFirst()) {
            cursor.moveToFirst();
            detail.setID(Integer.parseInt(cursor.getString(0)));
            detail.setName(cursor.getString(1));
            detail.setNo(Integer.parseInt(cursor.getString(2)));
            cursor.close();
        } else {
            detail= null;
        }
            db.close();
        return detail;
    }   
    public boolean deleteProduct(String productname) {      
        boolean result = false;     
        String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + " =  \"" + productname + "\"";
        SQLiteDatabase db = this.getWritableDatabase();     
        Cursor cursor = db.rawQuery(query, null);       
        Product product = new Product();        
        if (cursor.moveToFirst()) {
            product.setID(Integer.parseInt(cursor.getString(0)));
            db.delete(TABLE_PRODUCTS, COLUMN_ID + " = ?",
                    new String[] { String.valueOf(product.getID()) });
            cursor.close();
            result = true;
        }
            db.close();
        return result;
    }   
    public boolean deleteDetail(String studentname) {       
        boolean result = false;     
        String query = "Select * FROM " + TABLE_STUDENT + " WHERE " + COLUMN_STUDENTNAME + " =  \"" + studentname + "\"";
        SQLiteDatabase db = this.getWritableDatabase();     
        Cursor cursor = db.rawQuery(query, null);       
        Detail detail = new Detail();       
        if (cursor.moveToFirst()) {
            detail.setID(Integer.parseInt(cursor.getString(0)));
            db.delete(TABLE_STUDENT, COLUMN_ROLLNO + " = ?",
                    new String[] { String.valueOf(detail.getID()) });
            cursor.close();
            result = true;
        }
            db.close();
        return result;
    }
}

创建具有按钮的活动,并在按钮上单击mylistactivity显示 活动为......

package com.example.database;
import java.util.ArrayList;

import com.example.database.R.string;    
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;    

public class MyListActivity extends ListActivity{
    ArrayAdapter<String> adapter;
    MyDBHandler db;     
    @Override
    protected void onCreate(Bundle savedInstanceState) {            
        super.onCreate(savedInstanceState);
        retrive();
        setListAdapter(adapter);
        db =new MyDBHandler(MyListActivity.this);
    }    
    private void retrive() {
        ArrayList<String>namelist= new ArrayList<String>();
        int ii;
        //ArrayList<String>studentno = new ArrayList<String>();
        SQLiteDatabase sd = db.getReadableDatabase();
        Cursor cursor = sd.query(db.TABLE_STUDENT, null, null, null, null, null, null);
        ii=cursor.getColumnIndex("studentname");
        while (cursor.moveToNext()){
            namelist.add(cursor.getString(ii));
            //studentno.add(cursor.getString(1));
        }
        ArrayList<String>combimelist=new ArrayList<String>();
        for(int i = 0; i<namelist.size();i++){
            combimelist.add(namelist.get(i));
        }
        adapter = new ArrayAdapter<String>(MyListActivity.this,R.layout.mylist, combimelist);
    }
}

和布局将其显示为

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:padding="15dp"
    android:textSize="25dp"
    android:layout_marginBottom="25dp">


</TextView>

它显示错误为..

05-21 05:08:53.823: I/Choreographer(1887): Skipped 34 frames!  The application may be doing too much work on its main thread.
05-21 05:08:54.043: D/AndroidRuntime(1887): Shutting down VM
05-21 05:08:54.043: W/dalvikvm(1887): threadid=1: thread exiting with uncaught exception (group=0x41465700)
05-21 05:08:54.363: E/AndroidRuntime(1887): FATAL EXCEPTION: main
05-21 05:08:54.363: E/AndroidRuntime(1887): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database/com.example.database.MyListActivity}: java.lang.NullPointerException
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.os.Looper.loop(Looper.java:137)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.app.ActivityThread.main(ActivityThread.java:5103)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at java.lang.reflect.Method.invokeNative(Native Method)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at java.lang.reflect.Method.invoke(Method.java:525)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at dalvik.system.NativeStart.main(Native Method)
05-21 05:08:54.363: E/AndroidRuntime(1887): Caused by: java.lang.NullPointerException
05-21 05:08:54.363: E/AndroidRuntime(1887):     at com.example.database.MyListActivity.retrive(MyListActivity.java:30)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at com.example.database.MyListActivity.onCreate(MyListActivity.java:21)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.app.Activity.performCreate(Activity.java:5133)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-21 05:08:54.363: E/AndroidRuntime(1887):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
05-21 05:08:54.363: E/AndroidRuntime(1887):     ... 11 more

2 个答案:

答案 0 :(得分:2)

首先初始化 db ,然后调用 retrive()方法:

替换:

retrive();
setListAdapter(adapter);
db =new MyDBHandler(MyListActivity.this);

要:

db =new MyDBHandler(MyListActivity.this);
retrive();
setListAdapter(adapter);

答案 1 :(得分:0)

可能有帮助

package com.src.sqlite.list;

public class Contact {

    // private variables
    int _id;
    String _name;
    byte[] _image;

    // Empty constructor
    public Contact() {

    }

    // constructor
    public Contact(int keyId, String name, byte[] image) {
        this._id = keyId;
        this._name = name;
        this._image = image;

    }

    // constructor
    public Contact(String contactID, String name, byte[] image) {
        this._name = name;
        this._image = image;

    }

    // constructor
    public Contact(String name, byte[] image) {
        this._name = name;
        this._image = image;
    }

    // getting ID
    public int getID() {
        return this._id;
    }

    // setting id
    public void setID(int keyId) {
        this._id = keyId;
    }

    // getting name
    public String getName() {
        return this._name;
    }

    // setting name
    public void setName(String name) {
        this._name = name;
    }

    // getting phone number
    public byte[] getImage() {
        return this._image;
    }

    // setting phone number
    public void setImage(byte[] image) {
        this._image = image;
    }
}


//////////////////////////////////////////////////////////////////////////////
package com.src.sqlite.list;


import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import com.manish.sqlite.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactImageAdapter extends ArrayAdapter<Contact>{
     Context context;
        int layoutResourceId;   
       // BcardImage data[] = null;
        ArrayList<Contact> data=new ArrayList<Contact>();
        public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
            super(context, layoutResourceId, data);
            this.layoutResourceId = layoutResourceId;
            this.context = context;
            this.data = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ImageHolder holder = null;

            if(row == null)
            {
                LayoutInflater inflater = ((Activity)context).getLayoutInflater();
                row = inflater.inflate(layoutResourceId, parent, false);

                holder = new ImageHolder();
                holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
                holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
                row.setTag(holder);
            }
            else
            {
                holder = (ImageHolder)row.getTag();
            }

            Contact picture = data.get(position);
            holder.txtTitle.setText(picture._name);
            //convert byte to bitmap take from contact class

            byte[] outImage=picture._image;
            ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
            Bitmap theImage = BitmapFactory.decodeStream(imageStream);
            holder.imgIcon.setImageBitmap(theImage);
           return row;

        }

        static class ImageHolder
        {
            ImageView imgIcon;
            TextView txtTitle;
        }
    }

///////////////////////////////////////////////
package com.src.sqlite.list;

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

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

public class DataBaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "imagedb";

    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_IMAGE = "image";

    public DataBaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " text not null UNIQUE,"
                + KEY_IMAGE + " BLOB" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    public// Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact._name); // Contact Name
        values.put(KEY_IMAGE, contact._image); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }

    // Getting single contact
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getBlob(1));

        // return contact
        return contact;

    }

    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM contacts ORDER BY name";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setImage(cursor.getBlob(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
        // close inserting data from database
        db.close();
        // return contact list
        return contactList;

    }

    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_IMAGE, contact.getImage());

        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });

    }

    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }

    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}
/////////////////////////////////////////////
package com.src.sqlite.list;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.manish.sqlite.R;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class SQLiteDemoActivity extends Activity {
    ArrayList<Contact> imageArry = new ArrayList<Contact>();
    ContactImageAdapter adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        DataBaseHandler db = new DataBaseHandler(this);
        // get image from drawable
        Bitmap image = BitmapFactory.decodeResource(getResources(),
                R.drawable.facebook);

        // convert bitmap to byte
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte imageInByte[] = stream.toByteArray();
        /**
         * CRUD Operations
         * */
        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("FaceBook", imageInByte));
        // display main List view bcard and contact name

        // Reading all contacts from database
        List<Contact> contacts = db.getAllContacts();
        for (Contact cn : contacts) {
            String log = "ID:" + cn.getID() + " Name: " + cn.getName()
                    + " ,Image: " + cn.getImage();

            // Writing Contacts to log
            Log.d("Result: ", log);
            //add contacts data in arrayList
            imageArry.add(cn);

        }
        adapter = new ContactImageAdapter(this, R.layout.screen_list,
                imageArry);
        ListView dataList = (ListView) findViewById(R.id.list);
        dataList.setAdapter(adapter);

    }

}
//////////////////////////////////


main.xml

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

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="0.55" >
    </ListView>

</LinearLayout>

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

    <ImageView
        android:id="@+id/imgIcon"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_weight="0.71"
        android:gravity="center_vertical" />

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="80dp"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:textSize="14dp"
        android:layout_marginLeft="7dp" />

</LinearLayout>