如何使用游标适配器从SQLite数据库创建ListView

时间:2016-03-29 18:03:04

标签: android listview android-sqlite android-cursoradapter

我创建了一个包含ID,姓名,家庭,年龄,学生ID,学生电话号码的数据库。现在,我尝试通过搜索ID来检索学生的姓名和系列,然后使用游标适配器在自定义列表视图中显示检索到的数据,但我的代码不起作用。 请告诉我如何在列表视图中显示检索到的数据

这里我发布了我的代码:

DatabaseManager.java

const(
    Stage1 FeeStage = 1
    Stage2 FeeStage = 2
    Stage3 FeeStage = 2
)

Student.java

package com.example.tempcursoradapter;


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

public class DatabaseManager extends SQLiteOpenHelper{
    public DatabaseManager(Context context)
    {
        super(context,"myDB",null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        String query= "CREATE TABLE tbl_student ( "+
                " ID            INT            PRIMARY KEY"+
                " UNIQUE,"+
                " Name          VARCHAR( 50 ),"+
                " Family        VARCHAR( 50 ),"+
                " Age           INT,"+
                " StudentNumber VARCHAR( 11 ),"+
                " Tel           VARCHAR( 15 )"+ 
                " );";
        db.execSQL(query);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS tbl_student");
        onCreate(db);
    }


    public boolean addStudent (Student student)
    {
        boolean result;
        try{
        String query="INSERT INTO tbl_Student (ID,Name,Family,Age,StudentNumber,Tel) " +
                "VALUES ("+student.ID+",'"+student.Name+"','"+student.Family+"',"+27+",'"
                +student.stdNum+"','"+student.Tel+"')";
        SQLiteDatabase db=this.getWritableDatabase();
        db.execSQL(query);
        db.close();
        result = true;
        }
        catch(Exception e){
        result=false;
        }

        return result;
        }


    public boolean updataStudent (Student student)
    {
        boolean result;
        try{
        String query ="UPDATE tbl_Student  SET Name='"+student.Name+"',Family='"+student.Family+
                "',Age="+student.age+",StudentNumber='"+student.stdNum+"',Tel='"+student.Tel+"'" +
                " where ID = "+student.ID+"";
        SQLiteDatabase db =this.getWritableDatabase();
        db.execSQL(query);
        db.close();
        result =true;
        }
        catch (Exception e){
            result= false;
        }
        return result;
        }

    public Cursor getStudent (int id)
    {

        String query ="SELECT Name,Family FROM tbl_Student";
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cursor =db.rawQuery(query, null);

        return cursor;
    }

    public int getStudentCount()
    {
        int result=0;
        String query="SELECT * FROM tbl_student";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor=db.rawQuery(query, null);
        result=cursor.getCount();
        db.close();
        return result;
    }

    public boolean deleteStudent (int id)
    {
        boolean result;
        try{
        String query ="DELETE FROM tbl_student WHERE ID="+id;
        SQLiteDatabase db=this.getWritableDatabase();
        db.execSQL(query);
        db.close();
        result=true;
        }
        catch(Exception e)
        {
            result=false;
        }
        return result;
    }


}

TodoCursorAdapter.java

package com.example.tempcursoradapter;

public class Student {
    public int ID,age;
    public String Name,Family,stdNum,Tel;


}

MainActivity.java

package com.example.tempcursoradapter;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TodoCursorAdapter extends CursorAdapter {
      public TodoCursorAdapter(Context context, Cursor cursor, int flags) {
          super(context, cursor, 0);
      }


      @Override
      public View newView(Context context, Cursor cursor, ViewGroup parent) {
          return LayoutInflater.from(context).inflate(R.layout.item_todo, parent, false);
      }


      @Override
      public void bindView(View view, Context context, Cursor cursor) {
          // Find fields to populate in inflated template
          TextView tvName = (TextView) view.findViewById(R.id.tvname);
          TextView tvFamily = (TextView) view.findViewById(R.id.tvfamily);
          // Extract properties from cursor
          String body = cursor.getString(cursor.getColumnIndexOrThrow("Name"));
          String priority = cursor.getString(cursor.getColumnIndexOrThrow("Family"));
          // Populate fields with extracted properties
          tvName.setText(body);
          tvFamily.setText(String.valueOf(priority));
      }


    }

这是输出LogCat

package com.example.tempcursoradapter;



import android.R.integer;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv=(ListView) findViewById(R.id.listView1);
        // add 10 sample data to database
        final DatabaseManager db = new DatabaseManager(this);
        for (int j = 0; j < 10; j++) {
             Student student = new Student();
            student.ID=j;
            student.Name="name_"+String.valueOf(j);
            student.Family="family_"+String.valueOf(j);
            student.age=j;
            student.stdNum="stdNum_"+String.valueOf(j);
            student.Tel="telNum_"+String.valueOf(j);
             db.addStudent(student);
        }
// search for ID=1 
// I didn't used a Edit Text for input for simplicity and I only search for ID=1 
     Cursor todoCursor = db.getStudent(1);
// I know this line is my code's problem. my code crash at this line!
     TodoCursorAdapter todoAdapter = new TodoCursorAdapter(MainActivity.this, todoCursor,0);

     lv.setAdapter(todoAdapter);


    }


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

}

感谢您的好意

我已经更改了我的表格,但它仍然崩溃。

