SQLite username check with EditText value - java

Hi i have bit problem in login actually i"m trying to tesing login by checking username from databse and edit text value but its not working . the following is my codes .
i'm bit confussed about to get the EditTextvalue
package com.example.employeemanager;
import android.app.Activity;
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 Login extends Activity {
SQLiteDatabase db;
EditText unameedt;
String unam;
String pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button logbtn = (Button) findViewById(R.id.loginbtn);
Button signup = (Button) findViewById(R.id.signup);
EditText unameedt = (EditText) findViewById(R.id.editText1);
EditText passedt = (EditText) findViewById(R.id.editText2);
db = openOrCreateDatabase("Employeemanager", MODE_PRIVATE, null);
unam = unameedt.getText().toString();
pass = passedt.getText().toString();
logbtn.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Cursor c = db.rawQuery(
"SELECT username, password from Employee", null);
if (c != null) {
if (c.moveToFirst()) {
do {
String uname = c.getString(c
.getColumnIndex("username"));
String upass = c.getString(c
.getColumnIndex("password"));
if (uname.equals(unam)) {
StartActivity(new Intent(Login.this, Home.class));
}
} while (c.moveToNext());
}
}
}
});
signup.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, Emp_signup.class));
}
});
}
}

Put your
unam = unameedt.getText().toString();
pass=passedt.getText().toString();
into butonClick event
logbtn.setOnClickListener(new OnClickListener()
{
unam = unameedt.getText().toString();
pass=passedt.getText().toString();
});

Its simple but looks like a big thing while start learning Android. What you doing now is you got the value in onCreate
unam = unameedt.getText().toString();
pass = passedt.getText().toString();
So, now the unameand pass is empty because while onCreate there is no values set to the corresponding EditText.
In OnClick Method you comparing the Value from Edittext and from database
if (uname.equals(unam)) {//if(usernamefromDatabase.equals(emptyValue))
StartActivity(new Intent(Login.this, Home.class));
}
Thats where the problem is.
What you want to do now is get the unam and pass values in onClick
unam = unameedt.getText().toString();
pass = passedt.getText().toString();
if (uname.equals(unam)) {//if(usernamefromDatabase.equals(valueyouentered))
StartActivity(new Intent(Login.this, Home.class));
}
It should work now.

Related

Username and password store in shared preference

