在微调器中检索SQLite数据

时间:2017-10-15 13:48:34

标签: android sqlite android-sqlite

我正在使用SQLite数据库,我希望在加载时在Spinner中检索来自一列(USER_NAME)的数据。

当我运行应用程序时,它会崩溃。

这是我到目前为止的情况。在我的UserDBHelper类中,与微调器相关的方法称为getAllNames(),并且在Mark类中我将代码放在OnCreate()

UserContract:

public class UserContract  {

    public static abstract class NewUserInfo{
        public static final String USER_NAME = "user_name";
        public static final String USER_SURNAME = "user_surname";
        public static final String USER_MARK = "user_mark";
        public static final String TABLE_NAME = "user_info";
    }
}

UserDBHelper

    public class UserDBHelper extends SQLiteOpenHelper {

        public static final String DATABASE_NAME = "USERINFO.DB";
        private static final int DATABASE_VERSION = 1;

        private static final String CREATE_QUERY =
                "CREATE TABLE " + UserContract.NewUserInfo.TABLE_NAME + "(" + UserContract.NewUserInfo.USER_NAME + " TEXT,"
                        + UserContract.NewUserInfo.USER_SURNAME + " TEXT,"
                        + UserContract.NewUserInfo.USER_MARK + " TEXT);";

        SQLiteDatabase db;
        UserDBHelper helper;
        Context c;

        public UserDBHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            Log.e("DATABASE OPERATION", "Database created / opened...");


        }


        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(CREATE_QUERY);
            Log.e("DATABASE OPERATION", "Table created...");


        }

        public ArrayList<String> getAllNames(){

            ArrayList<String> list=new ArrayList<String>();
            // Open the database for reading
            SQLiteDatabase db = this.getReadableDatabase();
            // Start the transaction.
            db.beginTransaction();


            try
            {

                String selectQuery = "SELECT * FROM "+ UserContract.NewUserInfo.TABLE_NAME;
                Cursor cursor = db.rawQuery(selectQuery, null);
                if(cursor.getCount() >0)

                {
                    while (cursor.moveToNext()) {
                        // Add province name to arraylist
                        String name= cursor.getString(cursor.getColumnIndex("USER_NAME"));
                        list.add(name);

                    }


                }
                db.setTransactionSuccessful();

            }
            catch (SQLiteException e)
            {
                e.printStackTrace();

            }
            finally
            {
                db.endTransaction();
                // End the transaction.
                db.close();

                // Close database
            }
            return list;


        }


        //GET ALL VALUES
        public Cursor getAllValues()
        {
            String[] columns={UserContract.NewUserInfo.USER_NAME,UserContract.NewUserInfo.USER_SURNAME,UserContract.NewUserInfo.USER_MARK};
            return db.query(UserContract.NewUserInfo.TABLE_NAME, columns, null, null, null, null, null);
        }

        public void addInformations(String name, String surname, String mark, SQLiteDatabase db) {
            ContentValues contentValues = new ContentValues();
            contentValues.put(UserContract.NewUserInfo.USER_NAME, name);
            contentValues.put(UserContract.NewUserInfo.USER_SURNAME, surname);
            contentValues.put(UserContract.NewUserInfo.USER_MARK, mark);
            db.insert(UserContract.NewUserInfo.TABLE_NAME, null, contentValues);
            Log.e("DATABASE OPERATION", "One row inserted...");

        }


        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        }

        public boolean updateData (String name, String surname, String mark){
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put(UserContract.NewUserInfo.USER_NAME,name);
            contentValues.put(UserContract.NewUserInfo.USER_SURNAME,surname);
            contentValues.put(UserContract.NewUserInfo.USER_MARK,mark);
            db.update(UserContract.NewUserInfo.TABLE_NAME, contentValues, " USER_NAME = ?", new String[] { name });
            return true;

        }
}

标记

public class Mark extends Activity {
    Spinner spin;
    EditText uname, usurname, umark;
    Context context =this;
    UserDBHelper userDbHelper ;
    SQLiteDatabase sqLiteDatabase;
    ArrayList<String> names=new ArrayList<String>();
    ArrayAdapter<String> adapter;

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

        uname = (EditText) findViewById(R.id.txtName);
        usurname = (EditText) findViewById(R.id.txtSurname);
        umark = (EditText) findViewById(R.id.txtMark);
        spin=(Spinner) findViewById(R.id.spinner);

