PHP not return expected result - java

I'm getting a very weird result ! I posting an id from java class where the id will used in php script to retrieve specific data. The value should be 1, but it always display 2
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$id = $_POST['id'];
//Creating sql query
$sql = "SELECT xuenian FROM student WHERE sid='$id'";
//importing dbConnect.php script
require_once('db_config.php');
//executing query
$result = mysqli_query($con,$sql);
$value = mysqli_fetch_object($result);
$value->xuenian;
if($value === "1"){
echo "1";
}else{
echo "2";
}
mysqli_close($con);
}
I have tried ==, the result still same.
Java class
public void loadResults(final String id, final int xuenian) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_CHECKID,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplication(),response+"from php",Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), error + "", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Adding parameters to request
params.put(AppConfig.KEY_USERID, id);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

You're setting $value to an object here:
$value = mysqli_fetch_object($result);
Then this line does nothing:
$value->xuenian;
On the next line, $value is still an object, but you're comparing it to a string, which will always be false:
if($value === "1")
{
echo "1";
}else{
echo "2";
}
You probably want this:
if($value->xuenian === "1")

Related

Android studio isn't communicating to my php script

I have a 2 java scripts that should go to a php file located on http://localhost/phptesting/Register.php. My script's URL links it, but when I send a register request, nothing happens. Nothing even happens in the logs.
here is my registerrequest:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://localhost/phptesting/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL,listener,null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
and here is my register activity script:
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
CreateUser.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
my php script is this;
<?php
$db_host = 'localhost:3306';
$db_user = 'root';
$db_pass = '';
$db_name = 'test';
$con = mysqli_connect($db_host,'user',$db_pass,$db_name);
if($con){
echo "connection successful";
}else{
echo "connection failed";
}
$age = $_POST["isAdmin"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (username,password,isAdmin) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss",$username,$password,$isAdmin);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
All help is appreciated.
I see at least two errors on this code:
private static final String REGISTER_REQUEST_URL = "http://localhost/phptesting/Register.php";
Android doesn't like localhost you can read it here.
Best option is to do an ifconfig and get your ip address and instead of localhost put your ip address like
http://192.168.1.158/phptesting/Register.php
Also your localhost should have a port, right? So make sure you add it just in case in your BASE_URL, so it should look like this
http://192.168.1.158:8080/phptestig/Register.php
Then the call should work.
Then I see another problem with
mysqli_stmt_bind_param($statement, "siss",$username,$password,$isAdmin);
You are passing 4 values to an insert that requires 3.
I recommend you to go step by step, first make sure your api call is registering something (you can use PostMan or ARC to do it) and then go to Android side.

Script executing two times

I am using PHP as my API for a messaging android app, I have created a script which will register the user by inserting data into the database when logging for the first time, I have tried this Link but my primary key is unique and still the script is executing two times and which causes an error
:-
[27-Feb-2018 17:44:12 UTC] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3bc91dab47aeb989' for key 'users_device_id_uindex'' in [My Api Url]/DbFunction.php:44
Which means that there is a duplicate entry in the table.Basically, It stores the value perfectly when executed for the first time but when it executes again it gives the error described above
Script for registration (register.php):-
<?php
require_once ("DbFunction.php");//Importing DbFunction Class
/*Initializing Variables*/
$response = array();
$db = new DbFunction();
$result = $device_id = $phone_number = $user_name = $email = $website =
$profile_picture = $token = $created_at = '';
/* Checking If REQUEST_METHOD is POST*/
if($_SERVER['REQUEST_METHOD'] == 'POST') {
/*Checking is variables are set*/
$device_id = isset($_POST['device_id']) ? $_POST['device_id']:null;
$phone_number = isset($_POST['phone_number']) $_POST['phone_number']:null;
$user_name = isset($_POST['user_name']) ? $_POST['user_name'] : null;
$email = isset($_POST['email']) ? $_POST['email'] : null;
$website = isset($_POST['website']) ? $_POST['website'] : null;
$profile_picture = isset($_POST['profile_picture']) ? $_POST['profile_picture'] : null;
$token = isset($_POST['token']) ? $_POST['token'] : null;
$created_at = isset($_POST['created_at']) ? $_POST['created_at'] : null;
/* Checking For Nulls*/
if (!isNull($device_id) || !isNull($phone_number) || !isNull($user_name) || !isNull($email) || !isNull($profile_picture) || !isNull($token) || !isNull($created_at)) {
/* Calling The createUser functions with required parameters*/
$result = $db->createUser($device_id, $phone_number, $user_name, $email, $website, $profile_picture, $token, $created_at);
$response['error'] = !$result;// Setting the value of error which is inverse of $result(if result == true which means user registered successfully and there is no error so inverse of result which is false and vice versa)
if($result)
{
$response['message'] = "User Registered Successfully";
}
else{
$response['message'] = "Registration Error";
}
}
/* Echoing The Reponse*/
echo json_encode($response);
}
function isNull($variable)
{
return is_null($variable);
}
script for functions (DbFunction.php):-
public function createUser($device_id,$phone_number,$user_name ,$email ,$website ,$profile_dp ,$token ,$created_at )
{
/* Calling the uploadImage funtion to upload the Image To Server which will Return Url Where Image Is Stored*/
$profile_picture = $this->uploadImage($profile_dp, $email);
$stmt = $this->conn->prepare("INSERT INTO users (device_id, phone_number, user_name, email, website, profile_picture, token, created_at) VALUES (:device_id, :phone_number, :user_name, :email, :website, :profile_picture, :token, :created_at)");
$stmt->bindValue(':device_id', $device_id);
$stmt->bindValue(':phone_number', $phone_number);
$stmt->bindValue(':user_name', $user_name);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':website', $website);
$stmt->bindValue(':profile_picture', $profile_picture);
$stmt->bindValue(':token', $token);
$stmt->bindValue(':created_at', $created_at);
return $stmt->execute();
}
And now the Android code from where I am calling the request, I am using volley for that.
UserInfoActivity.java :-
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnNext:
if (isValidInput()) {
sendDataToServer();
dialog.setMessage("Loading....");
dialog.show();
}
}
}
private void sendDataToServer() {
StringRequest strreq = new StringRequest(Request.Method.POST,
Config.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
dialog.dismiss();
Log.d(TAG, Response);
Boolean error = null;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(Response);
error = jsonObject.getBoolean("error");
if(!error)
{
Toast.makeText(UserInfoActivity.this,"User Registered Successfully",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
VolleyLog.e(TAG, e);
e.printStackTrace();
Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}) {
#SuppressLint("HardwareIds")
#Override
public Map<String, String> getParams() {
DateTime dateTime = new DateTime();
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
Map<String, String> params = new HashMap<>();
params.put("phone_number", FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber());
params.put("user_name", etName.getText().toString());
params.put("email", etEmail.getText().toString());
if (!TextUtils.isEmpty(etWebsite.getText().toString())) {
params.put("website", etWebsite.getText().toString());
}
params.put("token", pref.getString("token", null));
params.put("device_id", Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
params.put("created_at", dateTime.toString());
params.put("profile_picture", image_to_server);
return params;
}
};
AppSingleton.getInstance(UserInfoActivity.this).addToRequestQueue(strreq);
}
AppSingleton.java :-
public class AppSingleton {
private static AppSingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mContext;
private AppSingleton(Context context){
// Specify the application context
mContext = context;
// Get the request queue
mRequestQueue = getRequestQueue();
}
public static synchronized AppSingleton getInstance(Context context){
// If Instance is null then initialize new Instance
if(mInstance == null){
mInstance = new AppSingleton(context);
}
// Return MySingleton new Instance
return mInstance;
}
public RequestQueue getRequestQueue(){
// If RequestQueue is null the initialize new RequestQueue
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
// Return RequestQueue
return mRequestQueue;
}
public<T> void addToRequestQueue(Request<T> request){
// Add the specified request to the request queue
getRequestQueue().add(request);
}
}
And after request, I get an error response which is null:-
02-28 14:58:20.690 14606-14606/com.dev.pigeon E/Volley: [1] 3.onErrorResponse: USERINFOACTIVITYTAG
UPDATE
After Watching the Log clearly I saw this:-
02-28 17:21:36.448 21212-21815/com.dev.pigeon D/Volley: [22348] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://[My Api Url]/register.php 0xec86a58c NORMAL 1> [lifetime=8562], [size=1208], [rc=500], [retryCount=1]
02-28 17:21:36.449 21212-21815/com.dev.pigeon E/Volley: [22348] BasicNetwork.performRequest: Unexpected response code 500 for http://[My APi Url]/register.php
02-28 17:21:36.463 21212-21212/com.dev.pigeon E/Volley: [1] 3.onErrorResponse: USERINFOACTIVITYTAG
Above Error Says That Volley Is Retrying The Request, I don't know why?
Please help from where this error is occurring, I am working on this weird behavior of Volley for a long time but didn't get any solution.
P.S. Sorry For My Bad English And Badly Written Code!!

Send a value of variable in android studio to php

I got problem to pass the value inside the variable of Android Studio to the php code. In this case I want to pass the value inside the variable "group_id" in Message.java to the DbOperation.php. That means at the end, the function "getMessages" inside the DbOperation.php can get the value of variable "group_id" and select the particular table inside the MySQL database. I still new to Android Studio and please help me to solve this problem. Tq very much.
For example: the value of variable "group_id" is "ABC123", the "getMessages" function inside DbOperation.php will perform "SELECT a.id, a.message, a.sentat, a.users_id, b.name FROM ABC123_messages a, users b WHERE a.users_id = b.id ORDER BY a.id ASC;"
This code below is the java class of the Message.java
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Config.SHARED_PREF_GROUP, Context.MODE_PRIVATE);
group_id = sharedPreferences.getString(Config.GROUP_SHARED_PREF, "Not Available");
private void fetchMessages() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_FETCH_MESSAGES,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//dialog.dismiss();
try {
JSONObject res = new JSONObject(response);
JSONArray thread = res.getJSONArray("messages");
for (int i = 0; i < thread.length(); i++) {
JSONObject obj = thread.getJSONObject(i);
int userId = obj.getInt("userid");
String message = obj.getString("message");
String name = obj.getString("name");
String sentAt = obj.getString("sentat");
Message messagObject = new Message(userId, message, sentAt, name);
messages.add(messagObject);
}
adapter = new ThreadAdapter(getActivity(), messages, AppController.getInstance().getUserId());
recyclerView.setAdapter(adapter);
scrollToBottom();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("group_id", group_id);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}
This is part of php code in index.php
$app->post('/messages', function () use ($app){
verifyRequiredParams(array('group_id'));
$group_id = $app->request()->post('group_id');
$db = new DbOperation();
$messages = $db->getMessages($group_id);
$response = array();
$response['error']=false;
$response['messages'] = array();
while($row = mysqli_fetch_array($messages)){
$temp = array();
$temp['id']=$row['id'];
$temp['message']=$row['message'];
$temp['userid']=$row['users_id'];
$temp['sentat']=$row['sentat'];
$temp['name']=$row['name'];
array_push($response['messages'],$temp);
}
echoResponse(200,$response);});
function verifyRequiredParams($required_fields){
$error = false;
$error_fields = "";
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoResponse(400, $response);
$app->stop();
}}
This is one of the function inside DbOperation.php
public function getMessages($group_id){
$stmt = $this->conn->prepare("SELECT a.id, a.message, a.sentat, a.users_id, b.name FROM ?_messages a, users b WHERE a.users_id = b.id ORDER BY a.id ASC;");
$stmt->bind_param("s",$group_id);
$stmt->execute();
$result = $stmt->get_result();
return $result;}
In Android code looks fine. But I think you haven't caught the send data in PHP. Using
$_POST["group_id"]