This is the register fiile:
The error is when I stored data and after that, I log in when I click on the login button app got crushed.
this is the register section;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText textview1;
EditText textview2;
Button button1;
Button buttonlog;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = (EditText)findViewById(R.id.ediuser);
textview2 = (EditText)findViewById(R.id.edipassword);
button1 = (Button)findViewById(R.id.btnreg);
buttonlog = (Button)findViewById(R.id.onlogin);
}
public void onreg(View view){
String username = textview1.getText().toString();
String Password = textview2.getText().toString();
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sharedPreferences.edit();
editor1.putString("username",username);
editor1.putString("password",Password);
editor1.apply();
Toast.makeText(this, "Register Successfully", Toast.LENGTH_SHORT).show();
}
public void onlog(View view){
Intent intent = new Intent(this,login.class);
startActivity(intent);
}
}
this is the login file:
package com.example.newshrd;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends AppCompatActivity {
EditText editText1;
EditText editText2;
Button button2;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText1 = (EditText) findViewById(R.id.userlog);
editText2 = (EditText) findViewById(R.id.passwordlog);
button2 = (Button) findViewById(R.id.btnlog);
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
}
//this is the login section find error and let me know please
public void onloghere(View view){
String userlog = editText1.getText().toString();
String passlog = editText2.getText().toString();
String userlogin= sharedPreferences.getString("username",null);
String userpaswwords=sharedPreferences.getString("passowrd",null);
if (userlog.contains(userlogin) && passlog.contains(userpaswwords)){
Toast.makeText(this, "Your are in", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "You are not", Toast.LENGTH_SHORT).show();
}
}
}
please, someone, find the error and let me know what I am missing in this code.
It is properly formatted (at least by the preview it is), so how can I fix this? I'm new to Stack Overflow formatting.
When you save, key is "password":
editor1.putString("password",Password);
But when get, you have a typo for the key here "passowrd":
String userpaswwords=sharedPreferences.getString("passowrd",null);
The userpaswwords you get is null (you set SharedPreferences.getString(String key, #Nullable String defValue) defValue value to be null), and here crashes:
passlog.contains(userpaswwords)
Cuz String.contains(CharSequence s) needs the argument to be non-null.

Else part running even if condition is true in android

I would like to implement a system where when they sign up they provide their username,phone number and a password along with some other data and it all gets saved to the database. So that the user can then signin with their username/phone and password
I am checking if username and password entered is equal to the username and password in the firebase database but it runs the else part even the if part is true, help me to sort out the issue tried with finish() and break statement too.
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
ImageView logo;
public EditText loginPhone, logInpasswd;
//Button btnLogIn;
TextView signup,phonetext,btnLogIn;
DatabaseReference dbview;
SessionManager sessionManager;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
//SessionManager session = new SessionManager(MainActivity.this);
dbview=FirebaseDatabase.getInstance().getReference("Users");
logo = (ImageView) findViewById(R.id.imageView);
logo.animate().rotation(360).start();
loginPhone = findViewById(R.id.loginPhone);
logInpasswd = findViewById(R.id.loginpaswd);
btnLogIn = findViewById(R.id.btnLogIn);
signup = findViewById(R.id.SignIn);
logo.setImageResource(R.drawable.mgenomics);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this, register.class);
startActivity(in);
}
});
btnLogIn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
verifyUser();
}
});
}
public void verifyUser(){
sessionManager = new SessionManager(MainActivity.this);
dbview.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot data:snapshot.getChildren()) {
User user = data.getValue(User.class);
String Phone = loginPhone.getText().toString().trim();
String Passwd = logInpasswd.getText().toString().trim();
String uphone = user.getuPhone();
String upass = user.getuPass();
String uname = user.getuUname();
String uid = user.getuID();
//Bundle data_pass = new Bundle();
// data_pass.putString("name",uname);
if(uname!=null && (uname.equals(Phone) || uphone.equals(Phone)) && upass.equals(Passwd)){
Intent i = new Intent(MainActivity.this,logged_user.class);
sessionManager.saveSession(uname);
sessionManager.loginUser(uname,true);
startActivity(i);
finish();
break;
}
else
{
logInpasswd.setError("Invalid Username/Password");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.i(TAG, "onCancelled: Error: " + error.getMessage());
}
});
}
}
In if statement if(uname!=null && (uname.equals(Phone) || uphone.equals(Phone)) && upass.equals(Passwd)) this will only works if only username not equal to null it means if you enter uphone number as you described username could be username/phone number this wont work. If we use && operator if the first condition fails it won't check for the rest of the conditions simple it will goto else condition. Please check your values for username.
Rewritten if statement based on your explanation:
if(((uname!=null && uname.equals(Phone)) || ( uphone !=null|| uphone.equals(Phone))) && upass.equals(Passwd))

