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

时间:2013-02-28 17:24:00

标签: android sqlite

这是我的数据库代码,我想从我的数据库中检索名称并在listview中显示它在下面发布的另一个java文件中作为profilelist.jar。但是我无法做到这一点请告诉我这段代码是否正确?

package a.vaccination;

import android.annotation.TargetApi;
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.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class datahandler {

    public static final String KEY_ROWID = "id";
    public static final String KEY_name = "name";
    public static final String KEY_dob = "dob";
    public static final String KEY_contact = "contact";
    public static final String KEY_email = "email";
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "profile";
    private static final String DATABASE_TABLE = "baby";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE = "create table if not exists"
            + DATABASE_TABLE
            + "(id integer primary key autoincrement, "
            + "name VARCHAR not null, dob date, contact VARCHAR, email  
VARCHAR);";
    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public datahandler(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    protected static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            try {
                db.execSQL(DATABASE_CREATE);
                // db = DBHelper.getWritableDatabase();
                Log.i(DATABASE_NAME, "create");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old 
data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }

    // ---opens the database---
    public datahandler open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    // ---closes the database---
    public void close() {
        DBHelper.close();
    }

    // ---insert a record into the database---
    public long insertRecord(String name, String dob, String contact,
            String email) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_name, name);
        initialValues.put(KEY_dob, dob);
        initialValues.put(KEY_contact, contact);
        initialValues.put(KEY_email, email);
        Log.i(DATABASE_NAME, "values added");
        return db.insert(DATABASE_TABLE, null, initialValues);

    }

    // ---updates a record---
    public boolean updateRecord(long rowId, String name, String dob,
            String contact, String email) {
        ContentValues args = new ContentValues();
        args.put(KEY_name, name);
        args.put(KEY_dob, dob);
        args.put(KEY_contact, contact);
        args.put(KEY_email, email);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public Cursor getAllTitles() {
        return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_name,
                KEY_dob, KEY_contact, KEY_email }, null, null, null, null,
                null, null);
    }

    // ---retrieves a particular title---

    public Cursor getTitle(long rowId) throws SQLException {
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                KEY_ROWID, KEY_name, KEY_email, KEY_dob, KEY_contact },
                KEY_ROWID + "=" + rowId, null, null, null, null, null, 
null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public void getReadableDatabase() {
        // TODO Auto-generated method stub
        Cursor cur = db
                .rawQuery("select rowid _id,* from DATABASE_TABLE", null);
    }
}

profilelist.java

package a.vaccination;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

//this shows profies of baby and option of add new one
public class profilelist extends Activity implements OnItemClickListener {

    datahandler db = new datahandler(this);
    SimpleCursorAdapter adapter = null;
    Cursor c;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.child);

        Button add = (Button) findViewById(R.id.button1);
        add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // navigate to create profile
                Intent it = new Intent(profilelist.this, 
createprofile.class);
                startActivity(it);

            }
        });


        db.open();
        Cursor c = db.getAllTitles();
        if (c.moveToFirst()) {
            do {
                DisplayRecord(c);
            } while (c.moveToNext());
        }
        db.close();

        // ---get a Record---
        db.open();
        c = db.getTitle(2);
        if (c.moveToFirst())
            DisplayRecord(c);
        else
            Toast.makeText(this, "No Assignments found", Toast.LENGTH_LONG)
                    .show();
        db.close();

    }

    public void DisplayRecord(Cursor c) {
        // TODO Auto-generated method stub
        Toast.makeText(
                this,
                "id: " + c.getString(0) + "\n" + "name: " + c.getString(1)
                        + "\n" + " dob: " + c.getString(2) + 
"contact"
                        + c.getString(3) + "email" + 
c.getString(4),

                Toast.LENGTH_SHORT).show();
        String[] columns = new String[] { datahandler.KEY_name };
        int[] to = new int[] { R.id.name };
        adapter = new SimpleCursorAdapter(this, R.layout.child, c, columns,
                to, 0);
        ListView names = (ListView) findViewById(R.id.listView1);
        names.setAdapter(adapter);
        names.setOnItemClickListener(this);

    }

我收到了错误      a.vaccination.datahandler.getTitle(datahandler.java:115)      和      at a.vaccination.profilelist.onCreate(profilelist.java:67)      java.lang.NoSuchMethodError:android.database.sqlite.SQLiteDatabaseb.query 我在上面提供了profilelist.java和datahandler.java

请帮助我,我被困在这里         @覆盖         public void onItemClick(AdapterView arg0,View arg1,int arg2,long arg3){             // TODO自动生成的方法存根

        Intent i = new Intent(profilelist.this, vaccination.class);
        startActivity(i);
    }


}

4 个答案:

答案 0 :(得分:0)

我最近实现了这种功能。基本上,您必须创建自定义BaseAdapter以在ListView中显示数据。在适配器构造函数中,传入包含数据的对象数组。我以前的教程是: http://www.vogella.com/articles/AndroidListView/article.html。希望这有帮助!

答案 1 :(得分:0)

回答你的第一个和第二个问题:"不,这段代码真的不太好"。你真的必须考虑使用Loader。虽然您所写的内容大部分时间都可以正常工作,但您很可能会生成突然终止应用程序的应用程序无响应错误。不要在UI线程上做这些事情。

有很多Android编程可能令人惊讶。我真的建议你在把自己画成一个角落之前,先拿一本关于如何做的标准书。

答案 2 :(得分:0)

您想使用像this SimpleCursorAdapter这样的CursorAdapter。你传递了一个列映射到视图ID,它处理绑定等等。

答案 3 :(得分:0)

您需要创建SimpleCursorAdapter并将其附加到从您的数据库自定义查询选择返回的游标。然后,从游标返回的数据列将映射到您的自定义视图以供显示。要了解更多点击 Here,这可以为您的问题提供正确的实施