simpleCursorAdaptor使我的Android应用程序意外退出

时间:2016-02-23 14:21:01

标签: java android xml listview

因此,我希望在此列表视图中显示我的数据库中所有注册学生的全名和电子邮件。我设法得到了光标和所有数据,但只要我将它绑定到SimpleCursorAdaptor我的应用程序崩溃.. 请帮忙...... 下面的Java和以及相应的XML资源代码......

Java代码:

package thedev.rdmuniversal.com.smartclass;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class studentListActivity extends AppCompatActivity {

Context octx = this;
Intent o_intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_student_list);
    o_intent = getIntent();
    populateListView();
}

public void populateListView(){
    db_handler odbh = new db_handler(octx);
    Cursor stuListCursor = odbh.getStudentList(odbh);
    stuListCursor.moveToFirst();

    String[] fromCols = new String[]{
        DbDefine.db_Info.USER_NAME_COL,
        DbDefine.db_Info.USER_FULL_NAME
    };

    int[] toView = new int[]{
            R.id.userNameElement_lbl,
            R.id.fullNameElement_lbl
    };

    SimpleCursorAdapter csa = new SimpleCursorAdapter(
            octx,
            R.layout.student_list_row,
            stuListCursor,
            fromCols,
            toView
    );
    ListView myls = (ListView) findViewById(R.id.stuListView);
    myls.setAdapter(csa);
    Toast.makeText(getBaseContext(), "len >> "+stuListCursor.getCount()+" :",Toast.LENGTH_LONG).show();
}

}

ListView的XML设计文件(activity_student_list.xml)

<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="thedev.rdmuniversal.com.smartclass.studentListActivity">

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/stuListView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:choiceMode="singleChoice"/>

</RelativeLayout>

列表元素的XML文件(student_list_row.xml)

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/userNameElement_lbl"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Medium Text"
    android:id="@+id/fullNameElement_lbl"/>

</LinearLayout>

完成错误日志:

02-23 19:56:22.871 21295-21295/? E/AndroidRuntime: FATAL EXCEPTION: main
                                               Process: thedev.rdmuniversal.com.smartclass, PID: 21295
                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{thedev.rdmuniversal.com.smartclass/thedev.rdmuniversal.com.smartclass.studentListActivity}: java.lang.IllegalArgumentException: column '_id' does not exist
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                   at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:148)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                Caused by: java.lang.IllegalArgumentException: column '_id' does not exist
                                                   at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333)
                                                   at android.widget.CursorAdapter.init(CursorAdapter.java:180)
                                                   at android.widget.CursorAdapter.<init>(CursorAdapter.java:128)
                                                   at android.widget.ResourceCursorAdapter.<init>(ResourceCursorAdapter.java:55)
                                                   at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:78)
                                                   at thedev.rdmuniversal.com.smartclass.studentListActivity.populateListView(studentListActivity.java:41)
                                                   at thedev.rdmuniversal.com.smartclass.studentListActivity.onCreate(studentListActivity.java:23)
                                                   at android.app.Activity.performCreate(Activity.java:6251)
                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                   at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                   at android.os.Looper.loop(Looper.java:148) 
                                                   at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

db_handler.java的完整代码

package thedev.rdmuniversal.com.smartclass;

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

/**
 *
 * Created by rohitmahindrakar on 19/02/16.
 *
 */

public class db_handler extends SQLiteOpenHelper {

    Context octx;

    public static final int database_version = 1;
    public String CREATE_QUERY_USERINFO = "CREATE TABLE "+DbDefine.db_Info.TABLE_NAME+" ("+DbDefine.db_Info.USER_ID_COL+" INTEGER PRIMARY KEY, "+DbDefine.db_Info.USER_NAME_COL+" TEXT, "+DbDefine.db_Info.USER_PASS_COL+" TEXT, "+DbDefine.db_Info
            .USER_LVL_COL+" TEXT, "+DbDefine.db_Info.USER_FULL_NAME+" TEXT, "+ DbDefine
            .db_Info.USER_CLASS+" TEXT, "+ DbDefine.db_Info.USER_DIV+" TEXT );";

