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.
Related
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")
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!!
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.
Hi i got this problem retrieving data, im using android volley and json to get data from web server.
heres my php file :
<?php
$con = mysqli_connect("***", "***", "***", "***");
// listing input entries for query
$city = $_POST["city"];
$term = $_POST["term"];
$p_type = $_POST["property_type"];
$min = $_POST["price_min"];
$max = $_POST["price_max"];
$bedrooms = $_POST["bedrooms"];
$bathrooms = $_POST["bathrooms"];
$query = "SELECT * FROM listing WHERE city = ? AND term = ? AND property_type = ? AND bedrooms = ? AND bathrooms = ?
AND price BETWEEN ? AND ?";
$statement = mysqli_prepare($con, $query);
mysqli_bind_param($statement, "sssiiii", $city, $term, $p_type, $bedrooms, $bathrooms, $min, $max);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $p_id, $p_name, $p_type, $term, $city, $address, $lot_area, $floor_area, $price,
$bedrooms, $bathrooms, $host_name, $host_contact_no, $host_details, $date_listed, $user_id);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
$response = array();
$response["hasData"] = false;
if($count > 0){
$response["hasData"] = true;
while(mysqli_stmt_fetch($statement)){
$response["property_name"]= $p_id;
$response["property_type"] = $p_type;
$response["term"] = $term;
$response["city"] = $city;
$response["address"] = $address;
$response["lot_area"] = $lot_area;
$response["floor_area"] = $floor_area;
$response["price"] = $price;
$response["bedroom"] = $bedroom;
$response["bathroom"] = $bathroom;
$response["host_name"] = $host_name;
$response["host_contact_no"] = $host_contact_no;
$response["host_details"] = $host_details;
$response["date_listed"] = $date_listed;
}
}else{
$response["hasData"] = false;
}
echo json_encode($response);
?>
i have a java class name searchListingRequest.java
public class SearchListingRequest extends StringRequest {
private static final String SEARCH_REQUEST_URL = "http://homeseek.netau.net/searchLising.php";
private Map<String, String> params;
public SearchListingRequest(String city, String term, String p_type,
int price_min, int price_max, int bedrooms, int bathrooms, Response.Listener<String> listener){
super(Method.POST, SEARCH_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("city", city);
params.put("term", term);
params.put("property_type", p_type);
params.put("price_min", price_min + "");
params.put("price_max", price_max + "");
params.put("bedrooms", bedrooms + "");
params.put("bathrooms", bathrooms + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
and in my other class ShowResults.java i call the class above to create instance and make a http request:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_results);
//unfocus on edittexts when starting
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//gets data from home fragment
Intent intent = getIntent();
//initialize listview
data_listing = (ListView) findViewById(R.id.lv_data_listing);
retrieveData(showResults, intent, data_listing);
}
public void retrieveData(Activity activity,Intent intent, final ListView lv){
final String inputCity = intent.getStringExtra("city");
final String inputTerm = intent.getStringExtra("term");
final String inputType = intent.getStringExtra("type");
final int inputPMin = Integer.parseInt(intent.getStringExtra("price_min"));
final int inputPMax = Integer.parseInt(intent.getStringExtra("price_max"));
final int inputBedrooms = Integer.parseInt(intent.getStringExtra("bedrooms"));
final int inputBathrooms = Integer.parseInt(intent.getStringExtra("bathrooms"));
test = (TextView) findViewById(R.id.tv_test);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray responseArray = new JSONArray(response);
boolean hasData = jsonResponse.getBoolean("hasData");
// check if has data
if(hasData){
test.setText("have data");
}
else{// no data retrieved
showAlertDialog();
test.setText("no data");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Can't connect to server.", Toast.LENGTH_SHORT).show();
test.setText("error");
}
}
};
SearchListingRequest searchListingRequest =
new SearchListingRequest(inputCity,inputTerm,inputType,inputPMin,inputPMax,inputBedrooms,inputBathrooms,responseListener);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(searchListingRequest);
}
and when i run the application the text displays "error" which means it has a jsonexception.
here's the logcat :
Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
I really have no idea what this means. thanks for helping!
This is because by default volley will not send the POST body in JSON format and I think server is expecting the POST body in JSON. Hence you need to override getBody() method and change the format from application/x-www-form-urlencoded to json.
Please refer the below code :
#Override
public bytes[] getBody() {
new JSONObject(params).toString().getBytes();
}
Also consider overriding getBodyContentType and setting it to JSON.
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¶m2=%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);
}