encountered "org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject"

I'm still new at this and I need help. Maybe I have missed something...
Here's my PHP Code
<?php
$con = mysqli_connect("localhost", "root", "", "customer");
$order_name = $_POST["order_name"];
$order_cust = $_POST["order_cust"];
$quantity = $_POST["quantity"];
$statement = mysqli_prepare($con, "INSERT INTO order (order_name, order_cust, quantity) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $order_name, $order_cust, $quantity);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
and then here's my response code..
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class OrderRequest extends StringRequest {
private static final String ORDER_REQUEST_URL = "http://10.0.2.2/customer/Insert.php";
private Map<String, String> params;
public OrderRequest(String order_name, String order_cust, String quantity, Response.Listener<String> listener){
super(Method.POST, ORDER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put ("order_name", order_name);
params.put ("order_cust", order_cust);
params.put ("quantity", quantity);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
lastly this is my button activity code...
bConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String user_id = etUsername.getText().toString();
final String date = etDate.getText().toString();
final String time = etTime.getText().toString();
final String pax = etPax.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success){
AlertDialog.Builder builder = new AlertDialog.Builder(ReservationActivity.this);
builder.setMessage("Success! Your reservation has been added to our Queue!").setNegativeButton("Confirm", null).create().show();
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(ReservationActivity.this);
builder.setMessage("Reservation failed or missing credentials...").setNegativeButton("Retry", null).create().show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ReservationRequest reservationRequest = new ReservationRequest(user_id, date, time, pax, responseListener);
RequestQueue queue = Volley.newRequestQueue(ReservationActivity.this);
queue.add(reservationRequest);
}
});
Here's the LogCat
W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
I need help pleaseee...
THe url you're requesting isn't sending JSON, its sending down html. So you can't parse it as JSON. Either your endpoint is wrong, it doesn't send JSON at all, or it sends HTML on errors. Or you have server bugs.

Trying to display User info from a database in my Android application

I have been working on this for a while. The first thing I have tried is storing the logged in user in a session, and then trying to use that variable later such as the following:
Login.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sessionid = session_id();
require_once('connect.inc.php');
$sql = "SELECT username, password FROM USER WHERE username = ?";
$stmt = $conn->prepare($sql);
$username = $_POST["username"];
$password = $_POST["password"];
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($user, $pass);
while($stmt->fetch()){
$verify = password_verify($password, $pass);
}
if($verify){
$_SESSION["username"] = $username;
echo 'connected';
echo $sessionid;
}else{
echo 'check details';
}
mysqli_close($conn);
}
?>
I am then taking the response of the login in message and splitting it into two variables. The login response and session id. I take the session id and store in shared preferences. I am trying to store the session ID in my java method so I can access the session user. Here is my java code for attempting to get the user:
GetUserData Java method
private void getUserData() {
SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
String sessionId = sharedPreferences.getString(Config.SID, "SessionID");
StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.SERVER_ADDRESS + "GetUserData.php?PHPSESSID=" + sessionId,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
//json string to jsonobject
jsonObject = new JSONObject(response);
//get json sstring created in php and store to JSON Array
result = jsonObject.getJSONArray(Config.json_array);
//get username from json array
getUserInfo(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getUserInfo(JSONArray jsonArray){
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
userInfo.add(json.getString(Config.getUsername));
} catch (JSONException e) {
}
}
}
Here is the php file the java method is attempting to call:
GetUserData.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET'){
$username = $_SESSION['username'];
$sql = "SELECT * FROM USER WHERE username = '$username'";
require_once('connect.inc.php');
$run = mysqli_query($conn, $sql);
$result = array();
while($row = mysqli_fetch_array($run)){
array_push($result, array(
'id' => $row['id'],
'fname' => $row['fname'],
'lname' => $row['lname'],
'username' => $row['username'],
'email' => $row['email'],
));
}
echo json_encode(array('result'=>$result));
mysqli_close($conn);
}
?>
When debugging, the 'result' array is empty, so for some reason,
$sql = "SELECT * FROM USER WHERE username = '$username'";
is not working. I know it has something to do with sessions, but Im not sure where the problem is.
My next attempt is going to try to just store the logged in user in shared preferences, and then call that variable from a php file and run a query to display user info with that variable. How would I do this?
Thank you.
What you will do is to send a request when a user enters username and password to the server as you have done here. Note I modified your code.
String enteredUsername = "username";
String enteredPassword = "xxxxxx";
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s", enteredUsername, enteredPassword);
StringRequest stringRequest = new StringRequest(Request.Method.GET, uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
// parse the response object and store user id and data in sharedpreference.
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Check the user has not been registered, add the user to your database and return the user database unique id plus other data you want.
then save the user id and username to SharedPreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
sharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("Personal Information", set);
edit.commit();
You should first check if a user id is stored in preference to determine if the user is a registered user. if the user is not register show the login form else redirect user to profile activity page.
I already have a login class that makes sure the user is registered. I'm just trying to get the user information from the database as I have stated. Here is the login method as I probably should have provided it:
private void login(){
final String username = txtUsrnm.getText().toString().trim();
final String password = txtPswrd.getText().toString().trim();
//create string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.SERVER_ADDRESS + "Login.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String responseOne = response.substring(0,9);
String responseTwo = response.substring(9);
if(responseOne.equalsIgnoreCase(Config.logInMessage)){
//create shared pref
SharedPreferences sharedPreferences = Login.this.getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
//editor stores values to the shared pref
SharedPreferences.Editor editor = sharedPreferences.edit();
//add values
editor.putBoolean(Config.sharedPrefBool, true);
editor.putString(Config.username, username);
editor.putString(Config.password, password);
editor.putString(Config.SID, responseTwo);
editor.commit();
Intent intent = new Intent(Login.this, Home.class);
startActivity(intent);
}else{
//display error message
Toast.makeText(Login.this, "Wrong Username or Password", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//from android.com: A Map is a data structure consisting of a set of keys and
// values in which each key is mapped to a single value. The class of the objects
// used as keys is declared when the Map is declared, as is the class of the
// corresponding values.
Map<String,String> hashMap = new HashMap<>();
//maps specified string key, username and password, to specified string value
hashMap.put(Config.username, username);
hashMap.put(Config.password, password);
return hashMap;
}
};
//add string request to queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Categories

Resources