Android Volley post json data to server - java

I am new in Java. I want to send post json data to webserver.
My Volley post is given below.
public void postData(String url,JSONObject data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
//here I want to post data to sever
};
requstQueue.add(jsonobj);
}
Here is my MainActivity code
JSONObject data = null;
try {
String datas = "{'email': email,'password': password}";
data = new JSONObject(datas);
}catch (JSONException e){
e.printStackTrace();
}
String url = "http://example.com";
I want to post JSON data to my PostData method.
How can I post this json data to my server?

public void postData(String url,Hashmap data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(data),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
//here I want to post data to sever
};
requstQueue.add(jsonobj);
}
Now, from your mainActiviy class
Hashmap data = new HashMap();
data.put("email","email");
data.put("password","password");
String url = "http://example.com";
//now you can just call the method, I have rectified your string to hashmap,
postData(url,data,new mResultCallb..... //rest of your code

public void postData(String url,JSONObject data,final VolleyCallback mResultCallback){
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
);
requstQueue.add(jsonobj);
}

public void postData(String url,final JSONObject data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
if(data != null){
Iterator<String> keysItr = data.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = data.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
params.put(key, value);
}
}
return params;
}
};
requstQueue.add(jsonobj);
this is working code for me
Hope this might be work for you..
Happy Codding

Related

How to get String response from post request volley

I am trying to get a string response from post request. Here, I am sending a post request. where I am sending this data. I have a Model of BillReceipt. Which I pass on the request body.
public void UserTransactionReceiptReport(TransactionTypeListener<String> listener, BillReceipt billReceiptReport){
final UserSettings userSettings = getMUserSettings();
final StringBuilder url = new StringBuilder(AppConfigsManager.getTouchServerUrl());
url.append("/api/User/UserData");
JSONObject params = new JSONObject();
try{
params.put("iB_CUST_ID",billReceiptReport.getiB_CUST_ID());
params.put("transactioN_DATE",billReceiptReport.getTransactioN_DATE());
params.put("transactioN_DATE_NM",billReceiptReport.getTransactioN_DATE_NM());
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url.toString(), params
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Gson mapper = new GsonBuilder().create();
try{
Type type = new TypeToken<APIResponse<String>>() {
}.getType();
APIResponse<String> responseObject = mapper.fromJson(response.toString(), type);
if(responseObject.Status == APIStatus.OK){
listener.didFetch(responseObject.Result, responseObject.Message);
}else {
listener.didError(responseObject.Message);
}
}catch (Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.didError(error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() {
return getAuthorizationTokenHashMap(getMUserSettings());
}
};
addVolleyRequest(request);
}
and I call this api from recycler download button.Here , I globally declared the manager where i write the api code. and also declare a the model name.
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager.UserTransactionReceiptReport(listener,billReceiptReport);
}
});
}
private final TransactionTypeListener<String> listener = new TransactionTypeListener<String>() {
#Override
public void didFetch(String response, String message) {
str = response;
}
#Override
public void didError(String message) {
}
};
any one help me to solve the problem i am facing.
Try this code
<code>
JSONObject jsonObject = new JSONObject(response);
System.out.println("jsonWallet----" + jsonObject);
int status_ = jsonObject.getInt("status");
if(status_ == 1){
String incomeWalletBal = jsonObject.getString("income_wallet");
String refundWalletBal = jsonObject.getString("refund_wallet");
}else {
}
</code>

JsonObjectRequest GET Request retrieves value after method returns value

