简体   繁体   中英

Android Login Using PHP, MySQL and Volley

I am trying to create a login activity in android using volley. I've set up my database on localhost phpmyadmin. I've created register activity successfully but whenever I try to login from the email and password that I just registered in the database suddenly my application crashes.

here is my login.php

 <?php
 if($_SERVER['REQUEST_METHOD']=='POST'){
 $email = $_POST['email'];
 $password = $_POST['password'];

 require_once('connection.php');

 $sql = "select * from person where email='$email' and password='$password'";

 $check = mysqli_fetch_array(mysqli_query($connect,$sql));

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

 }else{
 echo "error try again";
 }
 ?>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mememe.project">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RegisterActivity">
            <intent-filter>
                <action android:name="android.intent.action.RegisterActivity" />
            </intent-filter>
        </activity>
        <activity android:name=".ProfileActivity"></activity>
    </application>
   </manifest>

LoginActivity.java

package com.example.mememe.project;

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 android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    EditText etEmail, etPassword;
    Button login;

    StringRequest request;
    RequestQueue requestQueue;

    public static final String EMAIL = "email";
    public static final String PASSWORD = "password";
    private static final String LOGIN_URL = "http://192.XXX.XX.XX/loginApp/login.php";

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

        requestQueue = Volley.newRequestQueue(this);

        email = (EditText) findViewById(R.id.etEmail);
        password = (EditText) findViewById(R.id.etPassword);

        login = (Button) findViewById(R.id.logIn);

        login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        userLogin(email.getText().toString(), password.getText().toString());
    }

    private void userLogin(final String email, final String password){

        StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equals("success")){
                    Intent intent = new Intent();
                    intent.putExtra(EMAIL, email);
                    intent.putExtra(PASSWORD, password);
                    startActivity(intent);
                }else{
                    Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("email", email);
                map.put("password", password);

                return map;
            }
        };

        requestQueue.add(request);
    }
}

ProfileActivity.java

package com.example.mememe.project;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class ProfileActivity extends AppCompatActivity {

    private TextView textView;

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


        textView = (TextView) findViewById(R.id.textViewUserName);

        Intent intent = getIntent();

        textView.setText("welcome" + intent.getStringExtra(LoginActivity.EMAIL));

    }
}

Okay i think i found your problem.

Here inside your LoginActivity.java

private void userLogin(final String email, final String password){

    StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.trim().equals("success")){
                Intent intent = new Intent(getApplicationContext(), ProfileActivity.class); //your problem occur right here.
                intent.putExtra(EMAIL, email);
                intent.putExtra(PASSWORD, password);
                startActivity(intent);
            }else{
                Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> map = new HashMap<String, String>();
            map.put("email", email);
            map.put("password", password);

            return map;
        }
    };

    requestQueue.add(request);
}

Replace this method with your original userLogin method. The problem that I seen is you never put the parameter properly so which while u try to call startActivity(intent) it will crash because it doesn't have any value to know which class to run inside the intent your create in onReponse() .

Updated if it still crash try replace your ProfileActivity with this code

package com.example.mememe.project;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class ProfileActivity extends AppCompatActivity {

    private TextView textView;

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


        textView = (TextView) findViewById(R.id.textViewUserName);

        Intent intent = getIntent();

        textView.setText("welcome" + intent.getStringExtra("email"));

    }
}
   //get login response
