i wanted to post the json object using retrofit.
i have created following interface:
public interface syncinter {
#POST("url")
void sync_data(#Body JSONObject ordObj, Callback<JsonObject> callback);
}
the following data i want it to post.
final JSONObject ordJsonObj = new JSONObject();
JSONArray ordJsonArray = new JSONArray();
try {
ordJsonObj.put("Order_Nos",mOrdArr.size());
for (int i=0; i<mOrdArr.size();i++) {
JSONObject ordObj = new JSONObject();
ordObj.put("Order_No",mOrdArr.get(i).getorderID());
ordObj.put("Order_Date",mOrdArr.get(i).getorderDate());
ordObj.put("Customer_id",mOrdArr.get(i).getCustPKID());
Customer aCust = db.getEmployee(mOrdArr.get(i).getCustPKID());
ordObj.put("Cust_name",aCust.getEmpName());// query DB
ordObj.put("Company_id",sharedpreferences.getString(OrderApplication.CompanyID,"")); // sharedP
ordObj.put("Device_Ref",mOrdArr.get(i).getOrdPKID());// sharedP
ordObj.put("User_ID",sharedpreferences.getString(OrderApplication.UserID,""));// sharedP
JSONArray prodJsonArray = new JSONArray();
ArrayList<Product> mProdArr = db.getAllProductOrder(mOrdArr.get(i).getorderID());
for (int j=0; j<mProdArr.size();j++) {
JSONObject prodObj = new JSONObject();
prodObj.put("Product_id",mProdArr.get(j).getPrID());
prodObj.put("Product_name",mProdArr.get(j).getprName());
prodObj.put("Product_Brand",mProdArr.get(j).getBrandName());
prodObj.put("Qty",mProdArr.get(j).getPrQty());
prodObj.put("Rate",(Double.parseDouble(mProdArr.get(j).getPrAmt()+"")/ mProdArr.get(j).getPrQty()));
prodObj.put("Total_Amount",(Double.parseDouble(mProdArr.get(j).getPrAmt()+"")));
prodJsonArray.put(j, prodObj);
}
ordObj.put("OrderDetails",prodJsonArray);
ordJsonArray.put(i,ordObj);
}
ordJsonObj.put("Orders",ordJsonArray);
Log.d("response", "" + ordJsonObj.toString());
I have written the following retrofit code to post the json object but with this following code I am getting
failure -> error : 400 Bad Request.
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(OrderApplication.getBase_URL)
.build();
//Creating object for our interface
syncinter api = adapter.create(syncinter.class);
api.sync_data(ordJsonObj, new Callback<JsonObject>() {
#Override
public void success(JsonObject jsonObject, retrofit.client.Response response) {
}
#Override
public void failure(RetrofitError error) {
Log.d("ERROR", String.valueOf(error));
Toast.makeText(getActivity(),"Order failed to place on Server",Toast.LENGTH_LONG).show();
}
});
i was able to post it using TypedInput declare the api as shown below
#PUT(ServerEndPoint)
void callApi(#Body TypedInput input, Callback<Response> response);
and send the json object like this
TypedInput input = null;
try {
JSONObject obj = new JSONObject();
obj.put("KEY", "value");
input = new TypedByteArray("application/json", obj.toString().getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
callApi(input, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
}
#Override
public void failure(RetrofitError error) {
}
});
not of relative importance i am using retrofit 1.9
Related
I have some error parse Json on Android Studio,
Please if you have any idea can you share where is my error.
I want to get the current exchange rate information and print it on textview.
Json/Api Url : https://api.exchangeratesapi.io/latest?base=USD
private void jsonParse() {
String SHOP_URL = "https://api.exchangeratesapi.io/latest?base=USD&symbols=EUR,GBP";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, SHOP_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("rates");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject result = jsonArray.getJSONObject(i);
int xGBP=result.getInt("GBP");
usdtry.setText(String.valueOf(xGBP));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
pRequestQueue.add(request);
}
This code not erroring but not response any..I think i have some missing.
rates is a JsonObject, not an Array.
So, your code must be
JSONObject rates = response.getJSONObject("rates");
double xGBP = rates.getDouble("GBP");
usdtry.setText(String.valueOf(xGBP));
Also, for better formatting, you can use:
DecimalFormat formatter = new DecimalFormat("###,###.##", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
usdtry.setText(formatter.format(xGBP));
json with int key value
I've been stuck, to call json like this to android studio using volley, I've never done this before
According to this json with int key value
you are
receiving jsonArray instead of jsonObject
so you have to
send the request of JsonArray with volley
then the request will return jsonArray then you can get your string like this.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("url", new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response)
{
try
{
for (int i=0;i<response.length();i++)
{
JSONArray jsonArray = response.getJSONArray(i);
for (int j=0;j<jsonArray.length();j++)
{
String yourString = jsonArray.getString(j);
// you can convert it into int as per your requirement
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
}
});
I am creating an app which uses volley. I used JsonObjectRequest() to send Json object through volley. Thus I had to create Jason Object from values taken from Edit text.
btn_enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SN1 = inputsn.getText().toString();
Name1 = inputname.getText().toString();
}
});
JSONObject jsonMenu= null;
try {
jsonMenu = new JSONObject("");//string is to be added here
Toast.makeText(Add.this,"Made Obj",Toast.LENGTH_SHORT);
} catch (JSONException e) {
e.printStackTrace();
Log.d("Add","Error");
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,jsonMenu, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("MainActivity",response.toString());
Toast.makeText(Add.this,"Response Received",Toast.LENGTH_SHORT);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Add.this,"Error",Toast.LENGTH_SHORT);
}
});
RequestQueue queue= Volley.newRequestQueue(this);
queue.add(request);
Here, [{"SN":1,"Name":"Ajeeb"}] values 1 and Ajeeb is to be replaced by values of SN1 and Name1 respectively.Such that I can add it to Java code
JSONObject jsonMenu = new JSONObject("\\String goes here");
You can create property for json object and than as it to your Json Object
jsonMenu.addProperty("SN", SN1);
jsonMenu.addProperty("Name", Name);
This will result in {"SN":1,"Name":"Ajeeb"}
And if you want to create an array for it
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonMenu);
This will result in [{"SN":1,"Name":"Ajeeb"}]
I need to retrieve a list of json objects from mysql database, parse it using volley and populate a listview with it. I'm new to php and volley. Here's how I'm trying.
JSON:
{"result":[{"id":"3133482000","name":"John Doe","class":"3A","parent":"admin#gmail.com","status":"0","stopid":"6","busno":"0"},{"id":"0","name":"","class":"","parent":"","status":"0","stopid":"0","busno":"0"},{"id":"334","name":"sam","class":"3a","parent":"","status":"0","stopid":"2","busno":"0"}]}
Android:
JSONArray sts;
public static final String STUDENT_URL = "http://www.smartlbus.esy.es/getAllStudents.php";
students=new ArrayList<Student>();
StringRequest stringRequest = new StringRequest(STUDENT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=null;
jsonObject = new JSONObject(response);
sts = jsonObject.getJSONArray(JSON_ARRAY);
for (int i = 0; i < sts.length(); i++) {
JSONObject jo = sts.getJSONObject(i);
Student s=new Student();
Toast.makeText(StudentDetails.this,jo.getString(STUDENT_NAME),Toast.LENGTH_SHORT).show();
s.setId(jo.getString(STUDENT_ID));
s.setName(jo.getString(STUDENT_NAME));
s.setClassNo(jo.getString(STUDENT_CLASS));
s.setBusno(jo.getString(STUDENT_BUS));
s.setStatus(Integer.parseInt(jo.getString(STUDENT_STATUS)));
s.setStopid(jo.getString(STUDENT_STOP));
students.add(s);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
listView.setAdapter(new CustomListAdapter(StudentDetails.this,students));
Please help me out. In case this doesn't meet the standards here, please comment and let me know. I'll take it down.
Try to use Gson to ease your development.
Create your Java POJO Class:
public class StudentList {
List<Student> results;
// setter
public static class Student {
String name;
String id;
String status;
String class;
String stopid;
String busno;
// getter
}
}
Then parse them using GSON in the onResponse() method.
I'd suggest to use Retrofit to make network calls.
Gson gson = new Gson();
StudentList list = gson.fromJson(response);
// populate to ListView using list.getResults()
Try this & also check your URL. Your url not returning any json response.
StringRequest stringRequest = new StringRequest(Request.Method.GET,STUDENT_URL ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("TAG","response :"+response);
JSONObject jsonObject = new JSONObject(response);
sts = jsonObject.getJSONArray(JSON_ARRAY);
for (int i = 0; i < sts.length(); i++) {
JSONObject jo = sts.getJSONObject(i);
Student s=new Student();
Log.d("TAG","Name :"+jo.getString(STUDENT_NAME));
// Toast.makeText(StudentDetails.this,jo.getString(STUDENT_NAME),Toast.LENGTH_SHORT).show();
s.setId(jo.getString(STUDENT_ID));
s.setName(jo.getString(STUDENT_NAME));
s.setClassNo(jo.getString(STUDENT_CLASS));
s.setBusno(jo.getString(STUDENT_BUS));
s.setStatus(Integer.parseInt(jo.getString(STUDENT_STATUS)));
s.setStopid(jo.getString(STUDENT_STOP));
students.add(s);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
e.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Is it possible to check the type of json beforehand? I'm somteimes getting an array and sometimes an object and I don't see how to handle these 2 cases without doing 2 different functions...
public void RequestApi( String url, final ApiResponse<ApiResult> completion )
{
Log.v("Performing request: ", url);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, hostname+url, (JSONObject) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.v("RequestApi Response", response.toString());
//Log.v("Data: ", response.toString());
try {
ApiResult res = new ApiResult();
Boolean success = response.getBoolean("success");
//here need to check type, sometimes array, sometimes object
JSONArray data = response.getJSONArray("data");
res.success = success;
res.data = data;
completion.onCompletion(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ApiResult res = new ApiResult();
res.success = false;
completion.onCompletion(res);
}
}
);
AppController.getInstance().addToRequestQueue(jsonRequest);
}
Use StringRequest
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO something
}
});
Most simple solution - look at first string character. If it is { - object, if [ - array. But I think better to do following:
try {
JSONObject object = new JSONObject(value);
}
catch (JSONException) {
//if it throws, "value" contains not a JSONObject
JSONArray array = new JSONArray(value);
}
After going through the API I found a simple solution.
Since you are not sure of the return type, follow mentioned below steps.
First:
JSONArray arrayInstance = new JSONArray();// declare array instance to handle both the cases
Object objectInstance = rootObject.get(key); //key is the response string holding the value either jsonArray or jsonObject
Second:
if(objectInstance instanceof JSONArray){
arrayInstance = rootObject.getJSONArray(key);
}
else{
JSONObject tempObject = rootObject.getJSONObject(key);
arrayInstance.put(tempObject);
}
Third:
You can iterate though the array for the desired processing.