JSON object not displaying values after fetching from database - java

I am fetching data from database in android and i can see data fetching from databse in JSON format using POSTMAN but when i am trying to display it in my android application, its not displaying any value.
Values from POSTMAN:
{
"result": [
{
"Date": "18-3-2016",
"Events": "Local Holiday"
},
{
"Date": "23-3-2016",
"Events": "Monthly Fees"
},
{
"Date": "15-4-2016",
"Events": "Monthly Fees"
},
{
"Date": "23-4-2016",
"Events": "Annual Day"
},
{
"Date": "30-4-2016",
"Events": "session end"
},
{
"Date": "9-4-2016",
"Events": "Parent Teacher Meeting"
}
]
}
I am following some tutorials and Code using:
private void getData() {
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = config_events.DATA_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(events.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String date = "";
String comment="";
//String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config_events.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
date = collegeData.getString(config_events.KEY_NAME);
comment = collegeData.getString(config_events.KEY_ADDRESS);
//vc = collegeData.getString(config_events.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Date:"+date + "Comment:"+ comment);

Assuming that you have tried to debug it, this could be the problem of user-permissions in Android manifest. Make sure that you have following permissions in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

if you really getting the response through the API you might want to check the JSON parsing code this is something I wrote while assuming the response in the question
private void showJSON(String response){
try{
Log.d(TAG, "showJSON: \n"+response);// print here to check you are getting the right response
JSONObject response_JsonObject = new JSONObject(response);
JSONArray result_JsonArray = response_JsonObject.getJSONArray("result");
ArrayList<Event> events = new ArrayList<>();
for (int i = 0; i < result_JsonArray.length(); i++) {
Event single_Event = new Event();
single_Event.setDate(result_JsonArray.getJSONObject(i).getString("Date"));
single_Event.setEvent(result_JsonArray.getJSONObject(i).getString("Events"));
events.add(single_Event);
}
Log.d(TAG, "showJSON: Event list size: "+events.size()); // check number of elements
}catch (Exception e){
e.printStackTrace();
}
}
private class Event{
private String date;
private String event;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
}

Related

JSONObject cannot be converted to String

I saw this questions a bunch of times here in Stack, but had no luck. The thing is, I'm using this API for validate my CNPJ field, if I have a connection, the response would be the field "nome" and populate my textview field.
So far so good, the JSON is valid (already passed in jsonformatter) but I can't the object through JSONArray and when I manage to find it by JSONObject it tells me that can't be converted to String.
valide.setOnClickListener(view1 -> {
//String PJ = cnpj.getText().toString();
String PJ = "06990590000123";
String url = "https://www.receitaws.com.br/v1/cnpj/" + PJ;
jsonParse(url);
});
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
String json;
#Override
public void onResponse(JSONObject response) {
try {
json = response.getJSONObject("nome").toString();
razao.append(json);
razao.setText(json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Invalid ! ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError erro) {
erro.printStackTrace();
}
});
mQueue.add(request); //Volley.newRequestQueue
}
JSON
{ "atividade_principal": [ { "text": "Portais, provedores de conteúdo e outros serviços de informação na internet", "code": "63.19-4-00" } ],
"data_situacao": "01/09/2004",
"complemento": "ANDAR 17A20 TSUL 2 17A20", "tipo": "MATRIZ",
**"nome": "GOOGLE BRASIL INTERNET LTDA.", //Need this field**
"uf": "SP",
"telefone": "(11) 2395-8400",
"email": "googlebrasil#google.com",
LOG
org.json.JSONException: Value GOOGLE BRASIL INTERNET LTDA. at nome of
type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:101)
URL USED
https://www.receitaws.com.br/v1/cnpj/06990590000123
Can someone help me with this problem, please ? Thank you !
In your JSON the nome is of type String. So rather than getJSONObject use getString method from JSONObject class. So your code should be like below:
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
String json;
#Override
public void onResponse(JSONObject response) {
try {
json = response.getString("nome"); // Here is the change
razao.append(json);
razao.setText(json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Invalid ! ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError erro) {
erro.printStackTrace();
}
});
mQueue.add(request); //Volley.newRequestQueue
}
Try this:
First construct JsonObject and then get the string value of the key.
JSONObject jsonObject = new JSONObject(json);
String valueIWanted = jsonObject.getString("nome"))