private void getLoginResponse() {

    final ProgressDialog dialog = new ProgressDialog(Login.this);
    dialog.setMessage("Please wait...");
    dialog.show();
    //Get Latitude & Longitude from the Preference
    strLatitude = preferences.getString(check.LATITUDE, "").toString();
    strLongitude = preferences.getString(check.LONGITUDE, "").toString();
    strPassword = md5(strPassword);
    try {
        strLatitude = URLEncoder.encode(strLatitude, "UTF-8");
        strLongitude = URLEncoder.encode(strLongitude, "UTF-8");
        strEmail = URLEncoder.encode(strEmail, "UTF-8");
        strPassword = URLEncoder.encode(strPassword, "UTF-8");
        //strToken = URLEncoder.encode(strToken, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String webUrl;

    webUrl = getString(R.string.web_url) + getString(R.string.method_login) +
            getString(R.string.params_email) + strEmail
            + "&" + getString(R.string.params_password) + strPassword + "&" +
            getString(R.string.params_deviceToken) + strToken
            + "&" + getString(R.string.params_deviceType) + "Android" + "&" +
            getString(R.string.params_latitude) + strLatitude
            + "&" + getString(R.string.params_longtitude) + strLongitude;
    System.out.println(webUrl);

    JsonObjectRequest jsonArrayReq = new JsonObjectRequest(Request.Method.GET,
            webUrl, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d("Login Response", response.toString());
            boolean responseSuccess = false;
            int strSuccess = 0;
            String message = null, strUserId = null, strFullName = null;
            try {
                if (!response.getString("status").equals("")) {
                    strSuccess = response.getInt("status");
                }
                if (!response.getString("message").equals("")) {
                    message = response.getString("message");
                }

                if (strSuccess == 1) {
                    responseSuccess = true;
                    strUserId = response.getString("user_id");
                    strFullName = response.getString("full_name");
                    strEmail = response.getString("email");
                } else {
                    responseSuccess = false;
                }

                dialog.dismiss();
                if (responseSuccess) {
                    // Store UserId into Preferences
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString(check.USERID, strUserId);
                    editor.putString(check.USERON, "on");
                    editor.commit();
                    intent = new Intent(Login.this, HomeTabActivity.class);
                    intent.putExtra("type", "");
                    intent.putExtra("Notifytype", "");
                    intent.putExtra("otherUserId", "");
                    intent.putExtra("otherProfileId", "");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();

                } else {
                    Constant.showAlertDialog(Login.this, message);
                }
            } catch (JSONException e) {
                dialog.dismiss();
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Volley", "Error: " + error.getMessage());
            String message = null;
            dialog.dismiss();
            if (error instanceof NetworkError) {
                message = "Cannot connect to Internet...Please check your connection!";

            } else if (error instanceof ServerError) {
                message = "The server could not be found. Please try again after some time!!";

            } else if (error instanceof AuthFailureError) {
                message = "Cannot connect to Internet...Please check your connection!";
            } else if (error instanceof ParseError) {
                message = "Parsing error! Please try again after some time!!";
            } else if (error instanceof NoConnectionError) {
                message = "Cannot connect to Internet...Please check your connection!";

            } else if (error instanceof TimeoutError) {
                message = "Connection TimeOut! Please check your internet connection.";
            }

            Constant.showAlertDialog(Login.this, message);
        }
    });

    jsonArrayReq.setRetryPolicy(new DefaultRetryPolicy(30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    // Adding request to request queue
    BizEcard.getInstance().addToRequestQueue(jsonArrayReq,
            Constant.tag_json_obj);

}

you can call this method in your login button click listner. and create your base application class

public class Demo extends android.app.Application {
public static final String TAG = Demo.class.getSimpleName();

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private com.nostra13.universalimageloader.core.ImageLoader mLoader;
LruBitmapCache mLruBitmapCache;
private static Demo mInstance;
private static Context mAppContext;
@Override
public void onCreate() {
    if (Constant.Config.DEVELOPER_MODE
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectAll().penaltyDialog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectAll().penaltyDeath().build());
    }
    super.onCreate();
    Pref.init(this);
    mInstance = this;
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .threadPoolSize(3)
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .memoryCacheSize(1500000) // 1.5 Mb
            .denyCacheImageMultipleSizesInMemory()
            .discCacheFileNameGenerator(new Md5FileNameGenerator())
            .enableLogging() // Not necessary in common
            .build();

    // Initialize ImageLoader with configuration.
    mLoader.getInstance().init(config);

    this.setAppContext(getApplicationContext());
}
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}
public static synchronized Demo getInstance() {
    return mInstance;
}

public static Context getAppContext() {
    return mAppContext;
}

public void setAppContext(Context mAppContext) {
    this.mAppContext = mAppContext;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        getLruBitmapCache();
        mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
    }

    return this.mImageLoader;
}

public LruBitmapCache getLruBitmapCache() {
    if (mLruBitmapCache == null)
        mLruBitmapCache = new LruBitmapCache();
    return this.mLruBitmapCache;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}



public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM