JSON response is changed as no of item changes - android

my JSON Response from server is changes as user input , suppose on server when user added one item then i got response as JSONObject but when items is more than 1 Then response is in JSONArray form.
Now how to handle these response so that my application is not killed , need to use checkpoint ?
in case of two item ..
"items":{
"item":[
{
"item_id":"49623",
"type":"Products",
"name":"desktop app",
"description":"",
"unit_cost":"162.45",
"quantity":"1.00",
"discount":"0.00",
"discount_type":"Percent",
"tax1_percent":"0.00",
"tax2_percent":"0.00"
},
{
"item_id":"52851",
"type":"Products",
"name":"",
"description":"",
"unit_cost":"5,290.50",
"quantity":"1.00",
"discount":"0.00",
"discount_type":"Percent",
"tax1_name":{
},
"tax1_percent":"0.00",
"tax1_type":{
},
"tax2_name":{
},
"tax2_percent":"0.00",
"tax2_type":{
}
}
]
}
In case of single item
"items":{
"item":{
"item_id":"49623",
"type":"Products",
"name":"desktop app",
"description":"this is the software for your desktop system sequerty",
"unit_cost":"162.45",
"quantity":"1.00",
"discount":"0.00",
"discount_type":"Percent",
"tax1_name":{
},
"tax1_percent":"0.00",
"tax1_type":{
},
"tax2_name":{
},
"tax2_percent":"0.00",
"tax2_type":{
}
}
}
}

I think you could use optJSONArray("") or optJSONObject(""), which doesn't throw any exception, but returns null if the object isn't in the right type.
JSONObject items = myJSON.getJSONObject("items");
Object item;
if (items.optJSONArray("item") != null){
//The result isn't null so it is a JSONArray
item = items.optJSONArray("item");
}
else
{
//The result is null so it isn't a JSONArray
item = items.optJSONObject("item");
}
Then, you'll just have to use your Object as you wish, using "instanceof":
if (item instanceof JSONObject){
// The object is a JSONObject
[... Your code ...]
}
else
{
// The object is a JSONArray
[... Your code ...]
}

Related

for not running in onPostExecute

