Android SQL查询nullpointer无法从数据库中获取数据

时间:2022-08-07 16:13:42

here is the LogCat I can't post image so i put it in google drive

这里是LogCat我无法发布图像,所以我把它放在谷歌驱动器

link here

////////And here is the DB///////

////////这是DB ///////

    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.SQLiteDatabase.CursorFactory;

    import android.database.sqlite.SQLiteOpenHelper;

    public class UserDB {

        public static final String TABLE_USER = "User";
        public static final String ID = "ID";
        public static final String USERNAME = "USERNAME";
        public static final String PASSWORD = "PASSWORD";
        public static final String CHKPASSWORD = "CHKPASSWORD";
        public static final String SEX = "SEX";
        public static final String eat = "eat";
        public static final String drink = "drink";
        public static final String smoke = "smoke";
        public static final String conctrolweigh = "conctrolweigh";
        public static final String blosuger = "blosuger";
        public static final String hospital = "hospital";
        private Context Context = null;
        public static final String Education = "Education";


        public static class DatabaseHelper extends SQLiteOpenHelper{
            public static final String DATABASE_NAME = "diabetes.db";   
            private static final int DATABASE_VERSION = 1;
            //usertable
             public DatabaseHelper(Context context, CursorFactory factory) {
                    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
                }
            public static final String TABLE_USER_CREATE =
                    "CREATE TABLE " + TABLE_USER 
                    + "(" 
                    + ID  + "  INTEGER PRIMARY KEY AUTOINCREMENT, "
                      + USERNAME + " text , "
                      + PASSWORD+ " text ,"
                      + CHKPASSWORD+ " text ,"
                      + SEX+ " text ,"
                      + eat + " text , "
                      + drink + " text, "
                      + smoke + " text, "
                      + conctrolweigh + " text, "
                      + blosuger + " text, "
                      + hospital + " text, "
                      + Education + " text);";

            public DatabaseHelper(Context context) {
                super(context, DATABASE_NAME, null, 1);

            }
            @Override   
            public void onOpen(SQLiteDatabase db) {     

                    super.onOpen(db);       
                    // 每次成功打開資料庫後首先被執行     
                } 
             @Override
             public synchronized void close() {
                 super.close();
             }  
            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL(TABLE_USER_CREATE);

            }
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                db.execSQL("DROPB TABLE IF EXISTS " + TABLE_USER);      
                onCreate(db);
            }
        }

        public DatabaseHelper dbHelper;
        public SQLiteDatabase db;
        public UserDB(Context context){
            this.Context = context;

            DatabaseHelper openHelper = new DatabaseHelper(this.Context);
                this.db = openHelper.getWritableDatabase();
        }
        public UserDB open() throws SQLException{
            dbHelper = new DatabaseHelper(Context);
             db = dbHelper.getWritableDatabase();

            return this;

        }

        public void close(){
            dbHelper.close();
        }
    //add user

    public void insertEntry(String ID, String PWD,String CHPW,String SEX,String eat,String drink,String smoke,String conctrolweigh,String blosuger,String hospital,String Education){       
            if (PWD.equals(CHPW)){

                ContentValues newValues = new ContentValues();
                newValues.put("USERNAME", ID);
                newValues.put("PASSWORD", PWD);
                newValues.put("CHKPASSWORD", CHPW);
                newValues.put("SEX", SEX);
                newValues.put("eat", eat);
                newValues.put("drink", drink);
                newValues.put("smoke", smoke);
                newValues.put("conctrolweigh", conctrolweigh);
                newValues.put("blosuger", blosuger);
                newValues.put("hospital", hospital);
                newValues.put("Education", Education);
                db.insert(TABLE_USER, null, newValues);     

            }else{ 
        }
    }
    public String getSinlgeEntry(String userName) {
        Cursor cursor = db.query("User", null, " USERNAME=?",
                new String[] { userName }, null, null, null);
        if (cursor.getCount() < 1) // UserName Not Exist
            return "Not Exist";
        cursor.moveToFirst();
        String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
        return password;
    }

    public SQLiteDatabase getReadableDatabase() {
        // TODO Auto-generated method stub
        return null;
    }
}




