无法将sqlite数据库中的值检索到ListView中

时间:2013-02-15 04:37:17

标签: android database listview sqlite android-listview

我想从数据库中检索数据到我的ListView中,但是无法这样做。 我的java文件的相应activity_view_list.xml布局的名称是ViewList.java。 在这种情况下,请帮助我。 以下是我的代码

DBHelper.java

package com.example.shoppinglist;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper
{

    private static final String DATABASE_NAME = "ShoppingDatabase";
    private static final int DATABASE_VERSION = 1;
    private static final String DATBASE_CREATE = "CREATE TABLE ShoppingList(Id integer primary key autoincrement not null," +
            "List_name varchar(255) default null,List_status varchar(255) default 'OPEN'," +
            "date datetime)";
    public DBHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub

    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(DATBASE_CREATE);

    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.w(DBHelper.class.getName(), 
                "Upgrading database from version " + oldVersion + " to "
    + newVersion + ", which will delete the old data.");
    db.execSQL("DROP TABLE IF EXISTS ShoppingList");
    //Method is called during creation of new database
    onCreate(db);
    } 
}

DBAdpater.java

package com.example.shoppinglist;

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

public class DBAdapter 
{
    private Context ctxt;
    private SQLiteDatabase db;
    private DBHelper dbHelper;
    public static final String KEY_ROWID = "Id";
    public static final String KEY_NAME = "List_name";
    public static final String KEY_STATUS = "List_status";
    public static final String KEY_DATE = "date";
    //public static final String KEY_TOTAL_ITEMS = "Total_items";
    private static final String DATABASE_TABLE = "ShoppingList";

    public DBAdapter(Context ctxt)
    {
        this.ctxt = ctxt;
    }

    //Open database
    public DBAdapter open() throws SQLException
    {
        dbHelper = new DBHelper(ctxt, null, null, 0);
        db = dbHelper.getWritableDatabase();
        return this;
    }

    //Close database
    public void close()
    {
        dbHelper.close();
    }

    //Create a new item
    public long insertItem(String list_name , String list_status, String date)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, list_name );
        initialValues.put(KEY_STATUS, list_status);
        initialValues.put(KEY_DATE, date);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //update a item
    /*public boolean updateItem(long rowId, String list_name, 
        String list_status, String date)
    {
        ContentValues updateValues = new ContentValues();
        updateValues.put(KEY_NAME, list_name);
        updateValues.put(KEY_STATUS, list_status);
        updateValues.put(KEY_DATE, date);
        return db.update(DATABASE_TABLE, updateValues, KEY_ROWID + "=" + rowId,
                null) > 0;      
    }*/

    //delete a item
    public boolean deleteItem(long rowId)
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    //return cursor over the list of all items in the database
    public Cursor fetchAllItems(){
        return db.query(DATABASE_TABLE, new String[]{KEY_ROWID, KEY_NAME, 
                                KEY_STATUS, KEY_DATE}, 
                       null, null, null, null, null);
    }

    //return a cursor positioned at the defined item
    public Cursor fetchItem(long rowId) throws SQLException{
        Cursor mCursor = db.query(true, DATABASE_TABLE, 
                new String[]{KEY_ROWID, KEY_NAME, KEY_STATUS,
        KEY_DATE}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
        if(mCursor != null){
            mCursor.moveToFirst();
        }
        return mCursor;
    }   
}

activity_view_list.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewList" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

ViewList.java

package com.example.shoppinglist;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.database.Cursor;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;


public class ViewList extends ListActivity {

    private DBAdapter dbadpater;
    protected ListAdapter adapter;
    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_list);
        ListView listview = (ListView)findViewById(R.id.listView1);
        dbadpater = new DBAdapter(ViewList.this);
        dbadpater.open();
        Cursor values = dbadpater.fetchAllItems();
        adapter = new SimpleCursorAdapter(this, R.layout.list_example, values, new String[] {"Id","List_name"}, new int [] {R.id.txtid,R.id.txtname});
        setListAdapter(adapter);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), ((TextureView)view).getTextAlignment(),Toast.LENGTH_LONG).show();
            }
        });
        dbadpater.close();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_view_list, menu);
        return true;
    }

}

3 个答案:

答案 0 :(得分:0)

阅读tutorial for Loaders并使用SimpleCursorAdapter使用Loaders填充您的列表。 这非常容易和有效。装载程序处理打开,关闭和刷新Cursor本身。

答案 1 :(得分:0)

您忘记将适配器设置为列表视图。 试试如下:

listView.setAdapter(adapter);

答案 2 :(得分:0)

使用

从游标对象获取数据
if (cursor.moveToFirst()) {
        do {
        // looping through all rows and here we adding to list
        } while (cursor.moveToNext());
    }