I'm making an android app using MySQL and PHP for registration, and my MySQL database is not updating. I am getting to the php methods, but am not successfully updating the table. Here is the important snippet of java code:
public void updateGroupName() {
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText groupName = (EditText) dialog.findViewById(R.id.group);
final String name = groupName.getText().toString();
System.out.println("Name of group is: " + name);
updateUser(name);
System.out.println("Trying to update user group");
if (!name.isEmpty()) {
//add to sqlite database
updateUser(name);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
String tag_string_req = "req_update";
//showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Update Response: " + response.toString());
//hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
System.out.println("User group successfully updated in mysql");
// User successfully stored in MySQL
} else {
System.out.println("The use group failed to update");
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Update Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
// hideDialog();
}
}) {
String email = db.getUserDetails().get("email");
#Override
protected Map<String, String> getParams() {
System.out.println("trying to return params");
// Posting params to register url
Map<String, String> params = new HashMap<>();
params.put("tag", "update");
params.put("user_group", name);
params.put("email", email);
return params;
}
};
System.out.println("updating group to mysql database");
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
// System.out.println("here1");
// System.out.println("user group: " + db.getUserDetails().get("user_group"));
dialog.dismiss();
}
});
//System.out.println("here2");
}
Here are the important portions of my PHP code:
else if ($tag == "update") {
$user_group = $_POST['user_group'];
$uid = $_POST['email'];
//update user
$user = $db->updateUser($user_group, $email);
if ($user) {
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["user_group"] = ["user"]["user_group"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo "The update User function was called and a user was returned";
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Updating user group";
echo json_encode($response);
}
public function updateUser($user_group, $email) {
$result = mysql_query("UPDATE users SET user_group = '$user_group' WHERE email = '$email'");
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
You are passing $email to your method updateUser but the email address is stored in $uid.
Please change
$user = $db->updateUser($user_group, $email);
to
$user = $db->updateUser($user_group, $uid);
Related
I used JSON Request to send some parameters now I want to convert my json data by using json_decode but it does not allowing me to do so.
private void makeJsonObjReq() {
Map<Object, Object> postParam = new HashMap<>();
RequestQueue queue = Volley.newRequestQueue(this);
final String URL = "https://www.facilesol.com/api/test.php";
ArrayList<Map> myArray = new ArrayList<>();
Cursor data2 = dbHelper.getAllData();
if (data2.getCount() == 0)
{
Toast.makeText(getContext(), "Your cart is empty",
Toast.LENGTH_SHORT).show();
}
else if (data2.moveToFirst()) {
while (!data2.isAfterLast()) {
Map<String, String> map1 = new HashMap<>();
int pId = data2.getInt(1);
String quantity = data2.getString(3);
String price = data2.getString(4);
String priceID = data2.getString(6);
String toppingID = data2.getString(7);
map1.put("product_id", String.valueOf(pId));
map1.put("price_id", String.valueOf(priceID));
map1.put("topping_id", String.valueOf(toppingID));
map1.put("quantity", quantity);
map1.put("sale_price", String.valueOf(price));
myArray.add(map1);
data2.moveToNext();
}
}
postParam.put("branch_db",branchDb);
postParam.put("line_items", myArray);
Log.d(TAG, myArray.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(CheckOut.this, String.valueOf(response), Toast.LENGTH_SHORT).show();
try {
Log.d(TAG, response.toString());
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//Toast.makeText(CheckOut.this, "Please fill correct information and check your internet connection", Toast.LENGTH_SHORT).show();
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);
}
////////////////////////////////////////////////////////////////////////////
API File
//////////////////////////////////////////////////////////////////////////
<?php
include(DBConn.php);
$DBName = $_GET["branch_db"];
$JsonFile = $_GET["line_items"];
$arr = json_decode($JsonFile, true);
$Query = "SELECT MAX(cartid) As MaxOrderID FROM poscustomershoppingdata".
" WHERE cartid LIKE '".date("Ymd")."%'";
$rstOdr = mysql_db_query($DBName,$Query);
if (mysql_num_rows($rstOdr) > 0)
{
$objOdr = mysql_fetch_object($rstOdr);
if($objOdr->MaxOrderID == NULL)
{
$OrderID = 0;
}
else
{
$OrderID = substr($objOdr->MaxOrderID,9,11);
}
}
$OrderID = $OrderID + 1;
$CartID = date("Ymd")."-".str_pad($OrderID, 4, "0", STR_PAD_LEFT);
//echo $CartID ." ";
$CartDate = date("Y-m-d h:i:s");
$SqlCommand = "SELECT MAX(transid) FROM poscustomershopping";
$Result = mysql_db_query($DBName,$SqlCommand);
$MaxID = mysql_fetch_array($Result);
$TransactionID = $MaxID['0'];
$TransactionID = $TransactionID + 1;
foreach ($arr as $key => $value)
{
$Query = "INSERT INTO poscustomershopping".
" (cartid, transid, productid, priceid, toppingid, cartdate, quantity, saleprice) ".
" VALUES ($CartID, $TransactionID, '".($value["product_id"])."', '".($value["price_id"])."', '".($value["topping_id"])."', NOW(), '".($value["quantity"])."', '".($value["sale_price"])."')";
//echo $Query; die;
mysql_db_query($DBName,$Query);
}
//echo $Data; die;
?>
In Android Debugger everything is fine as shown in imageDebugger Screenshot but when I tried to decode_json file received via parameter I can't be able to insert data in mySQL although there is no error at all. Please brief me where is the issue and how can identify it for solution purposes.
I am Building a Project with PHP, MYSQL, java Volley Library
Problem is that it doesn't work all 3 at the same time getting this error
E/catch ===: org.json.JSONException: No value for SorrySignUpFirst
SorrySignUpFirst,
SorrySignUpFirst,
LoginPasswordWrong
If I comment 2 then run my Emulator its works so how to solve this Problem
PHP CODES
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
require_once("connection.php");
$data_array = array();
$login_email = $_POST['email'];
$login_email = strip_tags($login_email);
$login_email = str_replace(' ', '', $login_email); // remove spaces
$login_password = $_POST['password'];
$login_password = strip_tags($login_password);
$email = str_replace(' ', '', $login_password); // remove spaces
$db_email = mysqli_query($connection, "SELECT * FROM users WHERE email ='$login_email'");
if (mysqli_num_rows($db_email) == 0)
{
$data_array['SorrySignUpFirst'] = "1";
echo json_encode($data_array);
mysqli_close($connection);
}
else
{
$data = mysqli_fetch_array($db_email);
if (password_verify($login_password, $data['password']))
{
$data_array['LoginSuccessfull'] = "1";
$data_array['id'] = $data['id'];
$data_array['email'] = $data['email'];
echo json_encode($data_array);
mysqli_close($connection);
}
else
{
$data_array['LoginPasswordWrong'] = "1";
echo json_encode($data_array);
mysqli_close($connection);
}
}
}
?>
LoginActivity.java codes
final StringRequest LoginstringRequest = new StringRequest(Request.Method.POST, URLS.LOGIN_API, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String SorrySignUpFirst = jsonObject.getString("SorrySignUpFirst");
String LoginSuccessfull = jsonObject.getString("LoginSuccessfull");
String LoginPasswordWrong = jsonObject.getString("LoginPasswordWrong");
if (SorrySignUpFirst.contains("1")) {
Intent goToHomeScreenIntent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(goToHomeScreenIntent);
Toast.makeText(LoginActivity.this, "User Doen't Exist Sign Up", Toast.LENGTH_LONG).show();
}
if (LoginSuccessfull.contains("1")) {
String id = jsonObject.getString("id");
String fname = jsonObject.getString("email");
Intent goToHomeScreenIntent = new Intent(LoginActivity.this, HomeScreenActivity.class);
startActivity(goToHomeScreenIntent);
Toast.makeText(LoginActivity.this, "id = " + id + "email == " + fname, Toast.LENGTH_LONG).show();
}
if (LoginPasswordWrong.contains("1")) {
Toast.makeText(LoginActivity.this, "Password Wrong", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(LoginActivity.this, "if else if Error", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(LoginActivity.this, "catch -- " + e.toString(), Toast.LENGTH_LONG).show();
Log.e("catch === ", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error= 116" + error.toString(), Toast.LENGTH_LONG ).show();
Log.i("Catch error 116 ====", error.toString());
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> loginParams = new HashMap<>();
loginParams.put("email", Email);
loginParams.put("password", Password);
return loginParams;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(LoginstringRequest);
It seems to me that there is no attribute called SorrySignUpFirst on your jsonObject.
Try placing a breakpoint on this line:
String SorrySignUpFirst = jsonObject.getString("SorrySignUpFirst");
Inspect the jsonObject and check to see whether or not SorrySignUpFirst exists on it.
Please, can someone look at my code?I cant' find a mistake.
When I try login in the app a get Toast message "Bad responses from server".I think I make some mistake in php code.Before I add validation everything work.
PHP Login In next step i want add some basic token authorization.
<?php
$con = mysqli_connect("xxxxx", "xxx", "xxx", "xxx");
$username = $_POST["username"];
$password = $_POST["password"];
$result = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
$affected = mysqli_affected_rows($con);
$response = array();
$response["success"] = false;
$response["status"] ="INVAILD";
if ($affected > 0) {
$response["success"] = true;
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$response["id"] = $id;
$response["username"] = $username;
$response["email"] = $email;
$response["password"] = $password;
}
}
else{
$userCheck = mysqli_query($con, "SELECT * FROM `users` WHERE `username` =
'$username'");
$userAffected = mysqli_affected_rows($con);
if($userAffected>0){
$response["status"]="PASSWORD";
}
}echo json_encode($response);
mysqli_close($con);
exit();
?>
Java I created my login application using Volley, php, MYSQL
public class LoginActivity extends AppCompatActivity {
TextInputLayout tlUsername, tlPassword;
Button bLogin;
TextView tvSign;
String username, password;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
setTitle("Login");
initialize();
requestQueue = Volley.newRequestQueue(LoginActivity.this);
tvSign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent regintent = new Intent(LoginActivity.this,
RegisterActivity.class);
startActivity(regintent);
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = tlUsername.getEditText().getText().toString();
password = tlPassword.getEditText().getText().toString();
if (validateUsername(username) && validatePassword(password)) {
//Username and Password Validation
final ProgressDialog progressDialog = new
ProgressDialog(LoginActivity.this);
progressDialog.setTitle("Please Wait");
progressDialog.setMessage("Logging You In");
progressDialog.setCancelable(false);
progressDialog.show();
LoginRequest loginRequest = new LoginRequest(username, password, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onResponse(String response) {
Log.i("Login Response", response);
progressDialog.dismiss();
// json obcejt
try {
JSONObject jsonResponse = new JSONObject(response);
if (jsonResponse.getBoolean("success")) {
Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);
Long userId = jsonResponse.getLong("id");
String username = jsonResponse.getString("username");
User user = new User(userId, username);
// from server to activity
myIntent.putExtra(MainActivity.USER_ID, userId);
myIntent.putExtra(MainActivity.USER, user);
startActivity(myIntent);
Toast.makeText(LoginActivity.this, "Log in",
Toast.LENGTH_SHORT).show();
finish();
} else {
if (jsonResponse.getString("status").equals("invaild"))
Toast.makeText(LoginActivity.this, "User Not Found",
Toast.LENGTH_SHORT).show();
else {
Toast.makeText(LoginActivity.this, "Password dont't match",
Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Bad Response From Server", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
if (error instanceof ServerError)
Toast.makeText(LoginActivity.this, "Server Error", Toast.LENGTH_SHORT).show();
else if (error instanceof TimeoutError)
Toast.makeText(LoginActivity.this, "Connection Timed Out", Toast.LENGTH_SHORT).show();
else if (error instanceof NetworkError)
Toast.makeText(LoginActivity.this, "Bad Network Connection", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(loginRequest);
}
}
});
}
private void initialize() {
tlUsername = (TextInputLayout) findViewById(R.id.tl_etUsername);
tlPassword = (TextInputLayout) findViewById(R.id.tl_etPassword);
tvSign = (TextView) findViewById(R.id.tvSign);
bLogin = (Button) findViewById(R.id.bLogin);
}
private boolean validateUsername(String string) {
if (string.equals("")) {
tlUsername.setError("enter username");
return false;
} else if (string.length() > 10) {
tlUsername.setError("max 10 ");
return false;
} else if (string.length() < 6) {
tlUsername.setError("Min 6 characters");
return false;
}
tlUsername.setErrorEnabled(false);
return true;
}
private boolean validatePassword(String string) {
if (string.equals("")) {
tlPassword.setError("Enter Your Password");
return false;
} else if (string.length() > 10) {
tlPassword.setError("max 10 characters");
return false;
} else if (string.length() < 8) {
tlPassword.setError("minimum 8 characters");
return false;
}
tlPassword.setErrorEnabled(false);
return true;
}
}
you are going wrong there, fetch the data from database like this
correct form will be like this,
$result = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
and here,
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$response["id"] = $id;
$response["username"] = $row['username']; // username is your database table column name
$response["email"] = $row['email']; // same applies for email
$response["password"] = $row['password']; // like that here also
}
and over here
else{
$userCheck = mysqli_query($con, "SELECT * FROM users WHERE username =
'$username'");
make it like this
else{
$userCheck = mysqli_query($con, "SELECT * FROM users WHERE username =
'%".$username."%'");
I highly recommend you to use PDO prepare statements for security reasons.
The registration is OK, but when I try to login I have this exception:
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
Why?
Thanks in advance.
LOGIN.php:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['email']) && isset($_POST['password'])) {
// receiving the post params
$email = $_POST['email'];
$password = $_POST['password'];
// get the user by email and password
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["cognome"] = $user["cognome"];
$response["user"]["email"] = $user["email"];
$response["user"]["email2"] = $user["email2"];
$response["user"]["numero_appartamento"] = $user["numero_appartamento"];
$response["user"]["nome_edificio"] = $user["nome_edificio"];
$response["user"]["zona_metropolitana"] = $user["zona_metropolitana"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!";
echo json_encode($response);
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters email or password is missing!";
echo json_encode($response);
}
?>
LOGINACTIVITY.java:
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String cognome = user.getString("cognome");
String email = user.getString("email");
String email2 = user.getString("email2");
String numero_appartamento = user.getString("numero_appartamento");
String nome_edificio = user.getString("nome_edificio");
String zona_metropolitana = user.getString("zona_metropolitana");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name,cognome, email,email2,numero_appartamento,nome_edificio,zona_metropolitana,uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
// MainActivity.class);
ScrollableTabsActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
System.out.println(params);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
I have exception at these lines:
JSONObject jObj = new JSONObject(response);
And:
AppConfig.URL_LOGIN, new Response.Listener<String>()
I have 3 fragments inside an app and in one of them I display users name from the SQLite database. What happens is when I register a new user and login first time with it, inside the textview where the users name suppose to appear, it displays NULL value, but when I logout and login again with the same user, name appears as it should.
After registering user, all the data is inserted inside a database, I have checked.
Any ideas what can cause this problem? I will add some code on request as I have no idea which part of the code, fragments or java files might cause this..
EDITED
I have added some code to help resolve this issue.
Login function inside the main screen (once app launches):
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(Main.this,
Logged.class);
startActivity(intent);
finish();
} else {
error_msg.setVisibility(View.VISIBLE);
String msg = jObj.getString("error_msg");
error_msg.setText(msg);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
onViewCreated func inside fragment where users name should be diplayed:
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
profileName = (TextView) getActivity().findViewById(R.id.profileName);
// SqLite database handler
db = new SQLiteHandler(getActivity().getApplicationContext());
// session manager
session = new SessionManager(getActivity().getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
// Displaying the user details on the screen
profileName.setText(name);
}
Register function part:
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
Intent intent = new Intent(
Register.this,
Main.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
error_msg.setVisibility(View.VISIBLE);
String msg = jObj.getString("error_msg");
error_msg.setText(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
I managed to sort this problem myself.. The problem was not in java files but in php files sending to java for some reason..
In php function I used:
$stmt->bind_result($id, $unique_id, $name, $email, $encrypted_password, $salt, $created_at, $updated_at);
$user = $stmt->fetch();
But then changed to
$user = $stmt->get_result()->fetch_assoc();
And that fixed the problem..