for not running in onPostExecute - android

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.

Related

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

java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 error

Can anyone help me? I debugg app many more time but I can not found what exact issue going in my android app. In my android app, My cases are describe below.
cases 1: Insert data into database It is perfectly worked fine.
case 2: That data display in to recycler view ok. It will display fine.
It will work with only single user login. When another user will login in to app and try to add data then It will get this exception. Or when I will refresh first user login view at that time it have same exception.
Or when I remove second user from database then I refresh first login user view at that time it will work perfectly . Now what to do? Please any one help me out of this issue. I attached screen shot of my error log please refer it.
Retrive data.java
private void makeJsonArrayRequest(final String email) {
String cancel_req_tag = "list";
JsonArrayRequest req = new JsonArrayRequest(URL_FOR_SELECT,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("OnResponse", response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
ListMobileModal objMobileModal = new ListMobileModal();
if (jsonObject.getString("email").equals(email)) {
objMobileModal.email = jsonObject.getString("email");
if (!jsonObject.isNull("name")) {
objMobileModal.lname = jsonObject.getString("name"); //here we can fetch webservice field
}
if (!jsonObject.isNull("title")) {
objMobileModal.title = jsonObject.getString("title"); //here we can fetch webservice field
}
if (!jsonObject.isNull("eimage")) {
objMobileModal.eimage = jsonObject.getString("eimage");
}
if (!jsonObject.isNull("eid")) {
objMobileModal.eid = jsonObject.getString("eid");
}
if (!jsonObject.isNull("ename")) {
objMobileModal.ename = jsonObject.getString("ename");
}
if (!jsonObject.isNull("edescription")) {
objMobileModal.edescription = jsonObject.getString("edescription");
}
if (!jsonObject.isNull("evlocation")) {
objMobileModal.elocation = jsonObject.getString("elocation");
}
lstListMobile.add(i, objMobileModal);
}
}
objMobileAdapter = new ListMobileAdapter(SavedPhoneBottomActivity.this, lstListMobile);
objEmptyRecyclerViewAdapter = new EmptyRecyclerViewAdapter("No selected list!");
if (lstListMobile == null || lstListMobile.size() == 0) {
rvDisplay.setAdapter(objEmptyRecyclerViewAdapter);
rvDisplay.setVisibility(View.VISIBLE);
} else {
rvDisplay.setAdapter(objMobileAdapter);
rvDisplay.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SavedPhoneBottomActivity.this,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("VolleyError", "Error: " + error.getMessage());
Toast.makeText(SavedPhoneBottomActivity.this,
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(req, cancel_req_tag);
}
List exception error
try to replace lstListMobile.add(i, objMobileModal); with lstListMobile.add(objMobileModal);
when if (jsonObject.getString("email").equals(email)) condition fails 0 index is not added for that user.
you will get ArrayIndexOutOfBound error on lstListMobile.add(1, objMobileModal); if 0 index is not present
You're inserting lstListMobile.add(i, objMobileModal); maybe you can just add lstListMobile.add(objMobileModal);? Probably whats happening is that when i==0 is does not pass the test if (jsonObject.getString("email").equals(email)) {. So it does not add and the size remains 0. When i==1 it breaks when inserting.
Please check first array is not null
if (response.length > 0) {
// do something
}
else{
//empty array
}

Android cannot check json success and error response

I am struggling with one situation. I am returning some json data from PHP server my code is as follows,
PHP API code:
if ($user != false) {
$result = mysql_query("SELECT stock_name,stock_location FROM btrack_stock WHERE user_id= '$user_id'") or die(mysql_error());
$rows = array();
$count = mysql_num_rows($result);
if($count > 0){
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('usertransaction' => $rows));
}else{
$response["error"] = 1;
$response["error_msg"] = "You do not have any transaction so far. ";
echo json_encode($response);
}
}
On android side, I use a class that extends AsyncTask and on my onPostExecute I use:
protected void onPostExecute(JSONObject json) {
try {
if(json.getString("error_msg") != null){
String err = json.getString("error_msg");
stock_error.setText(err);
stock_error.setVisibility(View.VISIBLE);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well actually, I wanted to display error message that is returned from PHP server and display all the data if I got success message (here I am showing a Toast).
My question is how can we display error message if json returns error message and display success if json does not return error message.
* My code works fine if I get error_msg as json response but if I return other data the app stuck in process dialog with a warning in LogCat as " There is no value for error_msg".
Thanks in Advance.
Try this:
if json.isNull("error_msg") {
do_something()
}
else {
json.getString("error_msg");
do_something_else()
}

Categories

Resources