Login in an Android APP

3

I am having trouble authenticating my user when the user is verified it returns me a successful response, but my application does not change the activity. Here are my codes:

PHP:

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
require_once('dbConnect.php');

$sql = sprintf("select * from usuarios where username='$username' and password='$password'",
mysql_real_escape_string($username),
mysql_real_escape_string($password));
$check = mysqli_fetch_array(mysqli_query($con,$sql));

 if(isset($check)){
 echo "success";
 }else{
 echo "Invalid Username or Password";
 }

 }else{
 echo "error try again";
 }

JAVA:

package ------;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.*;
    import android.widget.*;

    import java.util.HashMap;


    public class Login extends Activity implements View.OnClickListener {
        public static final String USER_NAME = "USER_NAME";

        public static final String PASSWORD = "PASSWORD";

        private static final String LOGIN_URL = "URL";

        private EditText login;
        private EditText senha;
        private Button acessar;
        private Button facebook;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.act_login);

            login = (EditText) findViewById(R.id.login);
            senha = (EditText) findViewById(R.id.senha);
            acessar = (Button) findViewById(R.id.acessar);
            facebook = (Button) findViewById(R.id.facebook);
            acessar.setOnClickListener(this);
            facebook.setOnClickListener(this);
        }
        private void login(){
            String username = login.getText().toString().trim();
            String password = senha.getText().toString().trim();
            userLogin(username,password);
        }

        private void userLogin(final String username, final String password){
            class UserLoginClass extends AsyncTask<String,Void,String> {
                ProgressDialog loading;
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    loading = ProgressDialog.show(Login.this,"Please Wait",null,true,true);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    loading.dismiss();
                    if(s.equalsIgnoreCase("success")){
                        Intent intent = new Intent(Login.this,Home.class);
                        intent.putExtra(USER_NAME,username);
                        startActivity(intent);
                    }else{
                        Toast.makeText(Login.this,s,Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                protected String doInBackground(String... params) {
                    HashMap<String,String> data = new HashMap<>();
                    data.put("username", params[0]);
                    data.put("password", params[1]);

                    RegisterUserClass ruc = new RegisterUserClass();

                    String result = ruc.sendPostRequest(LOGIN_URL,data);

                    return result;
                }
            }
            UserLoginClass ulc = new UserLoginClass();
            ulc.execute(username,password);
        }

        @Override

        public void onClick(View v) {
            if(v == acessar){
                login();
            }

            final String valorLogin = login.getText().toString();
            final String valorSenha = senha.getText().toString();

            if (valorLogin.trim().isEmpty() || valorSenha.trim().isEmpty()) {
                AlertDialog.Builder dialogo = new AlertDialog.Builder(this);
                dialogo.setMessage("Campos Vazios");
                dialogo.setNeutralButton("Ok", null);
                dialogo.show();
            }
            else if(valorLogin.equals("[email protected]") && valorSenha.equals("123")){
                /*AlertDialog.Builder dialogo = new AlertDialog.Builder(this);
                dialogo.setMessage("Campos Vazios");
                dialogo.setNeutralButton("Ok", null);
                dialogo.show();*/

                Intent it = new Intent(this, Home.class);
                startActivity(it);
            }
            else {
                AlertDialog.Builder dialogo = new AlertDialog.Builder(this);
                dialogo.setMessage("Usuario não encontrado, deseja se cadastrar?");
                dialogo.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
                    // C DIGO QUE SER  EXECUTADO SE O USU RIO PRESSIONAR O BOT O N O - O usuario ser  levado para a dela de cadastro
                    public void onClick(DialogInterface dialog, int which) {
                        Intent itt = new Intent(Login.this, Perfil.class);
                        itt.putExtra("VALOR", login.getText().toString());

                        startActivity(itt);
                    }
                });
                dialogo.setNegativeButton("Não", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // C DIGO QUE SER  EXECUTADO SE O USU RIO PRESSIONAR O BOT O N O
                    }
                });
                dialogo.setTitle("Cadastre-se");
                dialogo.show();
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu){
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_login, 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();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }
    
asked by anonymous 03.09.2015 / 16:35

2 answers

1

A little hint: Use JSON as a method of communication between your application and web-service, and use the Volley library to pick up data from a page, if you are using it, make StringRequest , if for JSON, use JsonArrayRequest or JsonObjectRequest .

Here's a sample:

PHP:

if(isset($check)){
    $info = array("status"=>"Success", "statuscode" =>"1");
}else{
    $info = array("status"=>"Invalid Username or Password", "statuscode"=>"2");
}
$json = json_encode($info);
echo $json;

Android:

private void login(String url){
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, listener, errorListener);
    Volley.newRequestQueue(this).add(jsonObjectRequest);
}

Response.ErrorListener errorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.i("MyInfo", "errorListener");
        error.printStackTrace();
        Toast.makeText(MainActivity.this, "Não foi possível se conectar com o servidor", Toast.LENGTH_SHORT).show();
    }
};

Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        if(response.has("statuscode")){
            int statusCode = response.getInt("statuscode");
            if(statusCode == 1){
                //fez login;
            }else if(statusCode == 2){
                //senha incorreta
            }
        }
    }
};
    
29.07.2016 / 21:33
0

EDIT: The problem seems to be in PHP, since on Android it works normally depending on which URL is called. I leave it to the PHP folks to help.

In your onPostExecute() method, try changing this line:

if(s.equalsIgnoreCase("")){

by this:

if(s.equalsIgnoreCase("success")){
    
03.09.2015 / 16:44