get object integer json to android studio - android

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)
{
}
});

Related

com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference. How can I parse json using volley?

I'm trying to parse json using volley but I cant receive the data. Assume that I received the data. I send that to the recycler view. But I'm not sure about using the JSONObject. Maybe there is a error I couldn't see it. And this is my json website "https://docs.spacexdata.com/#3d6e6f8a-a459-4265-84b1-e2b288a58537".
private void parseJson() {
String url = "https://docs.spacexdata.com/#d65a7f85-e0c7-41ce-b41d-9ad20a238d90";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i = 0; i < response.length(); i++) {
JSONObject capsuleObject = response.getJSONObject(i);
String details = capsuleObject.getString("details");
String type = capsuleObject.getString("type");
mCapsuleList.add(new Capsule("null", "null", "null", "null", 0, 0, type, details, 0));
}
mCapsuleAdapter = new CapsuleAdapter(CapsuleFragment.this.getContext(), mCapsuleList);
mRecyclerView.setAdapter(mCapsuleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
There is a lot of value in json but I just want to receive "type" and "detail". It says my request is null. So how can i parse this?

How i can parse in Json Object or Array? Where is error on my code?

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));

Retrieve a list of json objects using volley

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);

How to post json object using retrofit

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

Android volley : how to check json type before parsing it

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.

Categories

Resources