Android Studio keeps giving me nullpointerexception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Hi i am doing a project that is due wednesday and i have spent over 13 hours trying to get Android studio working again, first their was a problem with the gradle and now i keep getting a nullpointerexception even though it same code that was working before. here is the code, please help? because i am stuck and could be doing my project rather that trying to solve android studios problems. by the way there are no errors within the code it says but here is the code.
package ie.wit.fitnessmadeeasy;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogActivity extends AppCompatActivity {
DataBaseHelper helper = new DataBaseHelper(this);
EditText uname = (EditText) findViewById(R.id.et_username);
String unstr = uname.getText().toString();
EditText pass = (EditText) findViewById(R.id.et_password);
String passstr = pass.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
TextView registerLink = (TextView) findViewById(R.id.regHere); //register link creates a link between the two pages
registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LogActivity.this, RegisterActivity.class);
LogActivity.this.startActivity(registerIntent); //what this does it creates an intent that opens the registeravtivity then it tells the current activity to perform the intent and open the register page
}
});
}
// Button login = (Button) findViewById(R.id.login);
public void onLogClick(View view) {
if (view.getId() == R.id.login) {
String Password = helper.searchPassstr(unstr);
Log.v("pass", passstr);
Log.v("pass", Password);
if (passstr.equals(Password)) {
Intent i = new Intent(LogActivity.this, UserAreaActivity.class);
i.putExtra("username", unstr);
startActivity(i);
} else {
Toast temp = Toast.makeText(LogActivity.this, "Username and Password don't Match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
}
package ie.wit.fitnessmadeeasy;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
//import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity {
DataBaseHelper helper = new DataBaseHelper(this);
final EditText name = (EditText) findViewById(R.id.et_name);
final EditText username = (EditText) findViewById(R.id.et_username);
final EditText password1 = (EditText) findViewById(R.id.et_password);
final EditText password2 = (EditText) findViewById(R.id.et_password);
String namestr = name.getText().toString();
String usernamestr = username.getText().toString();
String password1str = password1.getText().toString();
String password2str = password2.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// final EditText password2 = (EditText) findViewById(R.id.et_password);
name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(name.getText().length()==0){
name.setError("Fill Out");
}
else if(username.getText().length()==0){
username.setError("Fill Out");
}
}
});
}
public void onRegClick(View v)
{
if(v.getId() == R.id.confirm)
{
// EditText age = (EditText) findViewById(R.id.et_age); //age is a final variable and is only assigned to activity_register as a view
// EditText name = (EditText) findViewById(R.id.et_name);
// EditText username = (EditText) findViewById(R.id.et_username);
// EditText password1 = (EditText) findViewById(R.id.et_password);
// EditText password2 = (EditText) findViewById(R.id.et_password2);
if(namestr.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Name!", Toast.LENGTH_SHORT);
pass.show();
}
if(usernamestr.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Username!", Toast.LENGTH_SHORT);
pass.show();
}
if(password1str.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Password!", Toast.LENGTH_SHORT);
pass.show();
}
if(!password1str.equals(password2str))
{
//popup message
Toast pass = Toast.makeText(RegisterActivity.this, "Passwords don't match!", Toast.LENGTH_SHORT);
pass.show();
}
else{
// String namestr = name.getText().toString();
//insert details
RegRequest reg = new RegRequest();
reg.setEt_name(namestr);
reg.setEt_username(usernamestr);
reg.setEt_password(password1str);
// r.setEt_age(agestr);
Toast success = Toast.makeText(RegisterActivity.this, "Success", Toast.LENGTH_SHORT);
success.show();
Intent i = new Intent(RegisterActivity.this, LogActivity.class);
startActivity(i);
helper.insertUser(reg);
}
}
}
}
package ie.wit.fitnessmadeeasy;
public class RegRequest{
String et_name , et_username, et_password;
// int et_age;
public void setEt_name(String et_name)
{
this.et_name = et_name;
}
public String getEt_name()
{
return this.et_name;
}
public void setEt_username(String et_username)
{
this.et_username = et_username;
}
public String getEt_username()
{
return this.et_username;
}
public void setEt_password(String et_password)
{
this.et_password = et_password;
}
public String getEt_password()
{
return this.et_password;
}
}
at ie.wit.fitnessmadeeasy.LogActivity.<init>(LogActivity.java:17)
LogActivity.java
Only declare the fields like the following:
EditText uname, pass;
String unstr, passstr;
Initialize in onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
uname = (EditText) findViewById(R.id.et_username);
unstr = uname.getText().toString();
pass = (EditText) findViewById(R.id.et_password);
passstr = pass.getText().toString();
}
And RegisterActivity.java
DataBaseHelper helper ;
EditText name, username,password1,password2;
String namestr,usernamestr,password1str,password2str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
helper = new DataBaseHelper(this);
name = (EditText) findViewById(R.id.et_name);
username = (EditText) findViewById(R.id.et_username);
password1 = (EditText) findViewById(R.id.et_password);
password2 = (EditText) findViewById(R.id.et_password);
namestr = name.getText().toString();
usernamestr = username.getText().toString();
password1str = password1.getText().toString();
password2str = password2.getText().toString();
}

