1

I'm trying to send token to mySQL database to be stored there. I'm calling the below method in myFirebaseMessagingService class in onNewToken() but nothing happens. The function is working but the token and username are not being stored in the database.

  private void sendRegistrationToServer(String token) {
        JSONObject request = new JSONObject();
        try {
            //Populate the request parameters
            request.put(KEY_USERNAME, "testUser");
            request.put(KEY_TOKEN, token);
            Log.d("test","request: " + request.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsArrayRequest = new JsonObjectRequest
                (Request.Method.POST, submitToken_url, request, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.v("test","This is php response");
                        try {
                            //Check if user got registered successfully
                            if (response.getInt(KEY_STATUS) == 0) {
                                //Set the user session
                               Log.v("test","Token Stored Successfully" + KEY_STATUS);

                            } else if (response.getInt(KEY_STATUS) != 0) {
                                Log.v("test","Token Storing Failed" + KEY_STATUS);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                        //Display error message whenever an error occurs
                        Toast.makeText(getApplicationContext(),
                                error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        // Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
    }

This is also my php file:

<?php
$response = array();
include 'db/db_connect.php'; 
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['token']) ){
    $username = $input['username'];
    $token = $input['token'];
        //Query to register new user
        $insertQuery  = "INSERT INTO firebaseUser(username,token) VALUES (?,?)";
        if($stmt = $con->prepare($insertQuery)){
            $stmt->bind_param("ssss",$username,$token);
            $stmt->execute();
            $response["status"] = 0;
            $response["message"] = "User Token Stored";
            $stmt->close();
        }
}

echo json_encode($response);
?>

I added a log and got this error now org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

My Singleton class:

import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MySingleton {
    private static MySingleton mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

private RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

}

Saeed Joul
  • 234
  • 2
  • 15
  • `$stmt->bind_param("ssss",$username,$token);` This should throw a error message, since you only have 2 parameters, you only need 2 datatype `"ss"` – catcon Jul 11 '19 at 23:10
  • Here the post that show you to enable error report in PHP for better debugging https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display – catcon Jul 11 '19 at 23:13
  • @catcon thank. I don't know how i missed it. I changed it to "ss" but still no token being stored. is my java method correct? am i missing something else? – Saeed Joul Jul 11 '19 at 23:16
  • 1
    Can you post this `MySingleton` class, please? – Jonathas Nascimento Jul 12 '19 at 00:10
  • @JonathasNascimento Updated. Also, I use the similar method in the SignUp function and it works fine. – Saeed Joul Jul 12 '19 at 10:01

1 Answers1

0

Solved. I have updated my php file to the following:

<?php
$response = array();
include 'db/db_connect.php';

//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array

//Check for Mandatory parameters
if(isset($input['username']) && isset($input['token'])){
$username = $input['username'];
$token = $input['token'];


    //Query to register new user
    $insertQuery  = "INSERT INTO firebaseUsers(username, token) VALUES (?,?)";
    if($stmt = $con->prepare($insertQuery)){
        $stmt->bind_param("ss",$username,$token);
        $stmt->execute();
        $response["status"] = 0;
        $response["message"] = "Token Saved";
        $stmt->close();
    }

}
else{
$response["status"] = 1;
}
echo json_encode($response);
?>
Saeed Joul
  • 234
  • 2
  • 15