Can we post JsonObject or JsonArray using Android volley to the server?If yes can anyone please send the working sample.
If i post string then it works fine but i have some problem while posting jsonObject or jsonArray.
Yes you can. The JSON is added to the body of a POST request, like this:
JSONObject jsonObject; // your JSON here
requestQueue.add(new JsonObjectRequest(Method.POST, url, jsonObject, listener, errorListener);
Yes, just add data to JSONObject and pass that object in the request.
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
jsonObject.put("password", password);
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("volley", "response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("volley", "error: " + error);
}
});
Related
I want to get a response from a URL that has to do ajax requests to get and update the page without refreshing it.
My problem is when I want to receive its response with the volley library. In onResponse I just receive php code!!?
here is my code:
RequestQueue queue = Volley.newRequestQueue(getActivity());
final String test= "MY URL";
StringRequest stringRequest = new StringRequest(Request.Method.POST, test,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
popup.dismiss();
Log.e("response", response );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
popup.dismiss();
}
});
queue.add(stringRequest);
I tried with Request.Method.POST and Request.Method.GET but no difference.
NOTE:
I only can see the response of this URL when I am using chrome and 'Allow-Control-Allow-Origin' extension is installed.
I am trying to send images taken from my phone to a server, with the code below the app crashes when I try to upload a picture taken from my phone, I know the code works because I am able to upload images I have downloaded onto my phone.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
String fileNameSegments[] = picturePath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
Bitmap myImg = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
myImg.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
}
}
the code that uploads
public void uploadImage() {
RequestQueue rq = Volley.newRequestQueue(this);
String url = "http://serverwebsite.com/image.php";
Log.d("URL", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("RESPONSE", response);
JSONObject json = new JSONObject(response);
Toast.makeText(getBaseContext(),
"The image is upload", Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
Log.d("JSON Exception", e.toString());
Toast.makeText(getBaseContext(),
"Error while loadin data!",
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error [" + error + "]");
Toast.makeText(getBaseContext(),
"Cannot connect to server", Toast.LENGTH_LONG)
.show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("image", encodedString);
params.put("filename", fileName);
return params;
}
};
rq.add(stringRequest);
}
i hope this code help you
public void sendImage(MediaType mediaType)
{
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition",
"form-data; name=\"file\"; filename=" + '"'
+ name + '"'),
RequestBody.create(mediaType, new File(getFileAdress()
))).build();
final String credential = Credentials.basic(userName, pass);
Request request = new Request.Builder()
.header("Authorization", credential)
.url(WebServiceAddress())
.post(requestBody).build();
try {
Response response = client.newCall(request).execute();
int code=response.code();
String out = response.body().string();
if (response.isSuccessful()) {
} else {
} catch (Exception ex) {
}
}
This is my library addresses that I use for resizing photos :
https://github.com/alireza-87/ImageHelper
I'm trying to pass some values to server using JSONObjectRequest of Volley library. But somehow the data isn't being sent to server and the variable of server side script which is supposed to receive the data is empty.
Here is the JSONObjectRequest code
JSONObject obj = new JSONObject();
try {
obj.put("userid", "userid");
} catch (JSONException e) {
e.printStackTrace();
}
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.POST,
URL_FEED, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
Log.d(String.valueOf(getApplicationContext()),"Response generated");
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d("Error - >",error.getMessage());
Toast.makeText(getApplicationContext(),"Error is -->> " + error.getMessage(),Toast.LENGTH_LONG).show();
}
});
php side to get the variable
$userid = $_POST['userid'];
Get it to work by changing the JSONObjectRequest to StringRequest and then convert the Onresponse String to JSONObject as follow
// making fresh volley request and getting json
StringRequest jsonReq = new StringRequest(Method.POST,
URL_FEED, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
VolleyLog.d(TAG, "Response: " + s.toString());
JSONObject response = null;
try {
response = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(String.valueOf(getApplicationContext()), "Response generated");
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d("Error - >",error.getMessage());
Toast.makeText(getApplicationContext(),"Error is -->> " + error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("userid", userid);
return params;
}
};
Here´s the JSON that my php file delivers:
[{"id":"408","punktezahl":"15","name":"testname","email":"hsksjs","datum":"24.01.14 17:11","wohnort":"Vdhdhs","newsletter":"J"}]
When I try to access the JSON Object like this
public void connect(){
System.out.println("%%%%%%%%%%%%%%%%%1" );
Thread t = new Thread(){
#Override
public void run() {
try {
System.out.println("%%%%%%%%%%%%%%%%%2" );
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
String urlString = "http://url";
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
System.out.println("%%%%%%%%%%%%%%%%%3" );
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
//return the JSON response
JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("output");
String name = userDetails.getString("name");
System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
}
}catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
I get the following error:
01-24 18:18:21.746: W/System.err(20673): org.json.JSONException: Value [{"id":"408","datum":"24.01.14 17:11","punktezahl":"15","email":"hsksjs","newsletter":"J","wohnort":"Vdhdhs","name":"testname"}] of type org.json.JSONArray cannot be converted to JSONObject
01-24 18:18:21.746: W/System.err(20673): at org.json.JSON.typeMismatch(JSON.java:111)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:159)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:172)
01-24 18:18:21.746: W/System.err(20673): at com.wuestenfest.jagdenwilli.Highscore_zeigen$1.run(Highscore_zeigen.java:82)
Where´s my mistake?
Your response is a JSONArray not a JSOnObject.
So change
JSONObject parentObject = new JSONObject(response);
to
JSONArray jsonarray = new JSONArray(response);
Your JSON
[ // json array node
{ // jsson onject npode
"id": "408",
"punktezahl": "15",
"name": "testname",
"email": "hsksjs",
"datum": "24.01.14 17:11",
"wohnort": "Vdhdhs",
"newsletter": "J"
}
]
I do not see any json object output either in the above json. So
JSONObject userDetails = parentObject.getJSONObject("output");
is also wrong.
Parsing
JSONArray jsonarray = new JSONArray(response);
JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
String name= jb.getString("name");
The problem is just as the exception describes: you are trying to parse your response object into a JSONObject, but it is actually a JSONArray (as seen by the square brackets). In stead, parse it as a JSONArray, and get the first element from the array, which would be your desired JSONObject.
i am trying to parse an array from my php script to my android app.
my android code
public void func4(View view)throws Exception
{final String TAG_CONTACTS = "response";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc3.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try
{
JSONArray jArray = new JSONArray(response.toString());
// JSONObject jsonObject = new JSONObject(response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
User_List.add(json_data.getString(TAG_CONTACTS));
String s = User_List.get(0).toString();
tx.setText(s);
}
}
catch (Exception e)
{
tx.setText((CharSequence) e);
}
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
now i am sending or ECHOing a jSON array from my php code, which is being read into the response object of string type.
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
echo json_encode($cars);
exit;
?>
now error i am getting is org.json.JSONException: Value Volvo at 0 of type java.lang.String cannot be converted to JSONObject
i think thar onSuccess func accept string parameter and i m sending json as a parameter to it.. thats what causing problem please help.
Try Like this
JSONObject json = jsonParser.makeHttpRequest(url_get_contact, "GET", params);
Log.d("All Groups: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
groups = json.getJSONArray(TAG_GROUP);
System.out.println("Result Success+++"+groups);
for (int i = 0; i < groups.length();i++) {
JSONObject c = groups.getJSONObject(i);
String name = c.getString(TAG_CONTACTS);
System.out.println("Checking ::"+name);
namelist.add(name); // namelist is ur arraylist
}
}else {
showAlert();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
Let me know ur problem solved or not...
Answer found, i guess i was trying to convert an already String converted object from json into string again.
well to be precise i ust deleted JSONObject json_data = jArray.getJSONObject(i);
and it worked for me. Now i am able to save all values in my array.