How to iteratively store and retrieve JSONArray which contains nested JSON objects in couchbase (Android)

Trying to store a JSON array into Couchbase using this code in Android, put it is unsuccessful. Please help with how to successfully store it and also how to iteratively receive all data. Looked through the Couchbase documentation, but still stuck. Do i have to convert the JSON array to an object before i would be able to store and receive? Or what is the right way to handle such data from an API
private void storeLocalData() {
//COUCHBASE IMPLEMENTATION
// Create a manager
manager = null;
try {
manager = new Manager(new AndroidContext(getActivity()), Manager.DEFAULT_OPTIONS);
} catch (IOException e) {
e.printStackTrace();
}
// Create or open the database named 'saved_project_sample'
database = null;
try {
database = manager.getDatabase("saved_project_sample");
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
// Create a new document
document = database.createDocument();
try {
//Cast json String into JSON Array
JSONArray jsonArray= new JSONArray(json);
HashMap<String, Object> properties = new HashMap<>();
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject objJson = jsonArray.getJSONObject(k);
Object id = objJson.getString("id");
Object title = objJson.getString("title");
Object owner_id = objJson.getString("owner_id");
Object description = objJson.getString("description");
Object status = objJson.getString("status");
Object start_time = objJson.getString("start_time");
Object finish_time = objJson.getString("finish_time");
Object created = objJson.getString("created");
Object modified = objJson.getString("modified");
properties.put("id", id);
properties.put("title", title);
properties.put("owner_id", owner_id);
properties.put("description", description);
properties.put("status", status);
properties.put("start_time", start_time);
properties.put("finish_time", finish_time);
properties.put("created", created);
properties.put("modified", modified);
document.putProperties(properties);
Toast.makeText(getActivity(), "Successful Storage", Toast.LENGTH_SHORT).show();
}
} catch (CouchbaseLiteException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Unsuccessful", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Unsuccessful", Toast.LENGTH_SHORT).show();
}
}
This is my JSON Array
[
{
"id": "1",
"title": "New API",
"owner_id": "dsdssdsd445d",
"description": "Yh A Testin API",
"status": "unactiveAPI",
"start_time": "2017-08-01 14:25:22.060000",
"finish_time": "2017-08-01 14:25:22.060000",
"created": "2017-08-01 14:25:22.060000",
"modified": "2017-08-01 14:25:22.060000"
},
{
"id": "2",
"title": "New TW Projec API",
"owner_id": "dsdssdsd445d",
"description": "Testin API",
"status": "unactiveAPI",
"start_time": "2017-08-01 14:25:22.060000",
"finish_time": "2017-08-01 14:25:22.060000",
"created": "2017-08-01 14:25:22.060000",
"modified": "2017-08-01 14:25:22.060000"
},
{
"id": "3",
"title": "Projec API",
"owner_id": "dsdssdsd445d",
"description": "Testin",
"status": "unactiveAPI",
"start_time": "2017-08-01 14:25:22.060000",
"finish_time": "2017-08-01 14:25:22.060000",
"created": "2017-08-01 14:25:22.060000",
"modified": "2017-08-01 14:25:22.060000"
}
]
Use GSON and a class, then you do not need to manually get each variable.
public class UserDocument{
public int id;
public String title;
public String owner_id;
public String description;
public String status;
public Date start_time;
public Date finish_time;
public Date created;
public Date modified;
public UserDocument() {}; //Needs an empty constructor for reflection;
}
Now you have the class, then you can write
UserDocument[] userDocuments = new Gson().fromJson(json, UserDocument[].class);
for(UserDocument userDocument : userDocument){
HashMap<String, Object> properties = new HashMap<>();
properties.put("id", userDocument.id);
properties.put("title", userDocument.title);
properties.put("owner_id", userDocument.owner_id);
properties.put("description", userDocument.description);
properties.put("status", userDocument.status);
properties.put("start_time", userDocument.start_time);
properties.put("finish_time", userDocument.finish_time);
properties.put("created", userDocument.created);
properties.put("modified", userDocument.modified);
try {
document.putProperties(properties);
} catch (CouchbaseLiteException e) {
e.printStackTrace(); //This will tell you why it fails
}
}
Just define the type of the property, then GSON will check if the property can become that type
It is impossible to put multiple properties of a hashmap into a singular Couchbase doucment.
You create a new document everytime by
document = database.createDocument();
Or
document = database.getDocument(String documentId);
Before
document.putProperties(properties);
My code below now works properly without crashing
ProjectSummary[] projectSummaries = new Gson().fromJson(json, ProjectSummary[].class);
int project_number=1;
HashMap<String, Object> properties = new HashMap<>();
for (ProjectSummary projectSummary : projectSummaries) {
// Create a new document - Every Project-List Will Be Its Own Document
document = database.getDocument("Project-"+ project_number);
properties.put("id", projectSummary.id);
properties.put("title", projectSummary.title);
properties.put("owner_id", projectSummary.owner_id);
properties.put("description", projectSummary.description);
properties.put("status", projectSummary.status);
properties.put("start_time", projectSummary.start_time);
properties.put("finish_time", projectSummary.finish_time);
properties.put("created", projectSummary.created);
properties.put("modified", projectSummary.modified);
try {
document.putProperties(properties);
Toast.makeText(context, project_number+"- ID Saved", Toast.LENGTH_SHORT).show();
} catch (CouchbaseLiteException e) {
e.printStackTrace(); //This will tell you why it fails
Toast.makeText(context, "failure", Toast.LENGTH_SHORT).show();
}
//Increase Project Number
project_number++;
}
Toast.makeText(context, "Project Download Successful \n" , Toast.LENGTH_SHORT).show();
}
ProjectSummary Class for Hashmap Mapping
public class ProjectSummary {
public String id;
public String title;
public String owner_id;
public String description;
public String status;
public String start_time;
public String finish_time;
public String created;
public String modified;
public ProjectSummary() {
}

Get User online/offline state

I have chat app where i need to develop user online state and for this i am calling API in every 15 seconds on server, which will return all logged in users and their online state in 0(Offline) and 1(Online).
I need to show whether user is online or offline (leaves app not logged out) while chatting.I have 1 array list which shows when app is launch with all logged in user id and their details including their online state and i created second API which return users online state in JSON.I have following option to achieve users online state
Replace existing array list item:-I am getting User ID and their online state in JSON but i need to run loop in every 15 second which replace values in existing arraylist
Store JSON in someway where i can easily find user id and its state:- If i store JSON in array list i need to run loop to find ID and its state which i dont want to,So which is best way to store JSON so i can easily get user state by its User ID.
Here is how i am getting JSON
protected List<WrapperClass> doInBackground(Void... params) {
userSession=new UserSession(context,"Elaxer");
UserState_Update=new ArrayList<>();
String data = null;
try {
String ID=userSession.getUserID(); //Getting Value from shared pref
data = URLEncoder.encode("User_ID", "UTF-8") + "=" + URLEncoder.encode(ID, "UTF-8");
Log.d(TAG,"Login ID "+ ID);
Log.d(TAG,"DO IN BACKGROUND START ");
URL url=new URL(URL_Path_NearBy);
connection= (HttpURLConnection) url.openConnection();
Log.d(TAG,connection.toString());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
//For POST Only - Begin
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
os.close();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
Log.d(TAG,"GET INPUT STREAM AND PUUTING INTO READER");
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
Log.d(TAG,"JSON ARRAY START");
JSONObject parentArray=new JSONObject(completeJSON);
JSONArray jsonArray=parentArray.getJSONArray("uData");
String LastSeen;
int LoginStatus,User_ID;
int Rec_Online_Status;
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject childObject=jsonArray.getJSONObject(i);
LastSeen=childObject.getString("lastseen") ;
LoginStatus=childObject.getInt("login_status") ;
User_ID=childObject.getInt("User_ID");
String UseID= String.valueOf(User_ID);
Log.d(TAG,"JSON Values "+LastSeen+" "+LoginStatus+" "+User_ID);
WrapperClass wrapperClass=new WrapperClass(UseID,LoginStatus);
UserState_Update.add(wrapperClass);
}
return UserState_Update; //List<WrapperClass> UserState_Update
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
This is the response as JSON
{
"status": "SUCCESS",
"uData": [
{
"User_ID": "4",
"login_status": "1",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "1",
"login_status": "0",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "12",
"login_status": "1",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "33",
"login_status": "0",
"lastseen": "0000-00-00 00:00:00"
}
]
}
Is this right way to get user online state? (I know FCM is right way but FCM currently not ready on app server side)
UPDATE 2:-As code recommended by #XngPro i implement on doinBackground
Map<String,Online_Status_Wrapper.User> map=new HashMap<>();
Online_Status_Wrapper wrapper=gson.fromJson(completeJSON,Online_Status_Wrapper.class);
Log.d(TAG,"Wrapper Get Data value "+wrapper.getuData());
Log.d(TAG,"Wrapper Get Status value "+wrapper.getStatus());
for (Online_Status_Wrapper.User u: wrapper.getuData()){
map.put(u.getUser_ID(),u);
}
Log.d(TAG,"State of Other User users "+map.get(12).getLogin_status());//HERE I AM GETTING NullPointerException
return map;
I think you should use a Java serialization/deserialization library like Gson.
Hope to help you~
Example
private static void bar() {
String jsonStr = "{\"status\":\"SUCCESS\",\"uData\":[{\"User_ID\":\"4\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"1\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"12\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"33\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"}]}";
Gson gson = new Gson();
UserFoo userFoo = gson.fromJson(jsonStr, UserFoo.class);
Map<String, UserFoo.User> map = new HashMap<>();
for (UserFoo.User u : userFoo.getUData()) {
map.put(u.getUser_ID(), u);
}
System.out.println("userId: 12, loginState: " + map.get("12").getLogin_status());
}
public static class UserFoo {
/**
* status : SUCCESS
* uData : [{"User_ID":"4","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"1","login_status":"0","lastseen":"0000-00-00 00:00:00"},{"User_ID":"12","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"33","login_status":"0","lastseen":"0000-00-00 00:00:00"}]
*/
private String status;
private List<User> uData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<User> getUData() {
return uData;
}
public void setUData(List<User> uData) {
this.uData = uData;
}
public static class User {
/**
* User_ID : 4
* login_status : 1
* lastseen : 0000-00-00 00:00:00
*/
private String User_ID;
private String login_status;
private String lastseen;
public String getUser_ID() {
return User_ID;
}
public void setUser_ID(String User_ID) {
this.User_ID = User_ID;
}
public String getLogin_status() {
return login_status;
}
public void setLogin_status(String login_status) {
this.login_status = login_status;
}
public String getLastseen() {
return lastseen;
}
public void setLastseen(String lastseen) {
this.lastseen = lastseen;
}
}
}
public class Test {
public static void main(String[] args) {
bar();
}
private static void bar() {
String jsonStr = "{\"status\":\"SUCCESS\",\"uData\":[{\"User_ID\":\"4\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"1\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"12\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"33\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"}]}";
Gson gson = new Gson();
UserFoo userFoo = gson.fromJson(jsonStr, UserFoo.class);
Map<String, UserFoo.User> map = new HashMap<>();
for (UserFoo.User u : userFoo.getUData()) {
map.put(u.getUser_ID(), u);
}
System.out.println("userId: " + "12, loginState: " + map.get("12").getLogin_status());
}
public static class UserFoo {
/**
* status : SUCCESS
* uData : [{"User_ID":"4","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"1","login_status":"0","lastseen":"0000-00-00 00:00:00"},{"User_ID":"12","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"33","login_status":"0","lastseen":"0000-00-00 00:00:00"}]
*/
private String status;
private List<User> uData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<User> getUData() {
return uData;
}
public void setUData(List<User> uData) {
this.uData = uData;
}
public static class User {
/**
* User_ID : 4
* login_status : 1
* lastseen : 0000-00-00 00:00:00
*/
private String User_ID;
private String login_status;
private String lastseen;
public String getUser_ID() {
return User_ID;
}
public void setUser_ID(String User_ID) {
this.User_ID = User_ID;
}
public String getLogin_status() {
return login_status;
}
public void setLogin_status(String login_status) {
this.login_status = login_status;
}
public String getLastseen() {
return lastseen;
}
public void setLastseen(String lastseen) {
this.lastseen = lastseen;
}
}
}
}
Print

Try to POST JSONArray with volley

I got an jsonarray like:
[{
"color": -1,
"fill": false,
"id": 1,
"radius": 154.613,
"shapeText": "",
"shapeType": "circle",
"x1": 141.172,
"x2": 0,
"y1": 231.188,
"y2": 0
}, {
"color": -4569601,
"fill": false,
"id": 2,
"radius": 0,
"shapeText": "",
"shapeType": "rectangle",
"x1": 512.656,
"x2": 606.781,
"y1": 305.25,
"y2": 413.502
}]
and I try to do POST to the server but I fail :[
I already get an jsonarray frm the server and I also did POST but for jsonobject to the server but I couldn't make it POST Jsonarray :[, anyone got any idea how to do it?
public class JSONPostArrayRequest extends JsonRequest<JSONObject> {
JSONArray params;
public JSONPostArrayRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, JSONArray params) {
super(Method.POST, url, null, listener, errorListener);
this.params=params;
}
#Override
public byte[] getBody() {
if ( this.params != null && this.params.length() > 0) {
return encodeParameters( this.params, getParamsEncoding());
}
return null;
}
private byte[] encodeParameters(JSONArray params, String paramsEncoding) {
try {
return params.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
and my request done with this code:
public void updateDraw(ArrayList<Shape> shapes) {
JSONArray jsonArrayShapes = new JSONArray();
Log.d("START OF JSON ARRAY ", shapes.toString());
for (Shape shape : shapes) {
try {
JSONObject jsonObjectShape = new JSONObject();
jsonObjectShape.put("color", String.valueOf(shape.getColor()));
jsonObjectShape.put("fill", String.valueOf(shape.isFill()));
jsonObjectShape.put("radius", String.valueOf(shape.getRadius()));
jsonObjectShape.put("shapeText", String.valueOf(shape.getShapeText()));
jsonObjectShape.put("shapeType", String.valueOf(shape.getShapeType()));
jsonObjectShape.put("x1", String.valueOf(shape.getX1()));
jsonObjectShape.put("x2", String.valueOf(shape.getX2()));
jsonObjectShape.put("y1", String.valueOf(shape.getY1()));
jsonObjectShape.put("y2", String.valueOf(shape.getY2()));
jsonObjectShape.put("id", String.valueOf(shape.getId()));
jsonArrayShapes.put(jsonObjectShape);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSONARRAY = ", jsonArrayShapes.toString());
}
String shapeUrl = Main.GROUPS_URL + "/" + id + "/shape";
Log.d("URL = ", shapeUrl);
JSONPostArrayRequest jsonPostArrayRequest = new JSONPostArrayRequest(shapeUrl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("onErrorResponse ", error.toString());
}
}, jsonArrayShapes);
requestQueue.add(jsonPostArrayRequest);
}
You aren't passing your JSONArray into the request.
super(Method.POST, url, null, listener, errorListener);
That null parameter, as per the documentation
A JSONArray to post with the request. Null is allowed and indicates no parameters will be posted along with request.
Therefore, I don't see why you need to extend JsonRequest, or especially why you typed it with <JSONObject>.
The JsonArrayRequest class already exists, you just need to give the JSONArray object as the third parameter there.

Android and Json parsing

im trying to have my app connect to a rest API and pull the data from it. Ive so far pulled the data . but i dont know how to parse it. i believe thats what you do next.
here a snippet of my code that conencts to my rest API and gets the data . the error i get is JSONArray cannot be converted to JSONObject
if (status == 200) {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String responseString;
StringBuilder sb = new StringBuilder();
while ((responseString = reader.readLine()) != null) {
sb = sb.append(responseString);
}
String speciesListData = sb.toString();
species= SpeciesJson.fromJson(speciesListData);
Log.d(Constants.TAG, "speciesJSON: " + species);
return true;
}
this is were i tried to parse it , it was working fine up until here. hers is the line were i try to parse it
species= SpeciesJson.fromJson(speciesListData);
and this thats were it broke lol
public class SpeciesJson {
private String scientific_name, name,description;
public SpeciesJson (JSONObject species) throws JSONException {
this.scientific_name=species.optString("scientific_name");
this.name=species.optString("name");
this.description=species.optString("description");
}
public static ArrayList<SpeciesJson> fromJson(String photoData) throws JSONException {
ArrayList<SpeciesJson> speciesData = new ArrayList<>();
JSONObject data = new JSONObject(photoData);
JSONObject photos = data.optJSONObject("name");
JSONArray photoArray = photos.optJSONArray("name");
for (int i = 0; i < photoArray.length(); i++) {
JSONObject photo = (JSONObject) photoArray.get(i);
SpeciesJson currentPhoto = new SpeciesJson(photo);
speciesData.add(currentPhoto);
}
return speciesData;
}
so when i run it using the parsing method i made, it doesnt not work.
the sample of hte json data is below, im trying to show the scientific_name and name in a view
{
"id": 1,
"scientific_name": "Platanus racemosa",
"name": "California Sycamore",
"description": "typically in river areas, but planted all throughout L.A",
"type": 1
},
{
"id": 2,
"scientific_name": "Pyrus kawakamii",
"name": "Ornamental Pear",
"description": "native to Asia, commonly planted in L.A",
"type": 1
},
{
"id": 3,
"scientific_name": "Liquidambar styraciflua",
"name": "American Sweetgum",
"description": "native to SE U.S, planted all around L.A",
"type": 1
},
{
"id": 4,
"scientific_name": "Setophaga coronata",
"name": "Yellow-rumped Warbler",
"description": "native bird, spends the winter in L.A before migrating north during the summer to breed",
"type": 2
},
{
"id": 5,
"scientific_name": "Calypte anna",
"name": "Anna's Hummingbird",
"description": "native bird, does not migrate. Spends the year in L.A",
"type": 2
},
{
"id": 6,
"scientific_name": "Regulus calendula",
"name": "Ruby-crowned Kinglet",
"description": "native bird, spends the winter in L.A before migrating north during the summer to breed",
"type": 2
}
]
My Dear Friend Use googles GSON Library that's it.
And For Your Help I made this little bit easier.
Make This Class SpeciesJson.java
public class SpeciesJson {
private String scientific_name;
private String name;
private String description;
public SpeciesJson() {
}
public SpeciesJson(String scientific_name,String name,String description) {
this.scientific_name = scientific_name;
this.name = name;
this.description = description;
}
//And getter,setters
}
If SpeciesJson Is simple an object then use this
Gson gson = new Gson();
SpeciesJson species = gson.fromJson(responseString,SpeciesJson.class);
If SpeciesJson Is an ArrayList then use this (Its Looks Like Your Case So Check This As Your Json Response Consist Multiple SpeciesJson Objects)
Gson gson = new Gson();
ArrayList<SpeciesJson> species = new ArrayList<>();
SpeciesJson[] speciesarray = (SpeciesJson[]) gson.fromJson(responseString,SpeciesJson[].class);
Collections.addAll(species, speciesarray);
And If You wanna learn something more about Gson Library check this link
https://guides.codepath.com/android/Leveraging-the-Gson-Library
Well you can use GSON to parse the data and Volley to get the data.
//Create volley request
String url = String.format("SOME_URL", arrayOfObject);
RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// we got the response, now our job is to handle it
try {
ArrayList<SpeciesJson> speciesData = getDataFromJson(stream);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something happened, treat the error.
Log.e("Error", error.toString());
}
});
queue.add(request);
//If your JSON data is an Array
private static List<SpeciesJson> getDataFromJson(String json) {
Gson gson = new GsonBuilder().create();
List<SpeciesJson> result = new ArrayList<>();
try {
JSONObject posts=new JSONObject(json);
JSONArray dataArray=posts.getJSONArray("data");
for(int n = 0; n < dataArray.length(); n++)
{
JSONObject object = dataArray.getJSONObject(n);
result.add(gson.fromJson(object.toString(), SpeciesJson.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
And volley Service
public class VolleyService {
private static VolleyService instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private VolleyService(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url,bitmap);
}
});
}
public static VolleyService getInstance(Context context) {
if (instance == null) {
instance = new VolleyService(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Or you can use Retrofit library to parse it for you:
http://www.vogella.com/tutorials/Retrofit/article.html
https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit
You should use retrofit library with GsonConverterFactory. The best solution to manage network response.

Categories