Android登录使用PHP,MySQL和Volley
我想在android中使用凌空创建一个登录活动。我已经在localhost phpmyadmin上建立了我的数据库。我已经成功创建了注册活动,但每当我尝试从我刚在数据库中注册的电子邮件和密码登录时,突然我的应用程序崩溃。Android登录使用PHP,MySQL和Volley
,这里是我的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));
}
}
好吧,我想我找到了你的问题。
这里您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);
}
内与原有USERLOGIN方法替换该方法。我看到的问题是,你永远不会正确地设置参数,所以当你尝试呼叫startActivity(intent)
时,它会崩溃,因为它没有任何价值来知道在onReponse()
中创建的目的内部运行哪个类。
更新,如果它仍然崩溃尝试使用此代码
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"));
}
}
我只替换userLogin方法,现在这个时候应用程序没有崩溃。但为什么它不会到ProfileActivity.java – SofL
我发现,如果条件变得虚假。但我不知道它为什么会发生。如果(response.equals(“success”)){Intent intent = new Intent(getApplicationContext(),ProfileActivity.class); intent.putExtra(EMAIL,email); intent.putExtra(PASSWORD,password); startActivity(intent); } else { Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show(); } – SofL
嗯..你可以回应并检查日志猫看看你收到什么消息从PHP?既然你有敬酒,请告诉我你的敬酒信息返回 –
//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);
}
你可以叫你的登录按钮点击听者这种方法替换您的ProfileActivity。 和创建基本的应用程序类
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);
}
}
}
可以ü添加logcat的?我们需要知道它为什么崩溃的原因 –