Notifications are not send while I'm receiving no error - java

I'm creating a application but I'm stuck on the notification part. I want the android app to send a notification when I press on the button. I've done that by using HTTP request to Firebase but it is not sending the notification. It also does not give me a error. I followed a YouTube tutorial online but I couldn't contact the creator of the video and nobody in the comments section could help me.
private RequestQueue mRequestQueue;
private String URL = "https://fcm.googleapis.com/fcm/send";
public void sendMessage() {
JSONObject mainObj = new JSONObject();
try {
mainObj.put("to:", "/topics/news");
JSONObject notificationObj = new JSONObject();
notificationObj.put("title", "any title");
notificationObj.put("body", "any body");
mainObj.put("notification",notificationObj);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,
mainObj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(Main3Activity.this, "LADIES AND GENELTJEATMK", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main3Activity.this, "ERROR E SAH", Toast.LENGTH_SHORT).show();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Content-Type", "text/json");
header.put("authorization", "key=MYKEYSHOULDCOMEHERE");
return header;
}
};
mRequestQueue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

Android Volley: BasicNetwork.performRequest: Unexpected response code 400

E/Volley: [1888] BasicNetwork.performRequest: Unexpected response code 400 for https://pastebin.com/raw/2WMVsLei
Problem only Pastbin. I will try another https api but can't face any issue. Issue only occurs with pastebin api.
public void logIn() {
String URL="";
try {
JSONObject old = new JSONObject(Constantse.decrypt(PreferenceUtils.getAllData(con)));
String updateUrl = old.getString("DefUpdateURL");
URL = updateUrl;
}catch (Exception e){
System.out.println(e);
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject old = new JSONObject(Constantse.decrypt(PreferenceUtils.getAllData(con)));
JSONObject news = new JSONObject(Constantse.decrypt(response));
System.out.println(Constantse.decrypt(response));
if(Integer.parseInt(news.getString("UpdateVersion")) > Integer.parseInt(old.getString("UpdateVersion"))){
PreferenceUtils.setCredientials(con,news.getJSONArray("Servers").toString());
PreferenceUtils.setPayload(con,news.getJSONArray("payload").toString());
PreferenceUtils.setAllData(con,response);
editor.putInt("current_server", 0).apply();
editor.putInt("current_payload", 0).apply();
Toast.makeText(getActivity(),"Update Success",Toast.LENGTH_SHORT).show();
getActivity().finish();
startActivity(getActivity().getIntent());
}else{
System.out.println("Don't Update");
Toast.makeText(getActivity(),"Already Updated",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
System.out.println(e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
logIn2(); // this is additional api for server & payload
Toast.makeText(getActivity(),"Use Next Server",Toast.LENGTH_SHORT).show();
System.out.println(error);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
stringRequest.setShouldCache(false);// for cash clear
Volley.newRequestQueue(con).add(stringRequest);
Volley.newRequestQueue(con).getCache().clear();// for cash clear
}

Android volley returns clienterror 400 [Bad request]

I try everything to solve it but I couldn't. can anybody help me to solve this.
I try to login through volley but it gives bad request 400 error, I think it is because of body content type but I also override getbodycontenttype method but it doesn't work,
here is code
String url = "http://192.168.1.129:5000/api/dealers/login";
StringRequest stringRequest = new StringRequest( Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
Log.d("response", response);
try {
JSONObject data= new JSONObject(response);
//Boolean error =jsonObject.getBoolean("error");
if (data.getString("success").equals("true")) {
String message=data.getString("msg");
startActivity( new Intent( LoginActivity.this, MainActivity.class ) );
finishAffinity();
} else {
Toast.makeText(LoginActivity.this,
data.getString("msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(LoginActivity.this, String.valueOf(networkResponse.statusCode),
Toast.LENGTH_SHORT).show();
}else{
Log.e("Status code", String.valueOf(error));
Toast.makeText(LoginActivity.this, String.valueOf(error),
Toast.LENGTH_LONG).show();
}
}
}){
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("mobile",userMobile);
params.put("password",userPassword);
return params;
}
};
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(stringRequest);
HelloIf your server is correct, do this, but when I used this address, I did not receive any data ...
I also made a error in doing a project using it ... it is better to use version of 1.1.0 and before it ...

Error in Json in volley to Android Studio

I want to call a Api But Reception error is running !!
I have a Json api
A Java class to call
Please help me fix the error!
my jeson:
my class in load data:
public void loadproductview() {
String url = "https://alphaonline.ir/index.php?route=api32/product/product&token=3344556677";
Response.Listener<JSONObject> objectListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String name = response.getString("name");
txt_name.setText(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
};
Map<String, String> params = new HashMap();
params.put("product_id", "237");
JSONObject parameters = new JSONObject(params);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, parameters, objectListener, errorListener);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
}
You are initializing JSONObject with Map which is wrong>
Directly put the values in JSONObject.
JSONObject parameters = new JSONObject();
parameters.put("product_id", "237");
Try this:-
public void loadproductview() {
String url = "https://alphaonline.ir/index.php?route=api32/product/product&token=3344556677";
Response.Listener<JSONObject> objectListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String name = response.getString("name");
txt_name.setText(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductActivity.this, error.toString(),
Toast.LENGTH_SHORT).show();
}
};
JSONObject parameters = new JSONObject(params);
parameters.put("product_id", "237");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,
parameters, objectListener, errorListener);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
}
I am not sure how you handle the singleton instance of the request, so instead of this:
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
do this:
RequestQueue queue = Volley.newRequestQueue(this);
queue.addToRequestQueue(request);

How to fix "Volley: [15771] BasicNetwork.performRequest: Unexpected response code 404 in android?

The API is developed in Wordpress with POST method. API is working fine in POSTMAN and iOS(swift). I am getting response in POSTMAN and my colleague iOS developer also getting response.
But in Android I am getting 404 error in Android Studio.
I am trying to resolve with different Volley request like StringRequest, JSONObjectRequest and HttpURLConnection with AsyncTask. But getting only 404 error. Any one tell me what is the exact issue?
Below is my code.
private void RegisterUser(){
final ProgressDialog progressDialog = new ProgressDialog(RegistrationActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please wait...");
progressDialog.show();
StringRequest postrequest = new StringRequest(Request.Method.POST, Urls.REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
Log.e("res","==> "+response);
}
catch (Exception e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {progressDialog.dismiss();error.getLocalizedMessage();}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", "khushbu");
params.put("email", "kh#test.com");
params.put("user_pass", "test#123");
params.put("display_name", "khushbu");
params.put("company_name", "");
params.put("nature_of_business", "");
params.put("country", "");
params.put("nonce", "12e099a946");
params.put("notify", "both");
params.put("insecure", "cool");
Log.e("params","==> " + params);
return params;
}
};
FlawlessApplication.getInstance().addToRequestQueue(postrequest);
}
I also tried with adding headers but can't get any solution.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
params.put("cache-control", "no-cache");
return params;
}
Thank you in advance.
final ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(mContext, "", "Loading..");
progressDialog.setCancelable(false);
progressDialog.show();
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
HashMap<String, String> params = new HashMap<>();
params.put("username", "khushbu");
params.put("email", "kh#test.com");
params.put("user_pass", "test#123");
params.put("display_name", "khushbu");
params.put("company_name", "");
params.put("nature_of_business", "");
params.put("country", "");
params.put("nonce", "12e099a946");
params.put("notify", "both");
params.put("insecure", "cool");
Log.e("params","==> " + params);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
Urls.REGISTER,
new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
try {
Log.e("res","==> "+response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Do something when error occurred
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headerParams = new HashMap<>();
//add header params if having
headerParams.put("KEY", "value");
return headerParams;
}
};
// Add JsonObjectRequest to the RequestQueue
requestQueue.add(jsonObjectRequest);
In my case.
I was using the http in my API so after changing to https it worked for me. and in postman no matter it http or https it works the same.

Volley Request not giving any reponse

I am new to Android. I am figuring out how to make network calls. I am trying to send Headers along with JSON data. I tried debugging the code but it's not going to onResponse(). Can someone tell me what am i doing wrong .
Below is my code.
String url = "https://api.....";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("image", "https://i.imgur.com/5KdM.jpg");
jsonObject.put("subject_id", "Elixabeth");
jsonObject.put("gallery_name", "MyGallery");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null){
}
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("app_id", "");
headers.put("app_key", "");
headers.put("Content-Length", "124");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
I tried the same in Postman with same data and I am getting response.
Put the log inside
onResponse(JSONObject response) method Log.d("Response", response.toString()); and in
onErrorResponse(VolleyError error) method Log.e("Error", error.getMessage());.
Then check the logcat,you can find what goes wrong...

Categories