I am trying to retrieve a JsonObject via GET request. When I set Breakpoints in my code I see that the count() method returns nothing. After that the onResponse method from the inner class gets called and the desired value gets retrieved.
I am calling the count() method inside the save() method. In order to create a JSONObject. The code creates the JSONObject before it retrieves the correct customer count.
I am using a custom requesQueue called AppController to queue the network request. I hope someone understands this strange behaviour.
#Override
public void save(Customer customer) throws JSONException {
int zw = count();
JSONObject obj = new JSONObject();
obj.put("customernumber", count + 1);
obj.put("name", customer.getName());
obj.put("lastname", customer.getLastname());
obj.put("phonenumber", customer.getPhonenumber());
obj.put("addressid", customer.getAdressID());
obj.put("password", customer.getPassword());
String urlJsonObj = URL;
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
urlJsonObj, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public int count() {
String countURL = URL + "/count";
JsonObjectRequest jsonObjReq = new JsonObjectRequest
(Request.Method.GET, countURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
count = response.getInt("count");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d( "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);
return count;
The AppController network queue
public class AppController extends Application {
public static final String TAG = AppController.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
What's Happening?
This is happening due to incorrect thread usage. count() function performs the network request in the background thread, so it won't return the count immediately when we call it from save() function.
Solution
Wait for the response from count API and then perform a save operation. Replace the above implementation with the following
#Override
public void save(Customer customer) throws JSONException {
count();
}
private void performSave(Customer customer, int count) throws JSONException {
int zw = count; // Finally received the count
JSONObject obj = new JSONObject();
obj.put("customernumber", count + 1);
obj.put("name", customer.getName());
obj.put("lastname", customer.getLastname());
obj.put("phonenumber", customer.getPhonenumber());
obj.put("addressid", customer.getAdressID());
obj.put("password", customer.getPassword());
String urlJsonObj = URL;
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
urlJsonObj, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public int count(Customer customer) {
String countURL = URL + "/count";
JsonObjectRequest jsonObjReq = new JsonObjectRequest
(Request.Method.GET, countURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
count = response.getInt("count");
performSave(customer, count);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d( "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);
return 0; // Remove this return type as we will not use it anymore
}

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 POST raw type JSON Data in Body?

I'm sending a post request to server using Volley request and i have some raw Type JSON data that has to be sent. Here I have no idea how to send the
4th object students which is type of Array.
JSON data to be posted is
{
"course_id":1,
"batch_id":1,
"subject_id":1,
"students":[{"student_id":6,"present":0},{"student_id":17,"present":0}]
}
My code
private void fetchDataAndMarkAttendence() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
status = jsonObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
SharedPreferences prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, Activity.MODE_PRIVATE);
token = prefs.getString("token","");
map.put("Authorization", "Token "+token);
return map;
}
}
}
So, any help regarding how can i post the JSON data mentioned above will be helpfull.
This is called JSONArray.
try {
JSONArray jsonArray = jsonObject.getJSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
int student_id = jsonObject.getInt("student_id");
int present = jsonObject.getInt("present");
}
} catch (JSONException e) {
e.printStackTrace();
}
EDIT
as mention, you want to post the json. So create the json suing below code and post mainJsonObject.toString(); as parameter.
try {
JSONObject mainJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
//if more than one then wrap inside loop
JSONObject jsonObject = new JSONObject();
jsonObject.put("student_id", value);
jsonObject.put("present", value);
jsonArray.put(jsonObject);
//end loop
mainJsonObject.put("course_id", value);
mainJsonObject.put("batch_id", value);
mainJsonObject.put("subject_id", value);
mainJsonObject.put("students", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
hope it helps.
Replace your StringRequest with JsonObjectRequest
JSONObject postparams = new JSONObject();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
can you try this? This probably will fix your problem.
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
status = jsonObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String yourJSON = yourJsonObj.toString() ;
return yourJSON.getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
SharedPreferences prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, Activity.MODE_PRIVATE);
token = prefs.getString("token","");
map.put("Authorization", "Token "+token);
return map;
}
};

HTTPPOST Android with Body

I was looking for an easy way to make an HTTP post in Android with body, my api call should be like :
https:url/api/message?token=myToken&channel=Pew&text=someText&username=User
What I did is this, I created this class
Public class ApiCalls {
private static PostCommentResponseListener mPostCommentResponse;
private static Context mContext;
public ApiCalls(){
}
public static void postNewComment(Context context, final String message){
mContext = context;
String apiUrl = context.getResources().getString(R.string.api_url);
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("token",mContext.getResources().getString(R.string.access_token));
params.put("channel","pew");
params.put("text", message);
params.put("username","User");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}
}
But it doesn't work, it only shows app has stopped.
Is good to use Volley? Or you recommend to me to use other way? I used to use HttpClient but it's deprecated now...
What I'm missing?
Log error
java.lang.NullPointerException: Attempt to invoke interface method 'void com.package.ApiCalls$PostCommentResponseListener.requestStarted()' on a null object reference
You can send json body using volly as below two ways.
1. Using JsonObjectRequest
Map<String,String> params = new HashMap<String, String>();
params.put("token",mContext.getResources().getString(R.string.access_token));
params.put("channel","pew");
params.put("text", message);
params.put("username","User");
JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Process success response
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
});
// add the request object to the queue to be executed
queue.add(request_json);
2. Using JSON directly in request body
JSONObject jsonBody = new JSONObject();
jsonBody.put("token",mContext.getResources().getString(R.string.access_token));
jsonBody.put("channel","pew");
jsonBody.put("text", message);
jsonBody.put("username","User");
final String mRequestBody = jsonBody.toString();
StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Process success response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody.getBytes("utf-8");
} catch (Exception e) {
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
// add the request object to the queue to be executed
queue.add((sr);
Initialise your mPostCommentResponse like this:
public ApiCalls(){
mPostCommmentResponse = (PostCommentResponseListener)mContext;
}
it will do you work and rest is fine. Thanks.
EDITED:
In Another Activity from where you want to call "ApiCall" class, do code like that:
new ApiCalls().postNewComment(AnotherActivity.this,"Your Messsage here");
and in method "postNewComment" do like this:
mContext = context;
mPostCommmentResponse = (PostCommentResponseListener)mContext;
Is it ok and understable??

Categories