Error null! from Volley on Http Post Request with JSon object - android

I'm getting a Null Exception with JSon object from Volley
I filled the JSon object before it is used, and not in the parameterlist.
public static void SendPost6(final Context context){
final String TAG= "-->Error-->";
String url = "http://192.168.44.120/test_php_neuer_user.php";
RequestQueue queue = Volley.newRequestQueue(context);
JSONObject userObject = new JSONObject();
JSONObject paramsObject = new JSONObject();
try {
paramsObject.put("name", "Name");
paramsObject.put("email", "EMail");
userObject.put("user",paramsObject);
}
catch (JSONException e){
Toast.makeText(context, "JSON-Error:" + e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,
userObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(context, "Volley Response:" + response.toString(), Toast.LENGTH_LONG).show();
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle errors#
Log.d(TAG, "Failed with error msg:\t" + error.getMessage());
Log.d(TAG, "Error StackTrace: \t" + error.getStackTrace());
Toast.makeText(context, "Volley Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
try {
byte[] htmlBodyBytes = error.networkResponse.data;
Log.e(TAG, new String(htmlBodyBytes), error);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
queue.add(request);
//AppController.getInstance().addToRequestQueue(request);
I want to add the json object request into the queue to perform http-post. Volley Error is "null"

The firewall blocked the network access. This is why i'm getting response null. Solved.

Related

org.json.JSONException in volley

I am parsing json using volley but its not working and getting error. Follwing is my code and json reponse. please help me to solve this
private void getStaffList() {
showpDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
final String url = "url";
try {
final JSONObject jsonObj = new JSONObject();
jsonObj.put("username", "test");
jsonObj.put("password", "123456");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, jsonObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", "Main response=" + response);
staffarraylist=new ArrayList<DataModel>();;
try {
JSONObject jobSuccess=response.getJSONObject("TABLE_DATA");
Log.d("TAG", "JSONObj response=" + jobSuccess);
JSONArray jarMyData=jobSuccess.getJSONArray("data");
Log.d("TAG", "JSONArray response=" + jarMyData);
for (int i = 0; i < jarMyData.length(); i++) {
JSONArray jar = jarMyData.getJSONArray(i);
DataModel movie = new DataModel();
movie.setName(jar.getString(0));
movie.setOccupation(jar.getString(1));
movie.setPlace(jar.getString(2));
movie.setId(jar.getString(3));
movie.setDate(jar.getString(4));
movie.setPrice(jar.getString(5));
staffarraylist.add(movie);
}
}catch (JSONException e)
{
Log.d("JSONException",e.toString());
}
rcAdapter = new RecyclerViewAdapterHome(MainActivity.this, staffarraylist);
recyclerView.setAdapter(rcAdapter);
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "JSONObj Error: " + error.getMessage());
hidepDialog();
//Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
}
});
requestQueue.add(jsonObjReq);
} catch (JSONException e) {
e.printStackTrace();
}
}
Logcat
Main response={"TABLE_DATA":"{\"data\":[[\"Tiger Nixon\",\"System Architect\",\"Edinburgh\",\"5421\",\"2011/04/25\",\"$320,800\"],[\"Garrett Winters\",\"Accountant\",....so on
D/JSONException: org.json.JSONException: Value {"data":[["Tiger Nixon","System Architect","Edinburgh","5421","2011/04/25","$320,800"],["Garrett Winters","Accountant","Tokyo","8422","2011/07/25","$
First check that your json format is correct or not by clicking here and paste your json for checking. If the response is correct then use Gson. It will parse the response without any error.

How can I return value from onResponse of Volley?

I want to save values from Response on user class variables.
Unfortunately, I cannot.
Help me please.
This is the code JSONObjectRequest
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
jsonURLFull, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(ActivityLogin.class.getSimpleName(), response.toString());
try {
User userClass = new User();
JSONObject jsonUser = response.getJSONObject("user");
userClass.id = jsonUser.getInt("id");
userClass.name = jsonUser.getString("email");
userClass.email = jsonUser.getString("email");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(ActivityLogin.class.getSimpleName(), "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);
This is the User class:
public class User {
public int id;
public String name;
public String email;
}
This is the JSON of the API:
{"user":{"id":12,"name":"test_name","email":"test#email.com",}}
Two points for you :
1.you parse email to name attribude.
userClass.name = jsonUser.getString("name");
2.your json data is wrong due to the last ','
{"user":{"id":12,"name":"test_name","email":"test#email.com"}}

Volley Multipart Request with Progress Bar

how to use progressbar in volly multipart request to upload images. i am using VolleyPlus library for multipart request. my multipart request code is
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, 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) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
smr.addMultipartParam("name", fileType, fileName);
MyApplication.getInstance().addToRequestQueue(smr);
now i want to add progressbar for uploading file like this:
or

Volley JsonObjectRequest send headers in GET Request

I am trying to send some authentication headers from GET request and I tried using Volley JsonObjectRequest call :
Map<String,String> params=new HashMap<String,String>();
params.put("token","fghjbvjhnjjk");
activity.showDialog();
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
req.setShouldCache(true);
But its showing:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.<init>(Request.java:136)
at com.android.volley.toolbox.JsonRequest.<init>(JsonRequest.java:58)
at com.android.volley.toolbox.JsonObjectRequest.<init>(JsonObjectRequest.java:47)
I read somewhere that you can pass headers by making a hashmap and thus create a new JsonObject with that parameter. Maybe that will work on a POST request. Please help..
Well, the thing is simple and very precise. Passing headers to either GET or POST request, you need to override getHeaders method in JsonObjectRequest Class. This is how it will be done:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
//headers.put("Content-Type", "application/json");
headers.put("key", "Value");
return headers;
}
};

Volley synchronous request

I just started to use Volley's library to make http calls, and I tried to use the RequestFuture class for synchronous requests, but I fail my attempt to make a simple request. Any idea of what I am doing wrong?
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "http://myapi-oh.fr/v2/podcasts/x/shows/" + points.get(0).getShowId() + "/streams";
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(url, null, future, future);
requestQueue.add(request);
try {
JSONObject response = future.get(10, TimeUnit.SECONDS);; // this will block (forever)
points.get(0).setStreamUrl(response.getJSONArray("result").getJSONObject(0).getString("url"));
} catch (InterruptedException e) {
Log.d(TAG, "error : " + e);
// exception handling
Log.d(TAG, "error : " + e);
} catch (ExecutionException e) {
// exception handling
Log.d(TAG, "error : " + e);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "error : " + e);
} catch (TimeoutException e) {
e.printStackTrace();
}
To make a simple request just use the StringRequest class. Below is a small snippet:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest req = new StringRequest(Request.Method.POST, "your_url", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//handle response here.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//handle error here.
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//return params(if any) to server here.
return super.getParams();
}
};
queue.add(req);

Categories

Resources