在Android中使用SqLite进行身份验证时出现空指针异常

时间:2014-05-12 06:58:53

标签: java android sqlite

执行Query进行身份验证时,它会给出Null Value。我已经研究了这么多,但我没有找到答案。请解决这个,因为我是初学者在android。

我的活动是

public class MainActivity extends ActionBarActivity {

//private ImageView _imagView;
//private Timer _timer;
//private int _index;
//private MyHandler handler;

 DbHandler db=new DbHandler(this);
EditText  usertxt;
EditText  passtxt;

String auth="";
String utxt="";
String ptxt="";
long i;
Cursor cur;


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

  //handler= new MyHandler();
  //  _imagView=(ImageView) findViewById(R.id.imageView1);

   // _index=1;
   // _timer= new Timer();
   // _timer.schedule(new TickClass(), 850, 1500);

    //......................................//



        Log.d("Insert: ", "Inserting ..");  


        db.deleteAll();

        db.addContact(new ModelAuth(" Sohaib ", " Tariq "," User "));

    // Reading all contacts
    Log.d("Reading: ", "Reading all contacts.."); 
     List<ModelAuth> contacts = db.getAllContacts();       

    for (ModelAuth cn : contacts) {
        String log = "Id: "+ cn.get_id() + " ,Username: " + cn.getUsername() + " ,Password: " + cn.getPassword() +" ,Auth:" 
                + cn.getAuth();
            // Writing Contacts to log
    Log.d("Name: ", log);
}




 /*   if(i<0 || i == 0) {
        Toast.makeText(getApplicationContext(), "Not Inserting", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(getApplicationContext(), " Inserted", Toast.LENGTH_LONG).show();
    }*/


    usertxt= (EditText)findViewById(R.id.editText1);
    passtxt=(EditText)findViewById(R.id.editText2);

   utxt = usertxt.getText().toString();
   ptxt = passtxt.getText().toString();



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

        @Override
        public void onClick(View v) {



               utxt = usertxt.getText().toString();
               ptxt = passtxt.getText().toString();

                 auth=db.Authen(utxt,ptxt);

                              if(auth.equals("User")){

                                  Intent intent=new Intent(MainActivity.this,Wheels.class);
                                   startActivity(intent);
                                        }

                                if(auth.equals("Admin")){

                                    Intent intent=new Intent(MainActivity.this,Admin.class);
                                     startActivity(intent);
                }

        }
    });



}

HbHelper类是

public class DbHandler extends SQLiteOpenHelper{


// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "carshow";

// Contacts table name
private static final String TABLE_AUTH = "auth_table";

// Contacts Table Columns names
private static final String KEY_ID = "_id";
private static final String KEY_USERNAME = "username ";
private static final String KEY_PASSWORD = "password ";
private static final String KEY_AUTH = "auth ";


public DbHandler(Context context) {
    super(context,DATABASE_NAME, null, DATABASE_VERSION);

}

// ......... Crud操作................... //

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_AUTH_TABLE = "CREATE TABLE " + TABLE_AUTH + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_USERNAME + " TEXT,"
            + KEY_PASSWORD + " TEXT," + KEY_AUTH + " TEXT" + ");";
    db.execSQL(CREATE_AUTH_TABLE);

}

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

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_AUTH);
      onCreate(db);

}


public void addContact(ModelAuth authen) {



    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_USERNAME, authen.getUsername()); 
    values.put(KEY_PASSWORD, authen.getPassword()); 
    values.put(KEY_AUTH, authen.getAuth());

    // Inserting Row
    db.insert(TABLE_AUTH, null, values);
    db.close(); // Closing database connection


}

    public String Authen(String usertxt,String passtxt){

  SQLiteDatabase db = this.getReadableDatabase();

  String aut="";

  String query = "SELECT  * FROM " + TABLE_AUTH + " WHERE " + KEY_USERNAME + " = '" +  usertxt   +  "' AND " + KEY_PASSWORD + " = '" +  passtxt  + "' " ;

  Cursor c= db.rawQuery(query, null);

  if(c!=null && c.moveToFirst()){

          c.getString(3);

          return aut;
  }

      if (c != null && !c.isClosed()) {
           c.close();
       }
       if (db!=null){
           db.close();
       }



   return null;
       }

logcat的

05-12 12:01:02.977: E/AndroidRuntime(304): FATAL EXCEPTION: main
05-12 

12:01:02.977: E/AndroidRuntime(304): java.lang.NullPointerException
05-12 

12:01:02.977: E/AndroidRuntime(304):    at                     

com.activity.carsshow.MainActivity$1.onClick                    

(MainActivity.java:113)

05-12 12:01:02.977: E/AndroidRuntime(304):  at                               

            android.view.View.performClick(View.java:2408)
05-12 12:01:02.977: 

E/AndroidRuntime(304):  at android.view.View                    

$PerformClick.run(View.java:8816)

1 个答案:

答案 0 :(得分:0)

您应该在比较String的值之前进行检查:如下所示

if(auth != null){
    if(auth.equals("User")){
       Intent intent=new Intent(MainActivity.this,Wheels.class);
       startActivity(intent);
    }

    if(auth.equals("Admin")){
       Intent intent=new Intent(MainActivity.this,Admin.class);
       startActivity(intent);
    }
}