    public db_handler(Context context) {
        super(context, DbDefine.db_Info.DATABASE_NAME, null, database_version);
        Log.d("DB_OPRT", "DB Created");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_QUERY_USERINFO);
        Log.d("DB_OPRT", "Table Created");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void putAdminInfo(db_handler dbh){

        // check if admin is avaliable >>
        SQLiteDatabase oSQL = dbh.getReadableDatabase();

        String[] projection= {
                DbDefine.db_Info.USER_NAME_COL,
                DbDefine.db_Info.USER_PASS_COL
        };
        String selection = "`user_name` = ? AND `user_pass` = ?";
        String[] selectionArgs = {
                "admin",
                "passw"
        };
        Cursor oCurson = oSQL.query(
                DbDefine.db_Info.TABLE_NAME,    // table to query
                projection,                     // rows to return
                selection,                      // rows for where
                selectionArgs,                  // conditions for where
                null,                           // dont group th rows
                null,                           // dont filter by row groups
                null                            // dont sort
        );
        oCurson.moveToFirst();
        // <</ check if admin is avaliable

        if(0 == oCurson.getCount()){
            oSQL = dbh.getWritableDatabase();
            ContentValues ocv = new ContentValues();
            ocv.put(DbDefine.db_Info.USER_NAME_COL, "admin");
            ocv.put(DbDefine.db_Info.USER_PASS_COL, "passw");
            ocv.put(DbDefine.db_Info.USER_LVL_COL, 1);
            oSQL.insert(DbDefine.db_Info.TABLE_NAME, null, ocv);
            Log.d("DB_OPRT", "Admin Added");
            oCurson.close();
        }else{
            Log.d("DB_OPRT", "Admin Avaliable");
            oCurson.close();
        }


    }

    // login >>
    public int getUserForLogin(db_handler dbh, String u_name, String u_pass){
        SQLiteDatabase oSQL = dbh.getReadableDatabase();

        String[] projection= {
                DbDefine.db_Info.USER_NAME_COL,
                DbDefine.db_Info.USER_PASS_COL
        };

        String selection = "`user_name` = ? AND `user_pass` = ?";

        String[] selectionArgs = {
                u_name,
                u_pass
        };

        Cursor oCurson = oSQL.query(
                DbDefine.db_Info.TABLE_NAME,    // table to query
                projection,                     // rows to return
                selection,                      // rows for where
                selectionArgs,                  // conditions for where
                null,                           // don't group th rows
                null,                           // don't filter by row groups
                null                            // don't sort
        );

        oCurson.moveToFirst();
        int clen = oCurson.getCount();
        oCurson.close();
        return  clen;
    }
    // <</ login

    // puts student info in db >>
    public String putStudentInfo(db_handler dbh, String user_name, String user_pass, String
            user_fullName, String user_class, String user_div){

        // check if admin is avaliable >>
        SQLiteDatabase oSQL = dbh.getReadableDatabase();
        String[] projection= {
                DbDefine.db_Info.USER_NAME_COL,
                DbDefine.db_Info.USER_PASS_COL
        };
        String selection = "`user_name` = ?";
        String[] selectionArgs = {
                user_name
        };
        Cursor oCurson = oSQL.query(
                DbDefine.db_Info.TABLE_NAME,    // table to query
                projection,                     // rows to return
                selection,                      // rows for where
                selectionArgs,                  // conditions for where
                null,                           // dont group th rows
                null,                           // dont filter by row groups
                null                            // dont sort
        );
        oCurson.moveToFirst();
        // <</ check if admin is avaliable

        if(0 == oCurson.getCount()){
            oSQL = dbh.getWritableDatabase();
            ContentValues ocv = new ContentValues();
            ocv.put(DbDefine.db_Info.USER_NAME_COL, user_name);
            ocv.put(DbDefine.db_Info.USER_PASS_COL, user_pass);
            ocv.put(DbDefine.db_Info.USER_LVL_COL, "3");
            ocv.put(DbDefine.db_Info.USER_FULL_NAME, user_fullName);
            ocv.put(DbDefine.db_Info.USER_CLASS, user_class);
            ocv.put(DbDefine.db_Info.USER_DIV, user_div);
            oSQL.insert(DbDefine.db_Info.TABLE_NAME, null, ocv);
            Log.d("DB_OPRT", "User Added");
            oCurson.close();
            return "true";
        }else{
            Log.d("DB_OPRT", "User Avaliable");
            oCurson.close();
            return "xfalse";
        }

    }
    // <</ puts student info in db

