简体   繁体   中英

Cant validate Login on Android app using a SQLite db

I am having a problem validating my login for my android app. I have 2 fields that require user to enter email and password, if both exist in db then they will be taken to mainscreen (log in successful) if incorrect error will appear. I have tried everything but still doesnt work! Please help I have posted my code below.

package com.example.finalproject;



import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener{

    EditText mEmailAdd;
    EditText mPassword;
    private SQLiteAdapter mydb = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        //addListenerOnButton();
    }

    public void onCreateMainscreen(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screenmain_activity);

         Button mNewUser = (Button)findViewById(R.id.btnLogMain);
            mNewUser.setOnClickListener(this);
    }








    public void onClick(View v) {

        switch(v.getId()){

        case R.id.btnLogMain:
            mEmailAdd = (EditText)findViewById(R.id.email);
            mPassword = (EditText)findViewById(R.id.password);

            String uname = mEmailAdd.getText().toString();
            String pass = mPassword.getText().toString();

            if(uname.equals("") || uname == null){
                Toast.makeText(getApplicationContext(), "email Empty", Toast.LENGTH_SHORT).show();
            }else if(pass.equals("") || pass == null){
                Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
            }else{
                boolean validLogin = validateLogin(uname, pass, LoginActivity.this);
                if(validLogin){
                    System.out.println("In Valid");
                    Intent i = new Intent(LoginActivity.this, MainMenuActivity.class);
                    startActivity(i);
                    finish();
                }
            }
            break;


        }
    }

        //  @SuppressWarnings("deprecation")

    public boolean validateLogin(String uemail, String pass, Context context) {

        mydb = new SQLiteAdapter(this);
        SQLiteAdapter db = mydb.openToWrite();
        //SELECT
        String[] columns = {"_id"};

        //WHERE clause
        String selection = "email=? AND password=?";

        //WHERE clause arguments
        String[] selectionArgs = {uemail,pass};

        Cursor cursor = null;
        try{
        //SELECT _id FROM login WHERE email=uemail AND password=pass
        cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);

        //  startManagingCursor(cursor);

        }catch(Exception e){
            e.printStackTrace();
        }
        int numberOfRows = cursor.getCount();

        if(numberOfRows <= 0){

            Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
            return false;
        }


        return true;
    }

    public void onDestroy(){
        super.onDestroy();
        mydb.close();
    }


}

DATABASE CLASS

package com.example.finalproject;

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

public class SQLiteAdapter {

 public static final String MYDATABASE_NAME = "MY_PROJECT_DATABASE";
 public static final String MYDATABASE_TABLE = "MY_USERS_TABLE";
 public static final int MYDATABASE_VERSION = 1;
 public static final String KEY_ID = "_id";
 public static final String KEY_NAME = "name";
 public static final String KEY_EMAIL = "email";
 public static final String KEY_PASSWORD = "password";

 //create table MY_DATABASE (ID integer primary key, Content text not null);
 private static final String SCRIPT_CREATE_DATABASE =
  "create table " + MYDATABASE_TABLE + " ("
  + KEY_ID + " integer primary key autoincrement, "
  + KEY_NAME + " text not null, "
  + KEY_EMAIL + " text not null, "
  + KEY_PASSWORD + " text not null);";

 private SQLiteHelper sqLiteHelper;
 private SQLiteDatabase sqLiteDatabase;

 private Context context;

 public SQLiteAdapter(Context c){
  context = c;
 }

 public SQLiteAdapter openToRead() throws android.database.SQLException {
  sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
  sqLiteDatabase = sqLiteHelper.getReadableDatabase();
  return this; 
 }

 public SQLiteAdapter openToWrite() throws android.database.SQLException {
  sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
  sqLiteDatabase = sqLiteHelper.getWritableDatabase();
  return this; 
 }

 public void close(){
  sqLiteHelper.close();
 }

 public long insert(String name, String email, String password){

  ContentValues contentValues = new ContentValues();
  contentValues.put(KEY_NAME, name);
  contentValues.put(KEY_EMAIL, email);
  contentValues.put(KEY_PASSWORD, password);
  return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
 }

 public int deleteAll(){
  return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
 }

 public Cursor queueAll(){
  String[] columns = new String[]{KEY_ID, KEY_NAME, KEY_EMAIL,KEY_PASSWORD};
  Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
    null, null, null, null, null);

  return cursor;
 }

 public class SQLiteHelper extends SQLiteOpenHelper {

  public SQLiteHelper(Context context, String name,
    CursorFactory factory, int version) {
   super(context, name, factory, version);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
   // TODO Auto-generated method stub
   db.execSQL(SCRIPT_CREATE_DATABASE);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   // TODO Auto-generated method stub
  }
 } 
}

not your error, but change

if(uname.equals("") || uname == null){ // throws nullpointerexception if uname == null

to

if(uname == null || uname.length() == 0 ){ // throws no exception and also checks the " "

Not sure if this was just a copy-paste error but the code as provided not only doesn't compile, but never sets up the click listener for the login button either. Here's what I modified to make it both compile and query the database.

In SQLiteAdapter :

public SQLiteDatabase openToWrite() throws android.database.SQLException {
    sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
            MYDATABASE_VERSION);
    sqLiteDatabase = sqLiteHelper.getWritableDatabase();
    return sqLiteDatabase;
}

In LoginActivity :

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_activity);
    //addListenerOnButton();

    Button mNewUser = (Button)findViewById(R.id.btnLogMain);
    mNewUser.setOnClickListener(this);
}

public void onCreateMainscreen(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screenmain_activity);

     Button mNewUser = (Button)findViewById(R.id.btnLogMain);
     mNewUser.setOnClickListener(this);
}
 public boolean validateLogin(String uemail, String pass, Context context) {

    mydb = new SQLiteAdapter(this);
    SQLiteDatabase db = mydb.openToWrite();
    //SELECT
    String[] columns = {"_id"};

    //WHERE clause
    String selection = "email=? AND password=?";

    //WHERE clause arguments
    String[] selectionArgs = {uemail,pass};

    Cursor cursor = null;
    try{
    //SELECT _id FROM login WHERE email=uemail AND password=pass
    cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);

    //  startManagingCursor(cursor);

    }catch(Exception e){
        e.printStackTrace();
    }
    int numberOfRows = cursor.getCount();

    if(numberOfRows <= 0){

        Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
        return false;
    }


    return true;
}

Note also that this code will never insert anything into the database, either. I assume this will be done elsewhere. Further there are many naming convention and general good practices being broken here.

A few issues:

  • Never do database work on the main thread.
  • Variables prefixed with 'm' indicate they are member variables of the class.
  • Be sure to use the @Override notation when appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM