make NodeJS function synchronus? sends json response before querying database - java

I am making a login/register android app UI with nodejs as the backend language. Whats happening is that whenever I click the register button, it sends the json response before querying the database (select statement to check if username exists) causing the android app to get the wrong response which causes me to click the button twice to register the correct response. For instance lets say their is a username called test in the database and I try to sign up using the username test, it will tell me that the username is already taken and if erase test and enter lets say 'bob' which does not exist in the database it still says the username is already taken even though it is not but when I click the register button again it will register the user. I am assuming this is happening because it is async(it sends the json response while or before querying the database). How can I make this synchronus or is there another way to fix this?
server file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
//connection
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database : "androidtest"
});
//use json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//declare variables to hold values entered by the user
var name;
var username;
var password;
var age;
//boolean array to let frontend know what is going on
var response;
app.post('/', function(req, res) {
//retrieve variables
username = req.body.username;
name = req.body.name;
age = req.body.age;
password = req.body.password;
//query database
//check if username is taken
var select = "SELECT * FROM users WHERE username = ? LIMIT 1";
con.query(select, [username], function (err, results) {
if (err) throw err;
//if username is taken send json string 'exists' to android app
if(results.length) {
response = {"exists" : "true"};
//if username is available send string 'success' and add the user to the database
} else {
var add = "INSERT INTO users (name, username, age, password) VALUES (?, ?, ?, ?)";
response = {"success" : "true"};
con.query(add, [name, username, age, password]);
if (err) throw err;
console.log('row inserted');
}
});
//send json
res.json(response);
//prevents the functions from being executed more than once
res.end('/');
});
//listen on port 3000
app.listen(3000);
android app java:
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = etName.getText().toString();
final String username = etUserName.getText().toString();
final String password = etPassword.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
//Boolean exists = jsonResponse.getBoolean("exists");
String exists = jsonResponse.getString("exists");
if (exists.matches("true")) {
Toast toast = Toast.makeText(getApplicationContext(), "username already exists", Toast.LENGTH_SHORT);
toast.show();
}
} catch(Exception e) {
e.printStackTrace();
}
try {
JSONObject jsonResponse = new JSONObject(response);
//Boolean success = jsonResponse.getBoolean("success");
String success = jsonResponse.getString("success");
if (success.matches("true")) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}

You have to put
res.json(...);
res.end('/');
after the closing bracker of the following line (after & outside the else block):
console.log('row inserted');
then it first gets executed when to query has finished.

Related

Different types of users logging in to Android App with SQLite Database

Sorry if this is a stupid question but I am new to Android Development. I am trying to create a login screen which will direct doctors to a one activity and nurses to another activity when they login. This does not seem to work. I have put code into the login.java class:
btLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String email = loginemail.getText().toString();
String password = loginpassword.getText().toString();
Boolean Chkemailpass = db.emailpassword(email, password);
if(Chkemailpass == true) {
Cursor typeofuser;
typeofuser = db.checkUser(loginemail.getText().toString()); //get user type from database
if(typeofuser.equals("Nurse")) {
Intent mainintent = new Intent(Login.this, NurseHome.class);
startActivity(mainintent);}
else if (typeofuser.equals("Doctor")){
Intent intent = new Intent(Login.this, DoctorHome.class);
startActivity(intent);}
}
else
Toast.makeText(getApplicationContext(),"Wrong email or password", Toast.LENGTH_SHORT).show();
}
});
}
}
And I also have this code in the databasehelper class relating to the usertype:
public Cursor checkUser(String email) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT TYPEOFUSER from user_table WHERE EMAIL=email", null);
return res;
}
All help would be appreciated, thank you.
The argument email of checkUser() is a string, so in your sql statement it should be enclosed inside single quotes like this:
SELECT TYPEOFUSER from user_table WHERE EMAIL = 'email'
but the correct way to pass parameters to rawQuery() is with the use of ? placeholders and the use of the 2nd argument as an array of string parameters (instead of null).
Also don't return the Cursor, but the type of user as a String from checkUser().
So change to this:
public String checkUser(String email) {
String result = "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(
"SELECT TYPEOFUSER from user_table WHERE EMAIL = ?",
new String[] {email}
);
if (res.moveToNext()) {
result = res.getString(0);
}
res.close();
return result;
}
and instead of:
Cursor typeofuser;
typeofuser = db.checkUser(loginemail.getText().toString());
use this:
String typeofuser = db.checkUser(loginemail.getText().toString());

Nothing Happened when i put right and wrong password

why nothing happened when i put the correct email, but whatevet i put correct or incorrect password the program still not doing anything. It's like the program not checked the password, can you help me ?
This my login.php
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'];
$password = $_POST['password'];
require_once 'connect.php';
$sql = "SELECT * FROM user WHERE email='$email' ";
$response = mysqli_query($conn, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1 ) {
$row = mysqli_fetch_assoc($response);
if ( password_verify($password, $row['password']) ) { // I Think The Problem At This but i still don't know.
echo $password;
$index['name'] = $row['name'];
$index['email'] = $row['email'];
$index['id'] = $row['id'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}
}
}
?>
This my SignInActivity.java // or at this the problem is ?
public class SignInActivity extends AppCompatActivity {
private EditText email,password;
private Button login;
private TextView link_regist;
private static String URL_LOGIN = "https://awalspace.com/app/imbalopunyajangandiganggu/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
email = findViewById(R.id.titEmail);
password = findViewById(R.id.titPassword);
login = findViewById(R.id.btnSignIn);
link_regist = findViewById(R.id.tvToSignUp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if(!mEmail.isEmpty() || !mPassword.isEmpty())
{
login(mEmail,mPassword);
}
else{
email.setError("Silahkan Masukkan Email");
password.setError("Silahkan Masukkan Password");
}
}
});
}
private void login(final String email, final String password) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray =jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email = object.getString("email").trim();
Toast.makeText(SignInActivity.this, "Success Login. \n Your Name : "+name+"\nYour Email : "+email,Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SignInActivity.this, "Error "+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SignInActivity.this, "Error "+error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email",email);
params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Partial answer:
First off
You are open to SQL injection. You should parameterize your query.
Parameterized queries in PHP with MySQL connection
Second
You can add the password to your query so you don't have to do a 2nd check, if you store the passed password in the DB, or you can hash your password first then use it in your query. That avoids getting more user data than necessary (with the associated possible leaking of data) and avoids needing a second method to find the correct user.
This is shown in the link above.
If you store a salt in the DB, I can understand why you need the 2nd method, but you might be able to salt the password in the SQL, via a SQL function. Since you don't include the code for password_verify, we have no way to know what you're actually doing there, so I'm keeping this as basic as I can. (My philosophy is to keep things simple until complications are required.)
Third
Even if you are getting all the columns in that table, specify the column names you need. You might end up adding to that table later, which would cause this query to pull more data than it needs, again.
Fourth
Since you already have the email, which is one of the parameters of the query, you don't need to get it from the DB.
FYI, the link above adds each parameter individually, but mysqli_stmt_bind_param can do them all in one shot.
Object oriented style
mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] ) : bool
Procedural style
mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed &$var1 [, mixed &$... ] ) : bool
...
types
A string that contains one or more characters which specify the types for the corresponding bind variables:
...
https://www.php.net/manual/en/mysqli-stmt.bind-param.php
$stmt = mysqli_prepare($dbc, "SELECT name, id FROM users WHERE email= ? AND password = ?");
mysqli_stmt_bind_param($stmt, "ss", $email, $password); // or use a hash from a method instead of $password
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch($stmt);
This should pull just the one user, unless it doesn't pull any users, so you should have a clear indication of whether this user has access to your site/data/whatever or not. I would suggest sending an actual success message that you can recognize as something a little more specific to you, rather than the generic message you have right now. I understand you're still in testing phase, so it's something to think about later, if you hadn't already.
I would also suggest sending an HTTP 401 message back if $row is null. That way it's 100% guaranteed that your client software understands what happened as well as not giving any specifics as to why it failed. You can still tell the user something more meaningful, such as "Email and Password Combination Not Recognized". Also, don't specify if the email or the password is wrong, since this can lead to easier brute force hacking. There's a lot of contention around this idea of prompts, so I'll let you do your own research and make up your mind about it.
Whether your Java code is correctly sending the login credentials to your PHP server, IDK. I'm rusty on that, so I'll let someone else chime in, and why I'm saying this is a partial answer. At least this answer should get your PHP on the right track.

PHP if-else bodies both executing

I'm a beginner in PHP and i've got this code where both if and else parts are executed in the same "run". I know it's logically impossible but that's what I'm getting.
Here's my PHP Code:
<?php
require_once 'create_request_form.php';
$db = new create_request_form();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['rqTitle']) && isset($_POST['rqMname']) && isset($_POST['rqUname']) && isset($_POST['rqBranch']) && isset($_POST['rqText']) && isset($_POST['rqMinPrice']) && isset($_POST['rqMaxPrice']) && isset($_POST['rqImage']) && isset($_POST['rqCategory']) && isset($_POST['rqDateTime'])) {
// receiving the post params
$rqTitle = $_POST['rqTitle'];
$rqMname = $_POST['rqMname'];
$rqUname = $_POST['rqUname'];
$rqBranch = $_POST['rqBranch'];
$rqText = $_POST['rqText'];
$rqMinPrice = $_POST['rqMinPrice'];
$rqMaxPrice = $_POST['rqMaxPrice'];
$rqImage = $_POST['rqImage'];
$rqCategory = $_POST['rqCategory'];
$rqDateTime = $_POST['rqDateTime'];
// check if there is a request with the same title
if ($db->checkReqTitle($rqTitle)) {
// Request already exists
$response["error"] = TRUE;
$response["error_msg"] = "Request already exists with the title: " . $rqTitle;
echo json_encode($response);
} else {
// create a new request
$request = $db->StoreReqInfo($rqTitle, $rqMname, $rqUname, $rqBranch, $rqText, $rqMinPrice, $rqMaxPrice, $rqImage, $rqCategory, $rqDateTime);
if ($request) {
// request stored successfully
$response["error"] = FALSE;
$response["request"]["rqTitle"] = $request["rqTitle"];
$response["request"]["rqMname"] = $request["rqMname"];
$response["request"]["rqUname"] = $request["rqUname"];
$response["request"]["rqBranch"] = $request["rqBranch"];
$response["request"]["rqText"] = $request["rqText"];
$response["request"]["rqMinPrice"] = $request["rqMinPrice"];
$response["request"]["rqMaxPrice"] = $request["rqMaxPrice"];
$response["request"]["rqImage"] = $request["rqImage"];
$response["request"]["rqCategory"] = $request["rqCategory"];
$response["request"]["rqDateTime"] = $request["rqDateTime"];
echo json_encode($response);
} else {
// request failed to store
$response["error"] = TRUE;
$response["error_msg"] = "An error occurred while creating the request. Please try again.";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>
The required behavior (storing data in the database) is all performed well but the $response I'm getting is the error string i've assigned to when a request title already exists instead of the JSON formatted array of the stored request (Both if and else bodies are executed but i get the result of if body as a response).
A screenshot of the $response using Postman to send the request:
A screenshot from my Samsung Galaxy Note 3:
I'm also using Galaxy Note 4 for testing and it just shows me a blank Toast message and doesn't start the intent(doesn't move to home screen).
So far the only possible explanation is that the script is being executed twice, however I can't find anywhere that called it a second time.
This is the java code responsible for sending a request with required paramters to the php script above.
private void storeRequest(final String rTitle, final String rMname, final String rUname,
final String rBranch, final String rText, final String rMinPrice,
final String rMaxPrice, final String imagePath, final String rCategory) {
// Tag used to cancel the request
String cancel_req_tag = "request";
//A progress dialog message to let the user know they are being registered
progressDialog.setMessage("Please wait while we add your request...");
showDialog();
//creating a StringRequest to send the registration info to the script
// at the server for processing
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REQUEST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Request Response: " + response.toString());
hideDialog();
try { //json objects must be surrounded by try catch statement
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) { // error is set to false, meaning no error
// Launch home activity
Intent intent = new Intent(CreateRequestActivity.this, HomeActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(CreateRequestActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(CreateRequestActivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("rqTitle", rTitle);
params.put("rqText", rText);
params.put("rqMname", rMname);
params.put("rqUname", rUname);
params.put("rqBranch", rBranch);
params.put("rqMinPrice", rMinPrice);
params.put("rqMaxPrice", rMaxPrice);
params.put("rqImage", imagePath);
params.put("rqCategory", rCategory);
params.put("rqDateTime", DateFormat.getDateTimeInstance().format(new Date()));
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
Any ideas?
Thanks in advance!
So turns out the problem stemmed from the Java code and not PHP (poor PHP ;P). More accurately, Volley requests have a problem with request timeouts, especially when sending requests using POST method.
So what worked for me was adding this line right before adding the request to the queue:
strReq.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0));
*Replace strReq with your request name. Basically what this line does is that it prevents volley from sending a duplicate request when the first request takes too long.
The original & more datailed answer:
The DefaultRetryPolicy.class's hasAttemptRemaining() class looks like this:
protected boolean hasAttemptRemaining() {
return this.mCurrentRetryCount <= this.mMaxNumRetries;
}
From what I can see, setting the maxNumRetries to 0 will still make that return true if it hasn't done a retry yet.
I fixed it with a
request.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0);
Source: Android Volley makes 2 requests to the server when retry policy is set to 0

Firebase realtime database not registering data Android

I'm trying to add a table "user" to my Firebase real-time database, code wise everything looks fine but there are no registers showing!
Here's my code sample:
private void CreateUser(){
final TextView firstName = findViewById(R.id.signUpOnSuccess_FirstName), lastName = findViewById(R.id.signUpOnSuccess_LastName);
final EditText bday = findViewById(R.id.SignUpOnSuccess_Bday);
final Spinner gender = findViewById(R.id.signUpOnSuccess_Gender);
final String sFirstName = firstName.getText().toString().trim(),
sLastName = lastName.getText().toString().trim(),
sGender = gender.getSelectedItem().toString();
//Transfer from SignUpActivity.java
String sEmail = SignUpActivity.sEmail,
sPassword = SignUpActivity.sPassword;
if (!TextUtils.isEmpty(sFirstName)) {
if (!TextUtils.isEmpty(sLastName)) {
String id = databaseUsers.push().getKey();
User user = new User(id, sEmail, sPassword, sFirstName, sLastName, sGender);
databaseUsers.child(id).setValue(user);
Toast.makeText(getApplicationContext(), "User Entry Successfull", Toast.LENGTH_SHORT).show();
}else {Toast.makeText(getApplicationContext(), "Enter Last Name!", Toast.LENGTH_SHORT).show();}
} else {Toast.makeText(getApplicationContext(), "Enter First Name Address!", Toast.LENGTH_SHORT).show();}
}
--"--
String id = databaseUsers.push().getKey();
User user = new User(id, sEmail, sPassword, sFirstName, sLastName, sGender);
databaseUsers.child(id).setValue(user);
Here are my Firebase rules:
Here's what's shown on Firebase Database:
Add this at the beginning of the class:
public FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
public DatabaseReference databaseUsers = databaseUsers.getReference("NameofYourTable");
The rest of your code seems fine:
String id = databaseUsers.push().getKey();
User user = new User(id, sEmail, sPassword, sFirstName, sLastName, sGender);
databaseUsers.child(id).setValue(user);
To try to find out if there is a problem with the operation, you can add the CompletionListener, when you add the data into firebase database.
Change this:
databaseUsers.child(id).setValue(user);
For this:
databaseUsers.child(id).setValue(userAux, new DatabaseReference.CompletionListener() {
public void onComplete(DatabaseError error, DatabaseReference ref) {
if(error == null){
callback.OnSuccess("Ok");
}
else{
callback.OnFailure(error.toString());
}
}
});
Is just checking if the operation is going through(OnSuccess) or if is not (OnFailure), and why not:
error.toString()
Try Giving it some node and save it inside it like :
DatabaseReference databaseUsers = getDatabase().getReference("users");
String id = databaseUsers.push().getKey();
User user = new User(id, sEmail, sPassword, sFirstName, sLastName, sGender);
databaseUsers.child(id).setValue(user);

Not able to insert record to MySQL, but showing no error

Task: sync records from android sqlite to mysql.
Problem: mysql/php is not inserting data into my table in mysql. But no errors were shown.
DB_Connect.php:
<?php
class DB_Connect {
// constructor
function __construct(){
}
// destructor
function __destruct(){
}
// connecting to database
public function connect(){
require_once 'config.php'; // defined DB_HOST,DB_USER,DB_PASSWORD here
// connecting to mysql
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
// selecting database
mysqli_select_db($con,"heart");
// return database handler
return $con;
}
// closing database connection
public function close(){
mysqli_close($this->connect());
}
}
?>
DB_Operations.php:
<?php
class DB_Operations {
private $db;
public $last_id;
public $error;
public $error_conn;
public $error_no;
// constructor
function __construct(){
require 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct(){
}
// Storing new doctor
public function storeDoctor($_id,$firstName,$lastName,$specialization,$licenseNumber,$clinicAddress,$email,$contactNum,$username,$password,$aboutMe){
$result = mysqli_query($this->db->connect(),"INSERT INTO doctor(_id,first_name,last_name,specialization,license_number,clinic_address,email,contact_number,username,password,about_me) VALUES('$_id','$firstName','$lastName','$specialization','$licenseNumber','$clinicAddress','$email','$contactNum','$username','$password','$aboutMe')");
if (mysqli_connect_errno()){
$this->error_conn = mysqli_connect_error();
}
if(!$result){
if(mysqli_errno($this->db->connect()) == 1062){
// duplicate key - primary key violation
return true;
} else{
// for other reasons
$this->error = mysqli_error($this->db->connect());
$this->error_no = mysqli_errno($this->db->connect());
return false;
}
} else{
$this->last_id = mysqli_insert_id($this->db->connect());
return true;
}
}
// getters
public function getError(){
return $this->error;
}
public function getError_no(){
return $this->error_no;
}
public function getError_conn(){
return $this->error_conn;
}
...
insertuser.php:
<?php
include 'DB_Operations.php';
// create object for DB_Operations class
$db = new DB_Operations();
// get JSON posted by Android Application
$json = $_POST["doctorsJSON"];
// remove slashes
if(get_magic_quotes_gpc()){
$json = stripslashes($json);
}
// decode JSON into Array
$data = json_decode($json);
// util arrays to create response JSON
$a = array();
$b = array();
// loop through an array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data); $i++){
// store doctor into MySQL DB
$res = $db->storeDoctor($data[$i]->_id,$data[$i]->first_name,$data[$i]->last_name,$data[$i]->specialization,$data[$i]->license_number,$data[$i]->clinic_address,$data[$i]->email,$data[$i]->contact_number,$data[$i]->username,$data[$i]->password,$data[$i]->about_me);
// based on insertion, create JSON response
$b["local_id"] = $data[$i]->_id;
if($res){
$b["server_id"] = $db->last_id;
$b["status"] = 'yes';
}else{
$b["status"] = 'no';
$b["err_no"] = $db->getError_no();
$b["error"] = $db->getError();
$b["error_conn"] = $db->getError_conn();
}
array_push($a,$b);
}
// post JSON response back to Android Application
echo json_encode($a);
?>
I have a function in java which syncs the sqlite data to mysql:
public void syncSQLiteToMySQL(Context context,String selectQuery){
dop = new DatabaseOperations(context);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
ArrayList<HashMap<String,String>> doctorList = new ArrayList<HashMap<String,String>>();
doctorList = dop.getAllDoctors();
if(doctorList.size()!=0){
String json = dop.composeJSONfromSQLite(selectQuery);
params.put("doctorsJSON", json);
Log.i("json to pass", json);
client.post("http://"+ip+":8080/changed_server_name/insertuser.php",params ,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.e("client response",response);
try {
JSONArray arr = new JSONArray(response);
for(int i=0; i<arr.length();i++){
JSONObject obj = (JSONObject)arr.get(i);
// did something with json response here
dop.updateSyncStatus(obj.getString("local_id"),obj.getString("status"));
}
message = "DB Sync completed!";
} catch (JSONException e) {
message = "Error Occured [Server's JSON response might be invalid]!";
Log.e("JSONException",e.getMessage());
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
if(statusCode == 404){
message = "Requested resource not found";
}else if(statusCode == 500){
message = "Something went wrong at server end";
}else{
message = "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]";
Log.e("sync post failure",error.toString());
}
}
});
}
}
So, here's the response:
[{"local_id":"0","status":"no","err_no":0,"error":"","error_conn":null}]
The JSON works fine. No problem with it. I have checked and it passes correct data. Just the PHP and MySQL side. Somehow, I couldn't find the error to this code. There is no error message, error number is 0, and there was no error in connecting to DB. But the query in storeDoctor() returns false. How could this be? I have been reading about this problem on this site and others, but I have not really found something that's close to my problem.
Please enlighten me. Your help would really be appreciated. Thanks in advance.
Edit: I also tried mysqli_ping($this->db->connect()); and it returns true which means the connection is okay. So, what really is this something that makes the query fail?
Did you try using error_reporting(E_ALL);
Also inside the constructor you used
$this->db->connect();
And then in the store you used
$result = mysqli_query($this->db->connect(),
Can you post the code for connect

Categories