Я пытаюсь создать логин используя Volley. Кажется, что я смог подключиться к своей базе данных, так как она отображает сообщение «успех» в моем коде PHP, но я не могу пройти страницу входа после ввода правильных учетных данных из базы данных. Я показал ответ php в моем logcat. Мне совершенно неясно, что происходит, потому что я попытался использовать другой пробный URL для подключения к моему API с тем же контентом, и это работает. но когда я использую URL, указанный в моем SessionManagement
классе, он не работает. Может кто-нибудь, пожалуйста, помогите
Login.java
package com.example.merylle.themoneyger.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
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 com.example.merylle.themoneyger.HttpParse;
import com.example.merylle.themoneyger.R;
import com.example.merylle.themoneyger.SessionManagement;
import java.util.HashMap;
import java.util.Map;
public class Login extends Activity {
TextView title;
Typeface marcellus;
EditText emailuser, passworduser;
TextView forgot;
Button login, register;
private boolean loggedIn = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
/*session = new SessionManagement(getApplicationContext());*/
title = (TextView)findViewById(R.id.txtTitle);
marcellus = Typeface.createFromAsset(getAssets(),"marcellus.ttf");
title.setTypeface(marcellus);
emailuser = (EditText)findViewById(R.id.txtEmail);
passworduser = (EditText)findViewById(R.id.txtPassword);
login = (Button)findViewById(R.id.btnLogin);
forgot = (TextView)findViewById(R.id.txtForgotPW);
register = (Button)findViewById(R.id.btnRegister);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*CheckEditTextIsEmpty();*/
login();
}
});
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent registration = new Intent(Login.this, Registration.class);
startActivity(registration);
}
});
forgot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent forgot = new Intent(Login.this, ForgotPassword.class);
startActivity(forgot);
}
});
}
@Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(SessionManagement.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(SessionManagement.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
}
}
private void login(){
//Getting values from edit texts
final String email = emailuser.getText().toString().trim();
final String password = passworduser.getText().toString().trim();
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, SessionManagement.LOGIN_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//If we are getting success from server
if(response.equalsIgnoreCase(SessionManagement.LOGIN_SUCCESS)){
//Creating a shared preference
SharedPreferences sharedPreferences = Login.this.getSharedPreferences(SessionManagement.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(SessionManagement.LOGGEDIN_SHARED_PREF, true);
editor.putString(SessionManagement.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
//Starting profile activity
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(Login.this, "Invalid username/password", Toast.LENGTH_LONG).show();
Log.e("volley", response);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put(SessionManagement.KEY_EMAIL, email);
params.put(SessionManagement.KEY_PASSWORD, password);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
SessionManagement.java
public class SessionManagement {
//URL to our login.php file
public static final String LOGIN_URL = "http://10.0.2.2:63343/TheMoneyger/api/user-login.php";
//Keys for email and password as defined in our $_POST['key'] in login.php
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
//If server response is equal to this that means login is successful
public static final String LOGIN_SUCCESS = "success";
//Keys for Sharedpreferences
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "themoneygerapp";
//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
}
пользователь-login.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['email'];
$password = $_POST['password'];
//Creating sql query
$sql = "SELECT * FROM users WHERE email='$username' AND password='$password'";
//importing dbConnect.php script
require_once('config.php');
//executing query
$result = mysqli_query($database,$sql);
//fetching result
$check = mysqli_fetch_array($result);
//if we got some result
if(isset($check)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($database);
}
?>