SQL Lite android app login

android, authentication, database, passwords, sqlite

Solution

You can try below way.

Create class called DBAdapter.java and add following code.

public class DBAdapter {
    private static final String DATABASE_NAME         = "Your database name"; 
    private static final String DATABASE_CREATE_USERS = "create table TABLE_NAME (
    UserID integer primary key autoincrement, " + "Username text, Password text);" ; 

    private static final String DATABASE_SELECT_USERS = "users";
    public static final String USER_ID       = "UserID";
    public static final String USER_NAME     = "Username";
    public static final String USER_PASSWORD = "Password ";

    private final Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;  

    DBAdapter(Contex ctx) {
        this.context = ctx;
        DBHelper     = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        public void onCreate(SQLiteDatabase db) {
            System.out.println("Creating table");
            db.execSQL(DATABASE_CREATE_USERS);
        }

        public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

        }
    }   

    public DBAdapter open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

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

    public Cursor fetchUser(String username, String password) {  
        Cursor myCursor = db.query(DATABASE_SELECT_USERS,   
        new String[] { USER_ID, USER_NAME, USER_PASSWORD },   
                         USER_NAME + "='" + username + "' AND " +   
                         USER_PASSWORD + "='" + password + "'", null, null, null, null);  

        if (myCursor != null) {  
            myCursor.moveToFirst();  
        }  
        return myCursor;  
    }  

    public void InsertData(String username, String password) {
        String sql = "INSERT INTO users (Username,Password) VALUES('"+username+"','"+password+"')";
        db.execSQL(sql);
    }
}

and then create your Java file

Login.java

public class Login extends Activity 
{

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

        final EditText txt_username = (EditText) findViewById(R.id.editText1);
        final EditText txt_psw      = (EditText) findViewById(R.id.editText2);

        Button btn_signin = (Button) findViewById(R.id.button1);

        // Inner class to implement Button Listener when button is clicked.
        btn_signin.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {                   
                DBAdapter db = new DBAdapter(getBaseContext());
                db.open();                              
                db.InsertData("Chao", "1234");              
                Log.v("LoginDetails", txt_username.getText().toString()+"../.."
                      +txt_psw.getText().toString());

                // Accessing user using the fetchUser method we created in DBAdapter
                Cursor cur = db.fetchUser( txt_username.getText().toString(), 
                                           txt_psw.getText().toString());

                // Use this line if you want to see the number of users with these login details
                System.out.println("cur.getCount()   "+cur.getCount());

                if(cur.getCount()!=0) {
                    String usn=cur.getString(1);
                    if(usn.equals("Chao")) {   

                    }
                    else { 

                    }

                    System.out.println("Query succedded");
                    Toast.makeText(getBaseContext(), "Success! Valid User name and password", Toast.LENGTH_LONG).show();

                    db.close();
                }
                else
                    Toast.makeText(getBaseContext(), "Please enter Valid User name and password", Toast.LENGTH_LONG).show();
            } //Closes the onClick method
        }); //Closes the onClickListener
    }
}

Problem

I am working on a game at the moment and all I want is my login screen to be able to check that the username and password I have already stored in my database is correct and when it is correct and the log in button is clicked to open a new activity. I have my database built and also a login I just need to figure out how to check against my database not just the text in the fields. I already have a pre-added login stored in the database: Username: test Password: 1234 Thanks in advance p.s I am completely new to Java and SQL lite this is only for school work and is in no way going to be used in the real world I only want it to be simple :) Login Screen Activity: ``` package com.C05025.noughtsandcrosses; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View; import android.widget.EditText; public class LogInScreen extends Activity { EditText txtUsername; EditText txtPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loginscreen); txtUsername = (EditText) findViewById(R.id.EditUsername); txtPassword = (EditText) findViewById(R.id.EditPassword); } public void newLogIn(View view) { if(txtUsername.getText().toString().equals("test") && txtPassword.getText().toString().equals("1234")) { Intent intent = new Intent(LogInScreen.this, MainMenu.class); startActivity(intent); } } ``` Database Class: ``` package com.C05025.noughtsandcrosses; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DBHandler extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "userDB.db"; private static final String TABLE_USERS = "users"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_PASSWORD = "password"; public DBHandler(Context context, String name, CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "(" + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT," + COLUMN_PASSWORD + " INTEGER" + ")"; db.execSQL(CREATE_USER_TABLE); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { } public void addUser(LogIn user) { ContentValues values = new ContentValues(); values.put(COLUMN_NAME, user.getName()); values.put(COLUMN_PASSWORD, user.getPassword()); SQLiteDatabase db = this.getWritableDatabase(); db.insert(TABLE_USERS, null, values); db.close(); } public LogIn findUser(String Username) { String query = "Select * FROM " + TABLE_USERS + " WHERE " + COLUMN_NAME + " = \"" + Username + "\""; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); LogIn User = new LogIn(); if (cursor.moveToFirst()) { cursor.moveToFirst(); User.setName(cursor.getString(1)); User.setPassword(Integer.parseInt(cursor.getString(2))); cursor.close(); } else { User = null; } db.close(); return User; } } ```

Original source