-2

Ok so I am currently trying to make a Simple Register and Log in page using SQL Lite. I currently have no problems with creating or inserting values into the database. What I want to do is using an if-else statement for the Login, whereby it will deny the user if there is no record (or mistyped) found in the database and will only allow when they enter the username and password correctly. Attached is my code. Please advise. Thanks

package mdad.project;

import com.example.manandhowproject.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {
    SQLiteDatabase db;
    Button btnLogin, btnSignUp;
    EditText etUsername, etPassword;
    SQLiteOpenHelper dbhelper;
    Cursor cursor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    etUsername = (EditText)findViewById(R.id.etUsername);
    etPassword = (EditText)findViewById(R.id.etPassword);
    Button button = (Button)findViewById(R.id.btnLogin);
    db = dbhelper.getReadableDatabase();

    button.setOnClickListener(new OnClickListener(){
        public void onClick (View V){
        Toast.makeText(getApplicationContext(), "Log In Success ! ", Toast.LENGTH_LONG).show();
        Intent msg1 = new Intent(Login.this, Userreg.class);
        startActivity(msg1);
        }
    });

    Button btnSignUp = (Button) findViewById (R.id.btnSignUp);
    btnSignUp.setOnClickListener(new OnClickListener (){
        public void onClick (View V) {
            Toast.makeText(getApplicationContext(), "Sign Up Success ! ", Toast.LENGTH_LONG).show();

            String username= etUsername.getText().toString();
            String password= etPassword.getText().toString();
            String sql = "insert into Registration (Username ,Password) values( '"+username+"','"+password+"')";
            String result = updateTable(sql);
            etUsername.setText("");
            etPassword.setText("");
        }});

    String sql="create table if not exists Registration (recld integer PRIMARY KEY autoincrement, Username text, Password text)"; 
    String result = createDatabase(sql, "Reg.db");

}

String createDatabase(String sql, String dbName) {
    try{
        System.out.println(sql);
        db = SQLiteDatabase.openOrCreateDatabase("sdcard/" + dbName,null);
        db.beginTransaction();
        db.execSQL(sql);
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    catch (Exception e){
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        System.out.println(e.toString());
        return ("error open DB");
    }

    return "";
}

String updateTable(String sql)
 {
 try{
 System.out.println(sql);
 db.beginTransaction();
 db.execSQL(sql);
 db.setTransactionSuccessful();
 db.endTransaction();

 }catch (Exception e) { System.out.println(e.toString());
 return ("Error updating DB");
 }
 return ("DB updated");
 }





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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

Rizwan Atta
  • 3,222
  • 2
  • 19
  • 31
Kelvin How
  • 25
  • 9

2 Answers2

2

Here you go:

You need to match the username/password with the table/database.

button.setOnClickListener(new OnClickListener(){
    public void onClick (View V){
    if(login(etUsername.getText(), etPassword.getText()) == 1){
        Toast.makeText(getApplicationContext(), "Log In Success ! ", Toast.LENGTH_LONG).show();
        Intent msg1 = new Intent(Login.this, Userreg.class);
        startActivity(msg1);
    }else{
        Toast.makeText(getApplicationContext(), "Wrong Username/password combination", Toast.LENGTH_LONG).show();
    }

    }
});

Create this method:

public int login(String username, String password){

String[] selectionArgs = new String[]{username, password};
try
{
    int i = 0;
    Cursor c = null;
    c = db.rawQuery("select * from Registration where username=? and password=?", selectionArgs);
    c.moveToFirst();
    i = c.getCount(); 
    c.close(); 
    return i;
}
catch(Exception e)
{
    e.printStackTrace();
}
return 0;

}

Comment if you face any problems. Happy to help.

iamgopal
  • 634
  • 5
  • 12
  • that's a nice answer great! going – Rizwan Atta Jan 29 '18 at 11:19
  • @iamgopal Hi, thanks for the advise, however I still encounter an error, there was a red underline on the login in the line: if(login(etUsername.getText(), etPassword.getText()) == 1) when i hover my mouse it says "The method login(String, String) in the type Login is not applicable for the arguments (Editable, Editable)" – Kelvin How Jan 29 '18 at 11:31
  • you are directly sending the editText.getText in the login method you should first convert Text into String in order to work it with the method you made! @iamgopal – Rizwan Atta Jan 29 '18 at 12:01
  • @KelvinHow replace that line with this if(login(etUsername.getText().toString(), etPassword.getText().toString()) == 1). Please accept the answer if it solved your purpose as it was answered first :) – iamgopal Jan 29 '18 at 12:27
0

CHECK THIS THREAD TOO CURSOR DISCUSSION on STACK Try something like this!

I would recommend to make a. separate class inherited by SqliteOpenHelper so you could work with more clean code

public Cursor  getUserLogedIn(String Sql,SQLiteDatabase db){

   Cursor mCursor =db.rawQuery(sql)

   return mCursor;
}

//then do this to read in your click listener after execution of the method

Cursor incmoningCursor = getUserLogedIn("select * from Registration where username="+incomingUserEmail+ "and password="+incmoingPassword,db)
try {
    while (cursor.moveToNext()) {
        ...
       //read out the cursor and compare each string with your        //editTextString here
    }
} finally {
    cursor.close();
}
}

or

you can send directly your entered texts into the method like this

public int checkLogin(String incomingUsername, String incomingPassword){

String[] selectionArgs = new String[]{incomingUsername, incomingPassword};
try
{
    int i = 0;
    Cursor c = null;
    c = db.rawQuery("select * from Registration where username=? and password=?", selectionArgs);
    c.moveToFirst();
    i = c.getCount(); 
    c.close(); 
    return i;
}
catch(Exception e)
{
    e.printStackTrace();
}
return 0;

in the main activity of your button listener try this!

 button.setOnClickListener(new OnClickListener(){
    public void onClick (View V){
    if(checkLogin(etUsername.getText().toString(), etPassword.getText().toString()) == 1){
        Toast.makeText(getApplicationContext(), "Log In Success ! ", Toast.LENGTH_LONG).show();
        Intent msg1 = new Intent(Login.this, Userreg.class);
        startActivity(msg1);
    }else{
        Toast.makeText(getApplicationContext(), "Wrong Username/password combination", Toast.LENGTH_LONG).show();
    }
}

});

Rizwan Atta
  • 3,222
  • 2
  • 19
  • 31
  • Hi, I still I tried using your last method to do but what should I put in the click listener? if I put if(checkLogin(etUsername.getText(), etPassword.getText()) == 1) I will get this error saying "The method login(String, String) in the type Login is not applicable for the arguments (Editable, Editable)" – Kelvin How Jan 29 '18 at 11:55
  • it should be like this brother if(checkLogin(etUsername.getText().toString(), etPassword.getText().toString()) == 1) – Rizwan Atta Jan 29 '18 at 11:56