I am getting some info from the server and the for used in onPostExecute was supposed to store the data into 2 different arrays. The server's response it's alright, it gets to the app, it is recognized as a JSON object, but when it comes to transforming it to a JSONArray to get the elements it just gets over that part of the code, as it wouldn't be written. So, after the JSONArray departamenteArray = obj.getJSONArray("departamente"); line, it just goes over the rest of it without making any changes.
.java code:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
JSONArray departamenteArray = obj.getJSONArray("departamente");
for (int i = 0; i < departamenteArray.length(); i++) {
JSONObject dep = departamenteArray.getJSONObject(i);
// Verificare daca s-au primit probleme trimise de server
if (!dep.isNull("Departament")) {
String departament = SchimbareDiactritice(dep.getString("Departament")).replace("&","");
String id_departament= dep.getString("id_departament");
id_departamente.add(id_departament);
departamente.add(departament);
}
}
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
layout_validare.setVisibility(GONE);
linearLayout_obs_redirectionare.setVisibility(View.VISIBLE);
}
JSON response from the server :
{
"error": false,
"message": "Alerte reimprospatate",
"departamente": [{
"Departament": "Parcări",
"id_departament": 2
}, {
"Departament": "Trafic rutier și iluminat public",
"id_departament": 3
}, {
"Departament": "Salubritate și vandalism",
"id_departament": 4
}, {
"Departament": "Altele",
"id_departament": 5
}]
}
.php code on the server side:
if($stmt->num_rows > 0){
$stmt->bind_result($departament, $id_departament);
while($stmt->fetch()) {
$departamente[] = array (
"Departament"=>$departament,
"id_departament"=>$id_departament
);
$response['error'] = false;
$response['message'] = 'Alerte reimprospatate';
$response['departamente']= $departamente;
It seems that after a restart of the Android Studio it works. It must have been only a bug. The code shown above it's working properly.

How to populate an Android Spinner from a Json file URL

I have the following Json Format file:
[
{
"id": 1,
"game_genre": "RPG"
},
{
"id": 2,
"game_genre": "Action"
}
]
on a remote location:
http://127.0.0.1:8000/genre/?format=json (Ddjango Format)
and i want to populate an Android spinner with the respective id so that can perform a search later depending on the id of the genre. I read the other threads but since i am new into android i don't know where to start.
i have the Json parser file included in my project
Here is the code for JSON parsing :
String json = "[ { id: 1, game_genre: RPG }, { id: 2, game_genre : Action }]";
if (json != null) {
try {
ArrayList<String> game = new ArrayList();
ArrayList<Integer> id = new ArrayList();
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
game.add(jsonObject1.getString("game_genre"));
id.add(Integer.parseInt(jsonObject1.getString("id")));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(Activity.this, "Cannot get json from server", Toast.LENGTH_SHORT).show();
}
Then you just need to pass the game ArrayList to the Spinner adapter.
How can I add items to a spinner in Android?

How do you return the contents of the following nested JSON Array in Android?

W/O using Hashmap or GSON. This is my first time parsing a nested array. I know how to parse a single array and JSON objects. I've looked at several threads on here and I'm basing my code on this one:
How to parse this nested JSON array in android
I'm parsing the following JSON data(pasted from Postman) from the following url. JSON structure pasted below.
https://api.tfl.gov.uk/Line/victoria/Route/Sequence/inbound?serviceTypes=Regular,Night
I want to return a list of 16 subway stations in sequential order; return "id":940GDCOELW" or "naptanId:940DFDDKLJ09" and "name":"Warren Street Underground Station" for all the stations. They are stored in both "stations"(non-sequential) and "stopPointSequences" arrays and also in "orderedLineRoutes". I started parsing "stopPointSequences", but I'm not sure how to add the data to the ArrayList. Error indicated above the code. Or, would it be easier to parse "orderedLineRoutes"? But is it possible to parse it by matching the name to the id? I'm not sure if every "name" is included in the array. The first part of "stopPointSequence" array pasted below. Thank you in advance.
{
"$type": "Tfl.Api.Presentation.Entities.RouteSequence, Tfl.Api.Presentation.Entities",
"lineId": "victoria",
"lineName": "Victoria",
"direction": "inbound",
"isOutboundOnly": false,
"mode": "tube",
"lineStrings":[..];
"stations":[..];
"stopPointSequences":[
{
"$type": "Tfl.Api.Presentation.Entities.StopPointSequence, Tfl.Api.Presentation.Entities",
"lineId": "victoria",
"lineName": "Victoria",
"direction": "inbound",
"branchId": 0,
"nextBranchIds": [],
"prevBranchIds": [],
"stopPoint": [
{
"$type": "Tfl.Api.Presentation.Entities.MatchedStop, Tfl.Api.Presentation.Entities",
"parentId": "HUBWHC",
"stationId": "940GZZLUWWL",
"icsId": "1000249",
"topMostParentId": "HUBWHC",
"modes": [
"tube"
],
"stopType": "NaptanMetroStation",
"zone": "3",
"hasDisruption": true,
"lines": [{..}],
"status": true,
"id": "940GZZLUWWL",
"name": "Walthamstow Central Underground Station",
"lat": 51.582965,
"lon": -0.019885
},
],
"orderedLineRoutes": [
{
"$type": "Tfl.Api.Presentation.Entities.OrderedRoute, Tfl.Api.Presentation.Entities",
"name": "Walthamstow Central ↔ Brixton ",
"naptanIds": [
"940GZZLUWWL",
"940GZZLUBLR",
"940GZZLUTMH",
"940GZZLUSVS",
"940GZZLUFPK",
"940GZZLUHAI",
"940GZZLUKSX",
"940GZZLUEUS",
"940GZZLUWRR",
"940GZZLUOXC",
"940GZZLUGPK",
"940GZZLUVIC",
"940GZZLUPCO",
"940GZZLUVXL",
"940GZZLUSKW",
"940GZZLUBXN"
],
"serviceType": "Night"
},
{
"$type": "Tfl.Api.Presentation.Entities.OrderedRoute, Tfl.Api.Presentation.Entities",
"name": "Walthamstow Central ↔ Brixton ",
"naptanIds": [
"940GZZLUWWL",
"940GZZLUBLR",
"940GZZLUTMH",
"940GZZLUSVS",
"940GZZLUFPK",
"940GZZLUHAI",
"940GZZLUKSX",
"940GZZLUEUS",
"940GZZLUWRR",
"940GZZLUOXC",
"940GZZLUGPK",
"940GZZLUVIC",
"940GZZLUPCO",
"940GZZLUVXL",
"940GZZLUSKW",
"940GZZLUBXN"
],
"serviceType": "Regular" }]
}},
JSONUTILS class:
public static ArrayList<Stations> extractFeatureFromStationJson(String stationJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(stationJSON)) {
return null;
}
ArrayList<Stations> stations = new ArrayList<>();
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(stationJSON);
JSONArray stopPointSequenceArrayList = baseJsonResponse.getJSONArray("stopPointSequences");
if (stopPointSequenceArrayList != null) {
for (int i = 0; i < stopPointSequenceArrayList.length(); i++) {
JSONObject elem = stopPointSequenceArrayList.getJSONObject(i);
if (elem != null) {
JSONArray stopPointArrayList = elem.getJSONArray("stopPoint");
if (stopPointArrayList != null) {
for (int j = 0; j < stopPointArrayList.length(); j++) ;
JSONObject innerElem = stopPointArrayList.getJSONObject(i);
if (innerElem != null) {
String idStation = "";
if (innerElem.has("id")) {
idStation = innerElem.optString(KEY_STATION_ID);
}
String nameStation = "";
if (innerElem.has("name")) {
nameStation = innerElem.optString(KEY_STATION_NAME);
}
//Error stopPointSequenceArrayList.add(stopPointArrayList);
}
}
}
}
}
//Error
Stations station = new Stations(idStation, nameStation);
stations.add(station);
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing stations JSON results", e);
}
// Return the list of stations
return stations;
}
There is couple errors inside your code so this should work now. You can now extract id and name values:
try {
ArrayList<Stations> stations = new ArrayList<>();
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(stationJSON);
JSONArray stopPointSequenceArrayList = baseJsonResponse.getJSONArray("stopPointSequences");
if (stopPointSequenceArrayList != null) {
for (int i = 0; i < stopPointSequenceArrayList.length(); i++) {
JSONObject elem = stopPointSequenceArrayList.getJSONObject(i);
if (elem != null) {
JSONArray stopPointArrayList = elem.getJSONArray("stopPoint");
if (stopPointArrayList != null) {
for (int j = 0; j < stopPointArrayList.length(); j++) {
JSONObject innerElem = stopPointArrayList.getJSONObject(i);
if (innerElem != null) {
String id = innerElem.getString("id");
String name = innerElem.getString("name");
Log.d("Element", name);
Log.d("Element", id);
Stations station = new Stations(id, name);
stations.add(station);
}
}
}
}
}
return stations;
}
return null; //something went wrong
} catch (Exception e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing stations JSON results", e);
return null; // something went wrong exception is thrown
}

Android - How to Represent JSON Information from URL through GSON

I have been attempting to retrieve information from an online JSON Source using a URL. I initially got the information parsed to a TextView in Android, however I got ALL Information from the JSON. Below is a screenshot of what I am referring to.
Text View Showing All Data In Json
Essentially, What I want is to just show the Location, so in the above example, Oslo, in Norway in one Textview, then in another show the Current Moon Phase for that location, so - using the above example again, Waxing Crescent.
This is the JSON I am using.
{
"version": 2,
"locations": [{
"id": "187",
"geo": {
"name": "Oslo",
"country": {
"id": "no",
"name": "Norway"
},
"latitude": 59.913,
"longitude": 10.740
},
"astronomy": {
"objects": [{
"name": "moon",
"days": [{
"date": "2018-09-13",
"events": [],
"moonphase": "waxingcrescent"
}]
}]
}
}]
}
To parse the JSON to the Textview showing all the data I used the following.
JSONObject jo = new JSONObject(data);
JSONArray locations = jo.getJSONArray("locations");
for (int i = 0; i < locations.length(); ++i) {
JSONObject loc = locations.getJSONObject(0);
JSONObject geo = loc.getJSONObject("geo");
JSONObject country = geo.getJSONObject("country");
JSONObject astronomy = loc.getJSONObject("astronomy");
JSONObject objects = astronomy.getJSONArray("objects").getJSONObject(0);
JSONObject day = objects.getJSONArray("days").getJSONObject(0);
StringBuilder result = new StringBuilder();
String singleParsed = "Moon: "+ astronomy.getString("moonphase");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.fetcheddata.setText(this.data);
}
NOTE: A String is created in the For Loop, Called "Single Parsed", This is what I want to put on the screen, however - once I call that variable, nothing shows on the screen. It only shows when using:
MainActivity.fetcheddata.setText(this.data);
But Not with the following, I do actually receive an error saying "Cannot Resolve Symbol, singleParsed as well.
MainActivity.fetcheddata.setText(this.singleParsed);
After some research and previous questions on Stack, I believe GSON is the way to go to do what I wish, however I have no idea where to start, or how to do the task using GSON.
All help is appreciated.
JSON Information from URL through GSON
Simple answer - Look at using Retrofit, and find a tutorial on it, as well as Gson
However
You don't need Gson to fix your problem, and I suggest fixing the problem at hand rather than going down an unnecessary path.
First, singleParsed is a local variable within a loop. Therefore, this.singleParsed doesn't exist. Or if it does, you never set it.
Secondly, let's assume you only have one location, so you don't need a loop. Similar to how you accessed the other JSON arrays, just get the first array item.
Finally, you'll need to understand how AsyncTask works, but my general recommended solution is at How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
But, for this purpose, here is a simple example with AsyncTask<String, Void, String>
// protected String doInBackground(String... url) { // I assume you have this ??
// String data = parseJsonFrom(url[0]);
String singleParsed = "(none)";
try {
JSONObject jo = new JSONObject(data);
JSONObject firstLocationAstronomy = jo
.getJSONArray("locations").getJSONObject(0)
.getJSONObject("astronomy");
JSONObject firstDay = firstLocationAstronomy
.getJSONArray("objects").getJSONObject(0)
.getJSONArray("days").getJSONObject(0);
singleParsed = firstDay.getString("moonphase");
} catch (Exception e) { // TODO: catch a JSONParseException
}
return singleParsed; // This is returned to onPostExecute, don't store a variable elsewhere
}
Then in the MainActivity, wherever you make this task, and set the text
new MoonPhaseTask() {
#Override
protected void onPostExecute(String moonPhase) {
MainActivity.this.textView.setText("Phase: " + moonPhase);
}
}.execute("some url");
What I want is to just show the Location, so in the above example, Oslo, in Norway in one Textview, then in another show the Current Moon Phase for that location
You can change the AsyncTask to return you the entire JSONObject to the onPostExecute, and parse the JSON there if you really wanted. Just the networking pieces need to be off the UI thread... parsing is not computationally expensive.

How to parse data from pubnub history callback resonse?

History callback is shown below,I need to parse Object response (message) which response is given below for reference.Object message - params which produce nested array without any keyword and nested object with keyword as message.
pubnub.history(request_id, true, 100, new Callback() {
#Override
public void successCallback(String channel, Object message) {
super.successCallback(channel, message);
Log.e(TAG, "successCallback: History Messages" + message);
}
#Override
public void errorCallback(String channel, PubnubError error) {
super.errorCallback(channel, error);
Log.e(TAG, "successCallback: History Messages error" + error);
}
});
Here is my Object response message.
Response:-
[ //array 1
[ // array 2
{ //obj 1
"message":{
"message":"Hai",
"timestamp":1507105493379,
"type":"SENT",
"userId":137
},
"timetoken":15071054937865507
},
{ //object 2
"message":{
"message":"How are you ?",
"timestamp":1507105503320,
"type":"SENT",
"userId":137
},
"timetoken":15071055037143632
},
{ //object 3
"message":{
"message":"Fyn",
"timestamp":1507105505628,
"type":"SENT",
"userId":137
},
"timetoken":15071055060355900
}
], //array 1 end
15071054937865507,
15071055060355900
]
//array 2 end
How to parse this response.
You can parse your JSON using below code
Call parseJson() inside your successCallback method and pass message.toString() to parse method like this:
public void successCallback(String channel, Object message) {
super.successCallback(channel, message);
Log.e(TAG, "successCallback: History Messages" + message);
parseJson(message.toString());
}
JsonParse method:
private void parseJson(String jsonStr) {
try{
JSONArray jsonArray = new JSONArray(jsonStr);
JSONArray innerJsonArray = jsonArray.getJSONArray(0);
for(int i = 0; i < innerJsonArray.length(); i++) {
JSONObject jsonObject = innerJsonArray.getJSONObject(i);
JSONObject jsonObjectMessage = jsonObject.getJSONObject("message");
String msg = jsonObjectMessage.getString("message");
//TODO you can get all other fields
}
}catch (JSONException e){
e.printStackTrace();
}
}
first of all this is not a valid JSON, maybe this is way you are having trouble parsing it.
when you'll get a valid json (and you can check if it is a valid json in here https://jsonlint.com/) , you will need to first cast it from a string as a json object and then get every child and every child of a child ans so on until u get the whole object.
you should use some json parser like this one:http://json.parser.online.fr/ to help you understand what object is a child of what
good luck

Categories

Resources