0

So I have this customer, and I want to update the fcm_token value in the customer object via post request using volley, but It's not working..!

See the json link >> http://www.mocky.io/v2/5911638a1200001e020fb5d2

My attempt so far..

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";

@Override
public void onTokenRefresh() {

    String refreshedToken = FirebaseInstanceId.getInstance().getToken();

    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String token) {

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("fcm_token", token);

     Customer me = Hawk.get("user");
     String URL = API_URLs.TokenURL(me.getID());

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method
            .POST, URL, new JSONObject(params),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                   //Log
                }
            },
            new Response.ErrorListener()

            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                   //Log


                }

            }
    );

    requestQueue.add(jsObjRequest);

UPDATE

I change request to this and still didn't change..!?

 JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            URL, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                 }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
         }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("fcm_token", token);

            return params;
        }

    };

     requestQueue.add(jsonObjReq);

UPDATE 2

so after a lot of attempts still not solved, but I'm gonna explain what I want to do exactly maybe you will get what I want to accomplish, I wanna send my device fcm token to server based on the user id when login, so I have a Customer model class that has the value of fcm_token it must after the request is made it must be set as my token, the process happens in web server btw.

Here's my code so far..

MyFirebaseInstanceIDService Class

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";
String refreshedToken;

@Override
public void onTokenRefresh() {

    refreshedToken = FirebaseInstanceId.getInstance().getToken();

    Hawk.put("token", refreshedToken);

}

public static void sendRegistrationToServer(Context context) {

   }
 }

Customer Model Class

public class Customer {

@SerializedName("avatar_url")
@Expose
private String cusPicURL;

@SerializedName("first_name")
@Expose
private String firstName;

@SerializedName("last_name")
@Expose
private String lastName;

@SerializedName("fcm_token")
@Expose
private String token;

public String getToken() {
    return token;
}

public void setToken(String token) {
    this.token = token;
}

// ..... more variables & setters and getters

My Request Code inside a repository class (all request are here..)

   public static void UpdateFCM_Token(final Context context, final String token) {

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    Customer me = Hawk.get("user");
    Log.i("USER ID: ", "" + me.getID());
    String URL = API_URLs.TokenURL(me.getID());

    JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST,
            URL, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONObject o = response.getJSONObject("customer");
                        Gson gson = new Gson();
                        Customer customer = gson.fromJson(o.toString(), Customer.class);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Log.d("FCM OnResponse", response.toString());
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("FCM Error: ", "" + error.getMessage());
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("fcm_token", token);
            return params;
        }
    };
    requestQueue.add(req);
 }

The fragment in MainActivity

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // code..

    String token = Hawk.get("token");
    Log.i("TOKEN", token);
    DriverRepository.UpdateFCM_Token(getActivity(), token);

    return rootView;
}

The Logs

enter image description here

Alaa AbuZarifa
  • 1,171
  • 20
  • 39

3 Answers3

1

You may have to override getParams of JsonObjectRequest and pass your POST params.

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method
            .POST, URL, null, listener, errorListener){
    protected Map<String,String> getParams() throws AuthFailureError{
        return postParamsMap;
    }
}

You can also use StringRequest instead of JsonObjectRequest.

StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
            URL, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d(TAG, response);
                    //Converting the response to JSON
                    JSONObject jsonObj = new JSONObject(response);
                 }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
         }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("fcm_token", token);

            return params;
        }

    };
requestQueue.add(jsonObjReq);
VishnuSP
  • 599
  • 5
  • 16
  • You can try `StringRequest` instead of `JsonObjectRequest` and convert the response string to JSON. – VishnuSP May 09 '17 at 07:21
  • didn't work either, it called onErrorResopnse ! would please look at my url and see what type of request is the right one..!? – Alaa AbuZarifa May 09 '17 at 12:23
  • The response from your url is in JSON form and it should work as per my understanding. What is the error message you are getting `onErrorResopnse`. Please share the logs if possible. – VishnuSP May 10 '17 at 04:07
  • Did you try with `StringRequest`? What is the error you are getting in `StringRequest` case ? As per the logs, you got 400 response which indicats that the data stream sent by the client was 'malformed' i.e. did not respect the HTTP protocol completely. So try `error.printStackTrace` and check whether any more info available on where the request goes wrong. – VishnuSP May 10 '17 at 10:17
1

Hey you suppose to add Map + remove null from new JsonObjectRequest(.......null,listener....):

 private void sendRegistrationToServer(String token) {

RequestQueue requestQueue = Volley.newRequestQueue(this);

HashMap<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);

 Customer me = Hawk.get("user");
 String URL = API_URLs.TokenURL(me.getID());

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
               //Log
            }
        },
        new Response.ErrorListener()

        {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
               //Log


            }

        }
){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String,String> map = new HashMap();
            //add your params here to the map
            return map;
        }
    };

requestQueue.add(jsObjRequest);
Ron Shoshani
  • 913
  • 8
  • 13
  • hey,remove the null from the request, look at my code the new JsonObjectRequest(....) is difference then yours – Ron Shoshani May 09 '17 at 07:18
  • It won't allow me, it keeps showing error..! see this pic https://image.ibb.co/mhoHGQ/zzzzzzxx.jpg – Alaa AbuZarifa May 09 '17 at 07:49
  • hey try this way : new JsonObjectRequest(Request.Method.POST, url,new JsonObject(params),..listener.,.listener..) – Ron Shoshani May 09 '17 at 08:09
  • ok so first of all, please check if the request to the server works download POSTMAN and send the request over there and check if there is no problem with the server – Ron Shoshani May 10 '17 at 10:47
  • if you still have a problem look at this: [link](http://stackoverflow.com/questions/19837820/volley-jsonobjectrequest-post-request-not-working) – Ron Shoshani May 10 '17 at 10:57
0

after some works, I solved it using okhttp3 since volley didn't work for me, although the rest of request in my app are using volley but this one is only okhttp3, I hope that's not a bad practice.

Thanks a lot guys for ur help..!

here's the code in my request method.. in case someone might have the same problem.

 public static void UpdateFCM_Token(final String token) {

    Customer me = Hawk.get("user");
    Log.i("USER ID: ", "" + me.getID());
    String URL = API_URLs.TokenURL(me.getID());

    OkHttpClient client = new OkHttpClient();

    String json = "{\"fcm_token\":\"" + token + "\"}";

    Log.i("Json  : ", json);

    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, json);
    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(URL)
            .post(body)
            .addHeader("content-type", "application/json")
            .build();

    try {
        okhttp3.Response response = client.newCall(request).execute();
        isTokenSent = true;
        Log.i("response ", response + "");

    } catch (IOException e) {
        e.printStackTrace();
        Log.i("IOException", "" + e);

    }
  }
Alaa AbuZarifa
  • 1,171
  • 20
  • 39