        userDbHelper = new UserDBHelper(this);
        ArrayList<String> list=userDbHelper.getAllNames();
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.mark, R.id.text, list);
        spin.setAdapter(adapter);
    }




    public void insertUpdate(View view){
        userDbHelper = new UserDBHelper(getApplicationContext());
        sqLiteDatabase = userDbHelper.getReadableDatabase();
        Cursor cursor = updateData();

        if(cursor.moveToFirst()) {
            userDbHelper.updateData(uname.getText().toString(),
                    usurname.getText().toString(),
                    umark.getText().toString());
            Toast.makeText(Mark.this, "Data updated", Toast.LENGTH_LONG).show();
        }else{
            String name = uname.getText().toString();
            String surname = usurname.getText().toString();
            String mark = umark.getText().toString();

            userDbHelper = new UserDBHelper(context);
            sqLiteDatabase = userDbHelper.getWritableDatabase();
            userDbHelper.addInformations(name, surname, mark, sqLiteDatabase);
            Toast.makeText(getBaseContext(),"Data Saved",Toast.LENGTH_LONG).show();
            userDbHelper.close();
        }
    }

    public Cursor updateData(){
        SQLiteDatabase db = this.userDbHelper.getWritableDatabase();
        Cursor res = db.rawQuery("select * from "+TABLE_NAME.trim()+" WHERE "+USER_NAME.trim()+ " = " + "'"+ uname.getText().toString() + "'" ,null);
        return res;
    }

    public void viewAll(View view) {
        {
            userDbHelper = new UserDBHelper(getApplicationContext());
            sqLiteDatabase = userDbHelper.getReadableDatabase();
            Cursor cursor = getAllData();
            if (cursor.moveToFirst()) {
                String name = cursor.getString(0);
                String surname = cursor.getString(1);
                String  mark = cursor.getString(2);
                uname.setText(name);
                usurname.setText(surname);
                umark.setText(mark);
                // s_surname.setVisibility(View.VISIBLE);
                // s_mark.setVisibility(View.VISIBLE);
            }
        }
    }



    public Cursor getAllData() {
        SQLiteDatabase db = this.userDbHelper.getWritableDatabase();
        //Cursor res = db.rawQuery("select * from "+TABLE_NAME.trim()+" WHERE "+COL_2.trim()+" = 'Lyubo'" , null);
        Cursor res = db.rawQuery("select * from "+TABLE_NAME.trim()+" WHERE "+USER_NAME.trim()+ " = " + "'"+ uname.getText().toString() + "'" ,null);
        return res;
    }}

这是我的Log CAT:

FATAL EXCEPTION: main
                                                                           Process: com.example.lyubo.datatrial, PID: 6056
                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lyubo.datatrial/com.example.lyubo.datatrial.Mark}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                               at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                            Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                               at android.database.CursorWindow.nativeGetString(Native Method)
                                                                               at android.database.CursorWindow.getString(CursorWindow.java:438)
                                                                               at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
                                                                               at com.example.lyubo.datatrial.UserDBHelper.getAllNames(UserDBHelper.java:69)
                                                                               at com.example.lyubo.datatrial.Mark.onCreate(Mark.java:44)
                                                                               at android.app.Activity.performCreate(Activity.java:6679)
                                                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                                                                               at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                               at android.os.Looper.loop(Looper.java:154) 
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                               at java.lang.reflect.Method.invoke(Native Method) 
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

2 个答案:

答案 0 :(得分:1)

您的代码似乎很好,但缺少一件事。
试试这个:

            String selectQuery = "SELECT * FROM "+ UserContract.NewUserInfo.TABLE_NAME;
            Cursor cursor = db.rawQuery(selectQuery, null);
            if(cursor.getCount() >0)
            {
                cursor.moveToFirst(); //missing
                while (cursor.moveToNext()) {
                    // Add province name to arraylist
                    String name= cursor.getString(cursor.getColumnIndex("USER_NAME"));
                    list.add(name);
                }
            }

这应该按预期工作,因为cursor.moveToFirst();将光标放在第一个位置而不是第0个位置。

答案 1 :(得分:0)

这解决了我的问题:

UserDBHelper

public List<String> getAllNames(){
    List<String> labels = new ArrayList<String>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + UserContract.NewUserInfo.TABLE_NAME;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            labels.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning lables
    return labels;
}

Mark Class(主要活动):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mark);

    uname = (EditText) findViewById(R.id.txtName);
    usurname = (EditText) findViewById(R.id.txtSurname);
    umark = (EditText) findViewById(R.id.txtMark);
    spin=(Spinner) findViewById(R.id.spinner);

    loadSpinnerData();

}

private void loadSpinnerData() {
    // database handler
    UserDBHelper db = new UserDBHelper(getApplicationContext());

    // Spinner Drop down elements
    List<String> lables = db.getAllNames();

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, lables);

    // Drop down layout style - list view with radio button
    dataAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spin.setAdapter(dataAdapter);
}