    // puts teacher info into db >>
    public String putTeacherInfo(db_handler dbh, String teacherEmail, String teacherName, String
            teacherPass){

        // check if admin is avaliable >>
        SQLiteDatabase oSQL = dbh.getReadableDatabase();
        String[] projection= {
                DbDefine.db_Info.USER_NAME_COL,
                DbDefine.db_Info.USER_PASS_COL
        };
        String selection = "`user_name` = ?";
        String[] selectionArgs = {
                teacherEmail
        };
        Cursor oCurson = oSQL.query(
                DbDefine.db_Info.TABLE_NAME,    // table to query
                projection,                     // rows to return
                selection,                      // rows for where
                selectionArgs,                  // conditions for where
                null,                           // dont group th rows
                null,                           // dont filter by row groups
                null                            // dont sort
        );
        oCurson.moveToFirst();
        // <</ check if admin is avaliable

        if(0 == oCurson.getCount()){
            oSQL = dbh.getWritableDatabase();
            ContentValues ocv = new ContentValues();
            ocv.put(DbDefine.db_Info.USER_NAME_COL, teacherEmail);
            ocv.put(DbDefine.db_Info.USER_PASS_COL, teacherPass);
            ocv.put(DbDefine.db_Info.USER_LVL_COL, "2");
            ocv.put(DbDefine.db_Info.USER_FULL_NAME, teacherName);
            oSQL.insert(DbDefine.db_Info.TABLE_NAME, null, ocv);
            Log.d("DB_OPRT", "User Added");
            oCurson.close();
            return "true";
        }else{
            Log.d("DB_OPRT", "User Avaliable");
            oCurson.close();
            return "xfalse";
        }

    }
    // <</ puts teacher info into db


    // get all student info >>
    public Cursor getStudentList(db_handler dbh){
        // check if admin is avaliable >>
        String lvl = "3";
        SQLiteDatabase oSQL = dbh.getWritableDatabase();
        String[] projection= {
                DbDefine.db_Info.USER_NAME_COL,
                DbDefine.db_Info.USER_PASS_COL
        };
        String selection = "`user_lvl` = ?";
        String[] selectionArgs = {
                lvl
        };
        Cursor oCurson = oSQL.query(
                DbDefine.db_Info.TABLE_NAME,    // table to query
                projection,                     // rows to return
                selection,                      // rows for where
                selectionArgs,                  // conditions for where
                null,                           // dont group th rows
                null,                           // dont filter by row groups
                null                            // dont sort
        );
        oCurson.moveToFirst();
        // <</ check if admin is avaliable
        return oCurson;
    }

    // <</ get all student info


    }

DbDefine.java的JAVA代码

package thedev.rdmuniversal.com.smartclass;

import android.provider.BaseColumns;

/**
 * Created by rohitmahindrakar on 19/02/16.
 */
public class DbDefine {

    public DbDefine(){}

    public static abstract class db_Info implements BaseColumns{
        public static final String DATABASE_NAME = "smartClassDB";
        public static final String TABLE_NAME = "user_info";

        public static final String USER_ID_COL = "user_id";
        public static final String USER_NAME_COL = "user_name";
        public static final String USER_PASS_COL = "user_pass";
        public static final String USER_LVL_COL = "user_lvl";
        public static final String USER_FULL_NAME = "user_full_name";
        public static final String USER_CLASS = "user_class";
        public static final String USER_DIV = "user_div";
    }

}

1 个答案:

答案 0 :(得分:0)

DbDefine.db_Info.USER_ID_COL的值应为_id。如果没有,请将其设为,并在Cursor中获取该值。

SimpleCursorAdapter需要Cursor,其中包含_id列。

<强>更新

更改

public static final String USER_ID_COL = "user_id";

public static final String USER_ID_COL = "_id";

然后

String[] projection= {
            DbDefine.db_Info.USER_NAME_COL,
            DbDefine.db_Info.USER_PASS_COL
    };

String[] projection= {
            DbDefine.db_Info.USER_ID_COL,
            DbDefine.db_Info.USER_NAME_COL,
            DbDefine.db_Info.USER_PASS_COL
    };

像以前一样保持创建表查询。

注意:应用这些更改后,您必须先从手机/模拟器中卸载该应用,然后再重新安装(如全新安装)。