Following are the .java files I had written to login to the app using mysql. I had found help on http://easyway2in.blogspot.in/2015/07/android-mysql-database-connect.html
MainActivity.java
package com.example.soumya.attendance;
import android.app.Activity;
import android.content.Intent;
import android.os.StrictMode;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity{
EditText ET_NAME,ET_PASS;
String login_name,login_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ET_NAME = (EditText)findViewById(R.id.editText1);
ET_PASS = (EditText)findViewById(R.id.editText2);
}
public void userLogin(View view)
{
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,login_name,login_pass);
}
#Override
public void onBackPressed() {
return;
}
}
BackgroundActivity.java
package com.example.soumya.attendance;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2/webapp/register.php";
String login_url = "http://10.0.2.2/login.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
}
Now, I want to add an intent code so that if the user logs in successfully, he/she will be taken to the other activity. But, if I try to place it in MainActivity.java, it does not check for successful login or not. Please help me with it. Many others also have the same question on the source. Here, my login.php returns a result to notify whether the login is successful or not through echo.
Its Simple,
Just place on the Intent code on Post Execute when the login Success
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
//Place the Intent Code Here.
Intent intent = new Intent("android.intent.category.LAUNCHER");
intent.setClassName("com.your.package","com.your.package.MainActivity");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
Happy Coding :)
Related
Here below is the class which sends users details to php file and after successfull login the echo statements are shown in AlertDialog box. So this works very well...
BackgroundActivity.java
package com.example.weblogin;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.0.2/androidapp/register.php";
String login_url = "http://10.0.0.2/androidapp/login.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
}
But now I want to forward the user to the next activity or home activity after a successful login or once user is authenticated...
Below is the Login Activity(MainActivity) code...
MainActivity.java
package com.example.weblogin;
import android.app.Activity;
import android.content.Intent;
import android.os.StrictMode;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity{
EditText ET_NAME,ET_PASS;
String login_name,login_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ET_NAME = (EditText)findViewById(R.id.edittext_username);
ET_PASS = (EditText)findViewById(R.id.edittext_password);
}
public void userReg(View view)
{
startActivity(new Intent(this,Register.class));
}
public void userLogin(View view)
{
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,login_name,login_pass);
}
}
and this is my php file which returns some statements which are then shown in AlertDialog...
Login.php
<?php
require "../dbconnect.php";
$user_name = $_POST["login_name"];
$user_pass = $_POST["login_pass"];
$sql_query = "select Firstname,Lastname from users where emailid like '$user_name' and password like '$user_pass';";
$result = mysqli_query($db_conx,$sql_query);
if(mysqli_num_rows($result) >0 )
{
$row = mysqli_fetch_assoc($result);
$name =$row["Firstname"]." ".$row["Lastname"];
echo "Login Success..Welcome ".$name;
}
else
{
echo "Login Failed.......Try Again..";
}
?>
So what can I do to get the result in MainActivity.java or what else can I do to check the response and forward the user to next activity?
Call your desired Activity from onPostExecute!
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, MyActivity.class);
ctx.startActivity(intent);
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
Check the result and do the following to go to next intent
Which is the Activity you want to open
Replace the DisplayMessageActivity.class with required one.
String result = fetchedResult;
String successMessage = "Login Success..Welcome \".$name";
if (result.equals(successMessage)) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
startActivity(intent);
finish(); //To remove the login screen from backstack
}
My problems :
1. I want to make login more secure with if else statement
2. But, I have some problem that, whoever fill the form can access the Welcome page.
3. I have to add on what coding to make sure that the user that have register on my database only can access my Welcome page.
4. Help me, I already find a lot of answer of this problem but all of them cannot function.
Below is my .java file : Login.java
package com.example.lab3;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity
{
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = findViewById(R.id.etUsername);
password = findViewById(R.id.etPassword);
}
public void OnLog(View view)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Login Status");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
String Username = username.getText().toString();
String Password = password.getText().toString();
String type = "login";
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Background bg = new Background(Login.this);
bg.execute(type, Username, Password);
if(Username.equals("") || Password.equals("")) //for user doesnt fill the form
{
Toast.makeText(getApplicationContext(), "Username and Password are required!", Toast.LENGTH_LONG).show();
}
else if (bg.login(Username, Password)) //I have some error at login
{
startActivity(new Intent(getApplicationContext(), Welcome.class));
}
else {
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(), Welcome.class)); //can access Welcome.class while the user's account is not available on phpAdmin database.
}
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
dialog.show();
}
public void OnReg(View view) {
startActivity(new Intent(getApplicationContext(), Register.class));
}
}
My connection database : Background.java
package com.example.lab3;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class Background extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
Background(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String type = params[0];
String login_url = "http://172.20.10.4/LoginLab3.php";
String reg_url = "http://172.20.10.4/RegisterLab3.php";
if (type.equals("login")) {
try {
String username = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if(type.equals("register"))
{
try {
String name = params[1];
String surname = params[2];
String age = params[3];
String username = params[4];
String password = params[5];
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
+URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
+URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute()
{
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result)
{
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
New to android development and found this code below which connects to a mysql database, but seems to fall at runtime after login or register.
package applications.loginandregister;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.Buffer;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by Mitch on 2016-06-04.
*/
public class BackgroundTask extends AsyncTask<String,Void,String>
{
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
BackgroundTask(Context ctx){
this.context = ctx;
}
#Override
protected String doInBackground(String... params) {
preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.putString("flag","0");
editor.commit();
String urlRegistration = "http://domain.com/LoginAndRegister-register.php";
String urlLogin = "http://domain.com/LoginAndRegister-login.php";
String task = params[0];
if(task.equals("register")){
String regName = params[1];
String regEmail = params[2];
String regPassword = params[3];
try {
URL url = new URL(urlRegistration);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myData = URLEncoder.encode("identifier_name","UTF-8")+"="+URLEncoder.encode(regName,"UTF-8")+"&"
+URLEncoder.encode("identifier_email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&"
+URLEncoder.encode("identifier_password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8");
bufferedWriter.write(myData);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
inputStream.close();
editor.putString("flag","register");
editor.commit();
return "Successfully Registered " + regName;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(task.equals("login")){
String loginEmail = params[1];
String loginPassword = params[2];
try {
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the email and password to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myData = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginEmail,"UTF-8")+"&"
+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginPassword,"UTF-8");
bufferedWriter.write(myData);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null){
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println(dataResponse);
editor.putString("flag","login");
editor.commit();
return dataResponse;
} catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
//This method willbe called when doInBackground completes... and it will return the completion string which
//will display this toast.
#Override
protected void onPostExecute(String s) {
String flag = preferences.getString("flag","0");
if(flag.equals("register")) {
Toast.makeText(context,s,Toast.LENGTH_LONG).show();
}
if(flag.equals("login")){
String test = "false";
String name = "";
String email = "";
String[] serverResponse = s.split("[,]");
test = serverResponse[0];
name = serverResponse[1];
email = serverResponse[2];
if(test.equals("true")){
editor.putString("name",name);
editor.commit();
editor.putString("email",email);
editor.commit();
Intent intent = new Intent(context,LogginIn.class);
context.startActivity(intent);
}else{
display("Login Failed...", "That email and password do not match our records :(.");
}
}else{
display("Login Failed...","Something weird happened :(.");
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
public void display(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
This is what I caught in the logcat
applications.loginandregister E/AndroidRuntime: FATAL EXCEPTION: main
Process: applications.loginandregister, PID: 11263
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
at applications.loginandregister.BackgroundTask.onPostExecute(BackgroundTask.java:164)
at applications.loginandregister.BackgroundTask.onPostExecute(BackgroundTask.java:32)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I want to implement a remember me functionality in my android code but I'm not sure where to start because my code is type of complex. I'm not sure where to put things so please help me
I want to make phone no and password remember only when login is true so please help me. This is my codes and please tell me where to put your suggestions in my code it will be better if you edit it thank you
this is login code:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import static example.R.layout.login;
public class login extends Activity {
TextView signup_text;
Button login_button;
EditText PHONE_NO, PASSWORD;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
signup_text = (TextView) findViewById(R.id.sign_up);
signup_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(login.this, register.class));
}
});
PHONE_NO = (EditText) findViewById(R.id.phone_no);
PASSWORD = (EditText) findViewById(R.id.password);
login_button = (Button) findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phone_no = PHONE_NO.getText().toString();
String password = PASSWORD.getText().toString();
if (phone_no.equals("") || password.equals("")) {
builder = new AlertDialog.Builder(login.this);
builder.setTitle("Something went wrong...");
builder.setMessage("Please fill all the fields...");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} else {
BackgroundTask backgroundTask = new BackgroundTask(login.this);
backgroundTask.execute("login", phone_no, password);
}
}
});
}
}
and this is backgroundtask.java:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.CheckBox;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.*;
import android.content.SharedPreferences;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
String register_url = "http://10.0.0.4/loginapp/register.php";
String login_url = "http://10.0.0.4/loginapp/login.php";
Context ctx;
ProgressDialog progressDialog;
Activity activity;
AlertDialog.Builder builder;
public BackgroundTask(Context ctx) {
this.ctx = ctx;
activity = (Activity) ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
builder = new AlertDialog.Builder(activity);
progressDialog = new ProgressDialog(ctx);
progressDialog.setTitle("Please Wait");
progressDialog.setMessage("Connecting to server .... ");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("register")) {
try {
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String owner_name = params[1];
String shop_name = params[2];
String phone_no = params[3];
String shop_address = params[4];
String opening_time = params[5];
String closing_time = params[6];
String password = params[7];
String data = URLEncoder.encode("owner_name", "UTF-8") + "=" + URLEncoder.encode(owner_name, "UTF-8") + "&" +
URLEncoder.encode("shop_name", "UTF-8") + "=" + URLEncoder.encode(shop_name, "UTF-8") + "&" +
URLEncoder.encode("phone_no", "UTF-8") + "=" + URLEncoder.encode(phone_no, "UTF-8") + "&" +
URLEncoder.encode("shop_address", "UTF-8") + "=" + URLEncoder.encode(shop_address, "UTF-8") + "&" +
URLEncoder.encode("opening_time", "UTF-8") + "=" + URLEncoder.encode(opening_time, "UTF-8") + "&" +
URLEncoder.encode("closing_time", "UTF-8") + "=" + URLEncoder.encode(closing_time, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (method.equals("login")) {
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String phone_no, password;
phone_no = params[1];
password = params[2];
String data = URLEncoder.encode("phone_no", "UTF-8") + "=" + URLEncoder.encode(phone_no, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonarry = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonarry.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true")) {
showDialog("Registration Success", code, message);
} else if (code.equals("reg_false")) {
showDialog("Registration Failed", code, message);
} else if (code.equals("login_true")) {
Intent intent = new Intent(activity, HomeActivity.class);
intent.putExtra("message", message);
activity.startActivity(intent);
} else if (code.equals("login_false")) {
showDialog("Login Error", code, message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void showDialog(String title, String code, String message) {
builder.setTitle(title);
if (code.equals("reg_true") || code.equals("reg_false")) {
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.finish();
}
});
} else if (code.equals("login_false")) {
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText phone_no, password;
phone_no = (EditText) activity.findViewById(R.id.phone_no);
password = (EditText) activity.findViewById(R.id.password);
phone_no.setText("");
password.setText("");
dialog.dismiss();
}
});
}
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
please help Thank you
After clicking on login/SignIn, just check if remember me CheckBox is checked or not, if it is checked store userName/Email and password in SharedPreferences.
In your onCreate() of LoginActivity, check whether you have any userName/Email or password stored in SharedPreferences, if it is there fill your EditText with those UserName/Email and Password.
public class Log_in extends AppCompatActivity {
public static String PREFS_NAME="NAME";
public static String PREF_USERNAME="";
public static String PREF_PASSWORD="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
EditText txtuser=(EditText)findViewById(R.id.txt_user);
EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
CheckBox ch=(CheckBox)findViewById(R.id.ch_rememberme);
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
if (username != null || password != null) {
txtuser.setText(username);
txtpwd.setText(password);
ch.setChecked(true);
}
else {
ch.setChecked(false);
}
}
public void doLogin(View view){
EditText txtuser=(EditText)findViewById(R.id.txt_user);
EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
String username = txtuser.getText().toString();
String password = txtpwd.getText().toString();
CheckBox ch=(CheckBox)findViewById(R.id.ch_rememberme);
String type = "login";
if(ch.isChecked()){
rememberMe(username,password);
}
else{
clear();
}
BackgroundTask bt = new BackgroundTask(this);
bt.execute(type, username, password);
}
public void rememberMe(String user, String password){
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME,user)
.putString(PREF_PASSWORD,password)
.commit();
}
public void clear(){
SharedPreferences sharedPrefs =getSharedPreferences(Log_in.PREFS_NAME,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.clear();
editor.commit();
}
}
How to go next page? After check user, Password is right.
I write this code
startActivity(new Intent(this, getMenu.class));
on
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
it not check user&password. But always go to next.
I know is really stupid question. But I really don't know.
Please tell me. :'(
(sorry for my bad English.)
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText UsernameEt ,PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText)findViewById(R.id.etUserName);
PasswordEt = (EditText)findViewById(R.id.etPassword);
}
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
public void OpenReg(View view){
startActivity(new Intent(this,Register.class));
}
public void getJSONClick(View view){
startActivity(new Intent(this, getDatabase.class));
}
}
Backgroundwrok.java
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by puen on 4/6/2016.
*/
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.10.125/login.php";
String register_url = "http://192.168.10.125/register.php";
if(type.equals("login")){
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while ((line = bufferedReader.readLine())!= null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else if (type.equals("register")){
try {
String name = params[1];
String surname = params[2];
String age = params[3];
String username = params[4];
String password = params[5];
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
+URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
+URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while ((line = bufferedReader.readLine())!= null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
getData.java
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class getDatabase extends AppCompatActivity {
String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_database);
}
public void getJSON(View view)
{
new BackgroundTask().execute();
}
class BackgroundTask extends AsyncTask<Void,Void,String> {
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://192.168.10.125/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream =httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine())!=null)
{
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.tv3);
textView.setText(result);
}
}
}