02-27 12:28:54.129: E/Trace(6837): error opening trace file: No such file or directory (2)
02-27 12:28:55.258: D/dalvikvm(6837): GC_FOR_ALLOC freed 44K, 7% free 2555K/2720K, paused 44ms, total 50ms
02-27 12:28:55.268: I/dalvikvm-heap(6837): Grow heap (frag case) to 3.216MB for 635812-byte allocation
02-27 12:28:55.328: D/dalvikvm(6837): GC_FOR_ALLOC freed 2K, 6% free 3173K/3344K, paused 56ms, total 56ms
02-27 12:28:55.458: D/dalvikvm(6837): GC_CONCURRENT freed <1K, 5% free 3190K/3344K, paused 7ms+19ms, total 130ms
02-27 12:28:55.958: D/AndroidRuntime(6837): Shutting down VM
02-27 12:28:55.958: W/dalvikvm(6837): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
02-27 12:28:55.978: E/AndroidRuntime(6837): FATAL EXCEPTION: main
02-27 12:28:55.978: E/AndroidRuntime(6837): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tempcursoradapter/com.example.tempcursoradapter.MainActivity}: java.lang.IllegalArgumentException: column '_id' does not exist
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.os.Looper.loop(Looper.java:137)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.app.ActivityThread.main(ActivityThread.java:5041)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at java.lang.reflect.Method.invokeNative(Native Method)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at java.lang.reflect.Method.invoke(Method.java:511)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at dalvik.system.NativeStart.main(Native Method)
02-27 12:28:55.978: E/AndroidRuntime(6837): Caused by: java.lang.IllegalArgumentException: column '_id' does not exist
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.support.v4.widget.CursorAdapter.init(CursorAdapter.java:174)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.support.v4.widget.CursorAdapter.<init>(CursorAdapter.java:151)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at com.example.tempcursoradapter.TodoCursorAdapter.<init>(TodoCursorAdapter.java:13)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at com.example.tempcursoradapter.MainActivity.onCreate(MainActivity.java:42)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.app.Activity.performCreate(Activity.java:5104)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-27 12:28:55.978: E/AndroidRuntime(6837):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-27 12:28:55.978: E/AndroidRuntime(6837):     ... 11 more

输出LogCat

String query= "CREATE TABLE tbl_student ( "+
                " _id integer PRIMARY KEY autoincrement," +
                " ID          INT            "+
                " UNIQUE,"+
                " Name          VARCHAR( 50 ),"+
                " Family        VARCHAR( 50 ),"+
                " Age           INT,"+
                " StudentNumber VARCHAR( 11 ),"+
                " Tel           VARCHAR( 15 )"+ 
                " );";
        db.execSQL(query);

我也使用过这个命令,但我的问题是一样的

02-27 13:55:40.529: W/dalvikvm(9220): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
02-27 13:55:40.538: E/AndroidRuntime(9220): FATAL EXCEPTION: main
02-27 13:55:40.538: E/AndroidRuntime(9220): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tempcursoradapter/com.example.tempcursoradapter.MainActivity}: java.lang.IllegalArgumentException: column '_id' does not exist
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.os.Looper.loop(Looper.java:137)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.app.ActivityThread.main(ActivityThread.java:5041)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at java.lang.reflect.Method.invokeNative(Native Method)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at java.lang.reflect.Method.invoke(Method.java:511)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at dalvik.system.NativeStart.main(Native Method)
02-27 13:55:40.538: E/AndroidRuntime(9220): Caused by: java.lang.IllegalArgumentException: column '_id' does not exist
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.support.v4.widget.CursorAdapter.init(CursorAdapter.java:174)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.support.v4.widget.CursorAdapter.<init>(CursorAdapter.java:122)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at com.example.tempcursoradapter.TodoCursorAdapter.<init>(TodoCursorAdapter.java:13)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at com.example.tempcursoradapter.MainActivity.onCreate(MainActivity.java:42)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.app.Activity.performCreate(Activity.java:5104)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-27 13:55:40.538: E/AndroidRuntime(9220):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-27 13:55:40.538: E/AndroidRuntime(9220):     ... 11 more
02-27 14:00:40.689: I/Process(9220): Sending signal. PID: 9220 SIG: 9

4 个答案:

答案 0 :(得分:1)

请阅读CursorAdapter

的文档
  

Cursor必须包含名为&#34; _id&#34;的列。或者这个班级不起作用。

基本上,只需将ID重命名为_id,即可使用它。

答案 1 :(得分:0)

问题是您的表"_id"

中没有列tbl_student

要使用CursorAdapter,您必须拥有&#34; _id&#34;表格中的列。 改变 -

@Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        String query= "CREATE TABLE tbl_student ( "+
                " _id            INT            PRIMARY KEY"+
                " UNIQUE,"+
                " Name          VARCHAR( 50 ),"+
                " Family        VARCHAR( 50 ),"+
                " Age           INT,"+
                " StudentNumber VARCHAR( 11 ),"+
                " Tel           VARCHAR( 15 )"+ 
                " );";
        db.execSQL(query);

    }

阅读this

答案 2 :(得分:0)

除了将ID列重命名为_id之外,您还应该重写DatabaseManager方法:

public boolean addStudent(Student student) {    
    boolean result; 
    try {   
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();  
        contentValues.put("Name", student.Name);
        contentValues.put("Family", student.Family);    
        // etc  
        db.insert("tbl_Student", null, contentValues);  
        db.close(); 
        result = true;  
    } catch (Exception e) { 
        result = false;
    }       
    return result;  
}



public Cursor getStudent(int id) {  
    SQLiteDatabase db = this.getReadableDatabase(); 
    return db.query("tbl_Student", null, "_id = ?", new String[]{String.valueOf(id)}, null, null, null);
}

您可以找到有用的指南here

答案 3 :(得分:0)

迟到派对,但是你的问题是:

public Cursor getStudent (int id)
{

    String query ="SELECT Name,Family FROM tbl_Student";
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor =db.rawQuery(query, null);

    return cursor;
}

更改为:

public Cursor getStudent (int id)
{

    String query ="SELECT _id, Name, Family FROM tbl_Student";
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor =db.rawQuery(query, null);
    return cursor;
}