-1

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?

John
  • 72
  • 6
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Jan 28 '21 at 14:07
  • Please note that the way you have written the login script it is totally useless. Anyone can login even without a user account. – Dharman Jan 28 '21 at 14:08
  • Yes I have written it for testing purpose... and will change that and improve the security... and please don't down vote I already have less reputation and I am beginner... – John Jan 28 '21 at 14:10

2 Answers2

1

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();
    }
}
Am Ben
  • 89
  • 5
  • this solution works but I don't want to comeback again to the same activity when user presses back button... How can I use finish() in this? – John Jan 28 '21 at 16:11
0

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

        }
  • this if() logic is I have already thought but I want to pass/get the result from BackgroundActivity.java to MainActivity.java in order to check with this if condition – John Jan 28 '21 at 14:17
  • How would I get the result in your fetchedResult variable...? – John Jan 28 '21 at 14:19