//////here is the Activity//////////



    public class SelfteachingActivity extends Activity {

        Button btnselback,tvartical ,tvfood,tvhealth,tvexcise;
        TextView tvid,tvstore,tveat,tvhospital,tvblosuger,tvconctrolweigh,tvdrink,tvsmoke,tvSEX,tvEducation;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_selfteaching);
            findViews();
            setListeners();
            //openDatabase();
            String username= (this.getIntent().getExtras().getString("username"));
            tvstore.setText(username);
            tvid.setText(tvstore.getText().toString());

            query();

        }
        private void  query() {  

            UserDB helper = new UserDB(this);
            SQLiteDatabase db = helper.getReadableDatabase();
            helper.open();
        if(helper.getReadableDatabase() == null){
            Log.i("Log Activity Test", "helper is null!!!!!!!!!");
        }
             String user = tvstore.getText().toString();
             try {
                    Log.i("Log Activity Test", "start db!!");
                    Cursor cursor = db.rawQuery("SELECT SEX,hospital,blosuger,drink,conctrolweigh,smoke,Education,eat FROM User Where USERNAME ='"+user+"'", null);
                    if(cursor!=null){

                    int rows_num = cursor.getCount();
                    cursor.moveToFirst();
                    while (!cursor.isAfterLast()) {
                            Integer Id = cursor.getInt(cursor.getColumnIndex("id"));        


                        tvSEX.setText(cursor.getString(cursor.getColumnIndex("SEX")));
                        tvhospital.setText(cursor.getString(cursor.getColumnIndex("hospital")));
                        tvblosuger.setText(cursor.getString(cursor.getColumnIndex("blosuger")));
                        tvdrink.setText(cursor.getString(cursor.getColumnIndex("drink")));
                        tvconctrolweigh.setText(cursor.getString(cursor.getColumnIndex("conctrolweigh")));
                        tvsmoke.setText(cursor.getString(cursor.getColumnIndex("smoke")));
                        tvEducation.setText(cursor.getString(cursor.getColumnIndex("Education")));
                        tveat.setText(cursor.getString(cursor.getColumnIndex("eat")));

                        cursor.moveToNext();
                    }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {

                }
            }
        private long exitTime = 0; 
        @Override 
        public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ 
        if((System.currentTimeMillis()-exitTime) > 2000){ 
        Toast.makeText(getApplicationContext(), "再按一次返回鍵退出", Toast.LENGTH_SHORT).show(); 
        exitTime = System.currentTimeMillis(); 
        } else { 
        finish(); 
        System.exit(0); 
        } 
        return true; 
        } 
        return super.onKeyDown(keyCode, event); 
        } 

        private void findViews(){
            btnselback = (Button)findViewById(R.id.buttonselback);
            tvartical = (Button)findViewById(R.id.buttonartical);
            tvfood = (Button)findViewById(R.id.buttonfood);
            tvhealth = (Button)findViewById(R.id.buttonhealth);
            tvexcise = (Button)findViewById(R.id.buttonescise);
            tvid = (TextView)findViewById(R.id.tVsid);
            tvstore = (TextView)findViewById(R.id.tvstore);
            tveat = (TextView)findViewById(R.id.tveat);
        tvhospital= (TextView)findViewById(R.id.tvhospital);
        tvblosuger= (TextView)findViewById(R.id.tvblosuger);
        tvconctrolweigh= (TextView)findViewById(R.id.tvconctrolweigh);
        tvdrink= (TextView)findViewById(R.id.tvdrink);
        tvsmoke= (TextView)findViewById(R.id.tvsmoke);
        tvSEX= (TextView)findViewById(R.id.tvSEX);
        tvEducation= (TextView)findViewById(R.id.tvEducation);
        }
        private void setListeners(){
            //回上一頁
            btnselback.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String username = tvstore.getText().toString();
                        Intent intent = new Intent();
                        intent.setClass(SelfteachingActivity.this, LoginActivity.class);
                        intent.putExtra("username", username );

                        startActivity(intent);
                        SelfteachingActivity.this.finish();
                    }
                });
                //衛教文章
                tvartical.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        String username = tvstore.getText().toString();
                        Intent intent = new Intent();
                        intent.setClass(SelfteachingActivity.this, ArticalActivity.class);
                        intent.putExtra("SEX", tvSEX.getText().toString() );
                        intent.putExtra("username", username );
                        intent.putExtra("hospital", tvhospital.getText().toString());
                        intent.putExtra("blosuger", tvblosuger.getText().toString() );
                        intent.putExtra("drink", tvdrink.getText().toString() );
                        intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
                        intent.putExtra("smoke", tvsmoke.getText().toString());
                        intent.putExtra("Education", tvEducation.getText().toString());
                        intent.putExtra("eat", tveat.getText().toString());
                        startActivity(intent);
                        SelfteachingActivity.this.finish();

                    }
                });
                //食物衛教
                tvfood.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String username = tvstore.getText().toString();
                        Intent intent = new Intent();
                        intent.setClass(SelfteachingActivity.this, FoodActivity.class);
                        intent.putExtra("username", username );
                        intent.putExtra("SEX", tvSEX.getText().toString() );
                        intent.putExtra("hospital", tvhospital.getText().toString());
                        intent.putExtra("blosuger", tvblosuger.getText().toString() );
                        intent.putExtra("drink", tvdrink.getText().toString() );
                        intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
                        intent.putExtra("smoke", tvsmoke.getText().toString());
                        intent.putExtra("Education", tvEducation.getText().toString());
                        intent.putExtra("eat", tveat.getText().toString());
                        startActivity(intent);
                        SelfteachingActivity.this.finish();

                    }
                });
                //健康衛教
                tvhealth.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String username = tvstore.getText().toString();
                        Intent intent = new Intent();
                        intent.setClass(SelfteachingActivity.this, HealthActivity.class);
                        intent.putExtra("username", username );
                        intent.putExtra("SEX", tvSEX.getText().toString() );
                        intent.putExtra("hospital", tvhospital.getText().toString());
                        intent.putExtra("blosuger", tvblosuger.getText().toString() );
                        intent.putExtra("drink", tvdrink.getText().toString() );
                        intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
                        intent.putExtra("smoke", tvsmoke.getText().toString());
                        intent.putExtra("Education", tvEducation.getText().toString());
                        intent.putExtra("eat", tveat.getText().toString());
                        startActivity(intent);
                        SelfteachingActivity.this.finish();

                    }
                });
                //運動衛教
                tvexcise.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String username = tvstore.getText().toString();
                        Intent intent = new Intent();
                        intent.setClass(SelfteachingActivity.this, ExciseActivity.class);
                        intent.putExtra("username", username );
                        intent.putExtra("SEX", tvSEX.getText().toString() );
                        intent.putExtra("hospital", tvhospital.getText().toString());
                        intent.putExtra("blosuger", tvblosuger.getText().toString() );
                        intent.putExtra("drink", tvdrink.getText().toString() );
                        intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
                        intent.putExtra("smoke", tvsmoke.getText().toString());
                        intent.putExtra("Education", tvEducation.getText().toString());
                        intent.putExtra("eat", tveat.getText().toString());
                        startActivity(intent);
                        SelfteachingActivity.this.finish();

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

    }

Problem:

1.i don't get any data from SQL but no crash

1.i不从SQL获取任何数据但没有崩溃

what is the problem with my code?

我的代码有什么问题?

the program stop in here

程序停在这里

Cursor cursor = db.rawQuery("SELECT SEX,hospital,blosuger,drink,conctrolweigh,smoke,Education,eat FROM User Where USERNAME ='"+user+"'", null);

and say null pointer , i check the db and is null , i don't know how this happen.

并说空指针,我检查数据库并且为空,我不知道这是怎么发生的。

plz help me

请帮助我

1 个解决方案

#1


0  

Method that you call

你打电话的方法

SQLiteDatabase db = helper.getReadableDatabase();

returns your null due to your code:

由于您的代码返回null:

public SQLiteDatabase getReadableDatabase() {
    // TODO Auto-generated method stub
    return null;
}

#1


0  

Method that you call

你打电话的方法

SQLiteDatabase db = helper.getReadableDatabase();

returns your null due to your code:

由于您的代码返回null:

public SQLiteDatabase getReadableDatabase() {
    // TODO Auto-generated method stub
    return null;
}