Unable to Parse Json (Android login/register)

i need some help concerning a project in Android , its main goal is to connect with a database (register/login) .
The login works just fine but the register shows an error which is i think is an exception , the error is:
Unable to Parse Json
the information passed to the database successfully but there is no feedback (response).
I use 'ion' and PHP to connect/insert/check the database.
i am using WAMP on Windows.
The code is below :
package tn.contacthelpsoft.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
public class Main2Activity extends AppCompatActivity {
EditText fname,lname,cin,email,pass;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
fname= (EditText) findViewById(R.id.editText3);
lname= (EditText) findViewById(R.id.editText4);
cin= (EditText) findViewById(R.id.editText5);
email= (EditText) findViewById(R.id.editText6);
pass= (EditText) findViewById(R.id.editText7);
btn= (Button) findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("erreur","ee");
Ion.with(Main2Activity.this)
.load("POST","http://10.0.3.2/site/register.php")
.setBodyParameter("nom",fname.getText().toString())
.setBodyParameter("prenom",lname.getText().toString())
.setBodyParameter("cin",cin.getText().toString())
.setBodyParameter("email",email.getText().toString())
.setBodyParameter("pass",pass.getText().toString())
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Log.e("erreur","before");
if(e==null){
Log.e("erreur","after");
if(result!=null) {
String res = result.get("success").toString().substring(1, result.get("success").toString().length() - 1);
Log.e("erreur","after++");
if (res.equals("inscrit")) {
Toast.makeText(Main2Activity.this, " inscrit", Toast.LENGTH_SHORT).show();
Intent in = new Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
} else
Toast.makeText(Main2Activity.this, "echec", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(Main2Activity.this, "connection ?????"+e.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(Main2Activity.this, ""+result, Toast.LENGTH_SHORT).show();}
}
});
}
});
}
}

my login button does nothing

I can't find where my code going wrong. The application is running; it's not throwing exceptions or crashing. I must be missing something though because it doesn't give me an error message when I leave a field blank, and it doesn't log me in when I put in proper login credentials. I'm sure I'm missing something obvious, but thank you in advance for looking it over.
package me.paxana.alerta;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class LoginActivity extends AppCompatActivity {
#Bind(R.id.usernameField) EditText mUsername;
#Bind(R.id.passwordField) EditText mPassword;
#Bind(R.id.loginButton) Button mLoginButton;
#Bind(R.id.signupButton) TextView mSignupButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
mSignupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
username = username.trim();
password = password.trim();
if (username.isEmpty() || password.isEmpty()) { //if they leave a field blank give them an error
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(R.string.Login_Error_Message)
.setTitle(R.string.Login_Error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();}
else { //if every field is accounted for, log in.
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (e == null) { //if no errors return
Intent intent = new Intent(LoginActivity.this, MainActivity.class); // then we logged in, start the app!
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);} // success }
else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this); //something went wrong logging in
builder.setMessage(e.getMessage()) // get a meaningful error message from parse
.setTitle(R.string.Login_Error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
});
}
}
Try moving the code that sets the click listener on your mLoginButton outside the OnClickListener of your mSignupButton.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
mSignupButton.setOnClickListener(new View.OnClickListener(){...});
mLoginButton.setOnClickListener(new View.OnClickListener(){...});
...
}

Categories