AsyncTask doInBackground to return multiple strings - java

I'm trying to build a very basic weather app in android studio. I am using AsyncClass to return multiple strings.
As you can see in the code, I used a class named "Wrapper" that is used to store my strings so I can just return a class object and use it in the onPostExecute method of the AsyncTask. The problem I am facing is that when I test the app, all of the returned Strings somehow are undefined (the default for the Wrapper class). This means the strings are not being updated in the doInBackground method and I can't seem to figure out why!
My Activity
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
}
private class Wrapper
{
String Temperature = "UNDEFINED";
String city = "UNDEFINED";
String country = "UNDEFINED";
}
private class GetWeatherTask extends AsyncTask<String, Void, Wrapper> {
private TextView textView;
public GetWeatherTask(TextView textView) {
this.textView = textView;
}
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
String Temperature = "x";
String city = "y";
String country = "z";
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject cityobj = topLevel.getJSONObject("city");
Temperature = String.valueOf(main.getDouble("temp"));
city = cityobj.getString("name");
country = cityobj.getString("country");
w.Temperature= Temperature;
w.city= city;
w.country=country;
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}
#Override
protected void onPostExecute(Wrapper w) {
textView.setText("Current Temperature: " + w.Temperature + " C" + (char) 0x00B0
+"\n" + "Current Location: "+ w.country +"\n" + "City: "+ w.city );
}
}
}
UPDATE:
turned out that that I was using the wrong url in my code,I was using :
http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s
Instead I should've been using:
http://api.openweathermap.org/data/2.5/forecast?lat=%f&lon=%f&units=%s&appid=%s
-aka instead of weather I should've been using forcast

Your error starts here
JSONObject main = topLevel.getJSONObject("main");
Probably because the topLevel object has no "main" key.
{
"city":{ },
"cod":"200",
"message":0.1859,
"cnt":40,
"list":[ ]
}
Throw your JSON into here. https://jsonformatter.curiousconcept.com/
You'll notice that there are many, many "main" keys that are within the "list" element, but you have to parse those starting from getJSONArray("list").
Basically, something like this
String city = "undefined";
String country = "undefined";
List<Double> temperatures = new ArrayList<Double>();
try {
JSONObject object = new JSONObject(builder.toString());
JSONObject jCity = object.getJSONObject("city");
city = jCity.getString("name");
country = jCity.getString("country");
JSONArray weatherList = object.getJSONArray("list");
for (int i = 0; i < weatherList.length(); i++) {
JSONObject listObject = weatherList.getJSONObject(i);
double temp = listObject.getJSONObject("main").getDouble("temp");
temperatures.add(temp);
}
} catch (JSONException e) {
e.printStackTrace();
}
return new Wrapper(city, country, temperatures);

After studying your code, either your try block is failing, which is returning your object, but empty, or there is something wrong with your JSON parsing. If you could show us the JSON you are trying to parse that would be a great help.
That being said, the fact that it is still showing as "UNDEFINED" is because that is how you initialised it, and becuase (the JSON parse is likely failing), the object is being returned in an un-edited state.
EDIT:
You are parsing the JSON wrong. You are trying to find an object called "main" in the top directory, however the main object only exists inside of an array called list!
Please look here for a more easy to see and visual representation: http://prntscr.com/dlhlrk
You can use this site to help visualise your JSON and create an appropriate soluton based upon it. https://jsonformatter.curiousconcept.com/

Looking at the API you posted earlier (api.openweathermap.org) you are trying to access variables that don't exist. I suggest you have a look at what the API returns and try getting the variables one by one if you are getting a JSONException
EDIT:
What API you are using? In your initial post you said it was http://api.openweathermap.org/data/2.5/weather but in a comment above you said it was http://api.openweathermap.org/data/2.5/forecast.
If you're using the weather API (as initially stated) you can use the below:
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
Log.d("JSON", builder.toString());
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject sys = topLevel.getJSONObject("sys");
w.Temperature = String.valueOf(main.getDouble("temp"));
w.city = topLevel.getString("name");
w.country = sys.getString("country");
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}

Related

Getting a JSON Object from a JSON Array isn't working

I am trying to get JSON data from a JSON array which looks like this:
{
"common": [
{
"food_name": "eggs",
"serving_unit": "large",
"tag_name": "raw eggs",
"serving_qty": 1,
"common_type": null,
"tag_id": "775",
"photo": {
"thumb": "https://d2xdmhkmkbyw75.cloudfront.net/775_thumb.jpg"
},
"locale": "en_US"
},
Here's what I am using:
public class GetDietData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String calories = "UNDEFINED";
try {
URL urlForGetRequest = new URL("https://trackapi.nutritionix.com/v2/search/instant?query=egg");
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("x-app-key", "REMOVED");
connection.addRequestProperty("x-app-id", "REMOVED");
InputStream stream = new BufferedInputStream(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject();
JSONArray common = jsonRes.getJSONArray("common");
for (int i=0; i<common.length(); i++)
{
JSONObject jsonObj = common.getJSONObject(i);
calories = jsonObj.getString("food_name");
}
connection.disconnect();
} catch (IOException | JSONException e) {
editText=(findViewById(R.id.editTextDiet));
e.printStackTrace();
}
return calories;
}
#Override
protected void onPostExecute(String calories) {
if (calories == "UNDEFINED") {
Toast.makeText(Diet.this, "Food not found", Toast.LENGTH_LONG).show();
} else {
editText=(findViewById(R.id.editTextDiet));
editText.setText(calories);
}
}
}
I have the following problem:
W/System.err: org.json.JSONException: No value for common
at org.json.JSONObject.get(JSONObject.java:392)
So the problem seems to be that the "common" array has no value, hence it cannot find it's length? I'm unsure as to why it cannot see the "common" array as i have looked at numerous other questions about getting Objects from Arrays and I have replicated the code identically each time but with the same result. If I use solely a JSONObject and ignore the full array I can see in the stacktrace that it is attempting to download the whole array into that object which means it's definitely not something wrong with the GET request or the API keys.
Thanks.
the error you are getting is because you aren't passing the String response to jsonObject so it can't find any thing in an empty object
the fix is
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject(inputString); \\this is the fix
JSONArray common = jsonRes.getJSONArray("common");

OpenWeatherMap API Java

I am working on a project where i am creating a java app for watering plants.The idea to get weather information from online and based on that output should be if we plants require water or not.For weather information,i found an API OpenWeatherMap and i tried to implement it using educational video from YouTube.I don't have past experience with API's. The video i am using is "https://www.youtube.com/watch?v=og5h5ppwXgU" .I tried to implement my program the same way that guy did,but i am not getting any output.It just prints what's in the print statements ,not the actual data.
public static Map<String,Object> jsonToMap(String str){
Map<String,Object> map = new Gson().fromJson(str,new
TypeToken<HashMap<String,Object>> () {}.getType());
return map;
}
public static void main(String[] args) {
String API_KEY = "16 digit Private Key";
String LOCATION = "Los Angeles,CA";
String urlString = "http://api.openweathermap.org/data/2.5/weather?
q=" + LOCATION + "&appid=" + API_KEY + "&units =imperial";
try{
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader (conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null){
result.append(line);
}
rd.close();
System.out.println(result);
Map<String, Object > respMap = jsonToMap (result.toString());
Map<String, Object > mainMap = jsonToMap (respMap.get("main").toString());
Map<String, Object > windMap = jsonToMap (respMap.get("wind").toString());
System.out.println("Current Temperature: " + mainMap.get("temp") );
System.out.println("Current Humidity: " + mainMap.get("humidity") );
System.out.println("Wind Speed: " + windMap.get("speed") );
System.out.println("Wind Angle: " + windMap.get("deg") );
}catch (IOException e){
System.out.println(e.getMessage());
}
}
I received errors that gson library doesn't exist ,but after i cretaed my own library in net beans with javadoc,class path and soureces,the problem got resolved ,so i think that correct.Also the API key for openweathermap is also valid.I am just not able to get the code to get online information.
Output :
http://api.openweathermap.org/data/2.5/weatherq=Los Angeles,CA&appid="16 digit Private Key"&units =imperial
Expected Output : Current weather information of LA
Implementation of OpenWeatherMapApi with given latitude and longitude. For Network request Retrofit & Jsonschema2pojo to create model.
Hope this will help.
public void getWeatherDetails(double latitude, double longitude) {
String url = "http://api.openweathermap.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url) //This is the only mandatory call on Builder object.
.addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
.build();
WeatherApiService weatherApiService = retrofit.create(WeatherApiService.class);
weatherApiService.requestWeather(String.valueOf(latitude), String.valueOf(longitude), "metric", "10").enqueue(new UpasargaCallback<WeatherModel>() {
#Override
public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
if (getView() != null) {
getView().onWeatherApiSuccess(response.body());
}
}
}
}
#Override
public void onFailure(Call<WeatherModel> call, Throwable t) {
if (getView() != null) {
getView().onWeatherApiFailure(String.valueOf(t.getMessage()));
}
}
});
}
WeatherApiService
public interface WeatherApiService {
#Headers("x-api-key: " + AppConstants.WEATHER_API_KEY)
#GET("data/2.5/forecast")
Call<WeatherModel> requestWeather(#Query("lat") String lat,#Query("lon") String lon,#Query("units") String units,#Query("cnt") String count);
}
See WeatherModel.java
I tested the API with your app key in the browser. It was successful. Maybe you should encode your URL. It has a blank space which is a special character.

org.json.JSONException: JSONObject["status"] is not a JSONObject

I am now currently using a weather API from http://wiki.swarma.net/index.php?title=%E5%BD%A9%E4%BA%91%E5%A4%A9%E6%B0%94API/v2 and wished to convert the JSONObject into printable Strings. However, when I am working on the following code, two errors occurred:
public class getApi {
private static final String WEATHER_MAP_URL = "https://api.caiyunapp.com/v2/TAkhjf8d1nlSlspN/121.6544,25.1552/realtime.json";
private static final String WEATHER_TEST_API = "TAkhjf8d1nlSlspN";
public static JSONObject getWeatherJson() {
try {
URL url = new URL( WEATHER_MAP_URL );
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty( "x-api-key", WEATHER_TEST_API );
BufferedReader reader = new BufferedReader(
new InputStreamReader( connection.getInputStream()) );
StringBuffer json = new StringBuffer( 1024 );
String tmp;
while( (tmp = reader.readLine()) != null )
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject( json.toString() );
if(data.getJSONObject("status").toString() != "ok" ) {
return null;
}
return data;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
public static void main( String[] args ) {
JSONObject WeatherJson = getWeatherJson();
try {
JSONArray details = WeatherJson.getJSONObject("result").getJSONObject("hourly").
getJSONArray("skycon");
System.out.println(details.getJSONObject(0).getJSONObject("value").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The JSONObject structure, which is also shown in the link above, is like this:
{
"status":"ok",
"lang":"zh_CN",
"server_time":1443418212,
"tzshift":28800,
"location":[
25.1552, //latitude
121.6544 //longitude
],
"unit":"metric",
"result":{
"status":"ok",
"hourly":{
"status":"ok",
"skycon":[
{
"value":"Rain",
"datetime":"2015-09-28 13:00"
},
{
...
}]
}
}
}
The error occurred:
org.json.JSONException: JSONObject["status"] is not a JSONObject.
at org.json.JSONObject.getJSONObject(JSONObject.java:557)
at getApi.getWeatherJson(getApi.java:34)
at getApi.main(getApi.java:45)
Exception in thread "main" java.lang.NullPointerException
at getApi.main(getApi.java:47)
I have looked at similar posts on the topic is not a JSONObject Exception but found that none of them can help me. I suspect that something is wrong with requesting the data, so actually, getWeatherJson() returns a null object and results in the NullPointerException and JSONObjectException.
Can anyone help me with the code?
According to the getJSONObject() Javadoc, this method will throw an exception if the returned object isn't a true JSON object, which it isn't because "status" is a string. As such, try using data.getString("status").
The status field in the JSON document you have posted is not an object. In JSON, objects are enclosed in with {} brackets. The result node however, is a nested object which holds the status key/value pair. Try the following:
JSONObject data = new JSONObject(json.toString());
if(data.getJSONObject("result").get("status").toString() != "ok" ) {
return null;
}

Java code gets not executed

I developing android app and now I have problem. Below is a part of my code, and it keeps skipping the "for" part. When I put a breakpoint inside for statement, it stops at the point, and executes the lines very well and makes an output that I want. When I just 'run' app, it skips that part so "String locations" value doesn't change. I googled and some say it's thread-related problem. So I put synchroinzed on the method, still not working. Any other suggestions?
UPDATE
I was trying to show code only related to the problem, but I think now showing the whole would be more useful for those who try to help so here's my entire code on showMapActivity. You can see I've tried some ways around and nothing worked. Saving path's information into String url is where I'm having problem. I tested, and other parts seem to work fine. I know my code is really massy, that was why I only posted parts of the code. TMap related classes are imported from .jar file.
public class showMapActivity extends Activity {
TMapData tmapdata=new TMapData();
TMapView tmapView;
TMapPoint origin, dest;
volatile ArrayList<TMapPoint> points=new ArrayList<>();
private TextView x;
private TextView y;
private HashMap<String,LatLng> coordinates;
private HashMap<LatLng,Double> finalpoint;
static private ConcurrentHashMap<Double,Double> path;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_map);
coordinates=new HashMap<>();
Intent intent=getIntent();
tmapView=new TMapView(this);
path=new ConcurrentHashMap<>();
coordinates=(HashMap<String,LatLng>)intent.getSerializableExtra("coordinate");
path=getPathPoints(coordinates);
int i=0;
String url=getUrl();
//String url = "https://maps.googleapis.com/maps/api/elevation/json?locations=";
//String locations="";
/*
Iterator<Double> keys= path.keySet().iterator();
while(keys.hasNext()){
Double key=keys.next();
//String lat=String.valueOf(key);
//String lng=String.valueOf(path.get(key));
locations=locations+String.valueOf(key)+","+String.valueOf(path.get(key));
if(keys.hasNext())
locations=locations+"|";
}path.entrySet()
*/
/*
for(ConcurrentHashMap.Entry<Double,Double> elem : path.entrySet())
{
String lat=String.valueOf(elem.getKey());
String lng=String.valueOf(elem.getValue());
locations=locations+lat+","+lng;
i++;
if(i!=path.size())
{
locations=locations+"|";
}
}
*/
//url=url+locations+"&key=AIzaSyDD88VFMPIfC5sr0XsFL0PDCE-QRN8gQto";
//String url=getUrl(path);
FetchUrl fetchUrl=new FetchUrl();
fetchUrl.execute(url);
}
private ConcurrentHashMap<Double,Double> getPathPoints(HashMap<String,LatLng> coordinates)
{
final ConcurrentHashMap<Double,Double> Path=new ConcurrentHashMap<>();
tmapView.setSKPMapApiKey("6bb5b7f3-1274-3c5e-ba93-790aee876673");
origin=new TMapPoint(coordinates.get("origin").latitude,coordinates.get("origin").longitude);
dest=new TMapPoint(coordinates.get("dest").latitude,coordinates.get("dest").longitude);
tmapdata.findPathData(origin, dest, new TMapData.FindPathDataListenerCallback() {
#Override
public void onFindPathData(TMapPolyLine polyLine) {
points=polyLine.getLinePoint();
for(TMapPoint point : points )
Path.put(point.getLatitude(),point.getLongitude());
}
});
return Path;
}
//ConcurrentHashMap<Double,Double> path
private synchronized String getUrl() {
int i=0;
String url = "https://maps.googleapis.com/maps/api/elevation/json?locations=";
String locations="";
for(HashMap.Entry<Double,Double> elem : path.entrySet())
{
String lat=String.valueOf(elem.getKey());
String lng=String.valueOf(elem.getValue());
locations=locations+lat+","+lng;
i++;
if(i!=path.size())
{
locations=locations+"|";
}
}
url=url+locations+"&key=AIzaSyDD88VFMPIfC5sr0XsFL0PDCE-QRN8gQto";
//https://maps.googleapis.com/maps/api/elevation/json?locations=
// 39.7391536,-104.9847034|36.455556,-116.866667&key=AIzaSyDD88VFMPIfC5sr0XsFL0PDCE-QRN8gQto
// Output format
return url;
}
private class FetchUrl extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
//downloadURL
data = downloadUrl(url[0]);
Log.d("Background Task data", data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//ParserTask
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
//읽은 데이터를 버퍼에 저장
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, ArrayList<Double>> {
// Parsing the data in non-ui thread
#Override
protected ArrayList<Double> doInBackground(String... jsonData) {
JSONObject jObject;
ArrayList<Double> altitude = null;
try {
jObject = new JSONObject(jsonData[0]);
Log.d("ParserTask",jsonData[0].toString());
//DataParser class 호출
DataParser parser = new DataParser();
Log.d("ParserTask", parser.toString());
// Starts parsing data
altitude = parser.parse(jObject);
Log.d("ParserTask","Getting Altitudes");
Log.d("ParserTask",altitude.toString());
} catch (Exception e) {
Log.d("ParserTask",e.toString());
e.printStackTrace();
}
return altitude;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(ArrayList<Double> result) {
finalpoint=new HashMap<>();
LatLng latLng;
int i=0;
for(HashMap.Entry<Double,Double> elem : path.entrySet() )
{
latLng=new LatLng(elem.getKey(),elem.getValue());
finalpoint.put(latLng,result.get(i++));
}
x = (TextView) findViewById(R.id.textView5);
y = (TextView) findViewById(R.id.textView6);
x.setText(String.valueOf(finalpoint.get(coordinates.get("origin"))));
y.setText(String.valueOf(finalpoint.get(coordinates.get("dest"))));
}
}
}
(Apologies for posting this as an answer - I don't yet have the required reputation to comment)
Simply adding synchronized to a method doesn't necessarily guarantee thread safety.
How and when is path being populated?
Update after additional information provided
The problem seems to be that the path points are being generated asynchronously, and you are trying to use them before the generation process has finished (or perhaps even started). This happens because the findPathData simply starts the generation process and returns immediately (i.e. before the generation process has finished). In your code, you then go on and build the URL which is supposed to contain the point data immediately. At this point the background point generation process may not have finished, and may not have even started. As a result the point map may be empty or incomplete, and your URL will not be generated as you expect.
You need to find a way to wait until all of the path point data has been returned by the asynchronous processing before creating the URL. This looks like it could be very difficult, if not impossible, with the version of the findPathData method you are using, because it returns points via the callback one at a time and you may not know how many will be generated.
I had a quick look at the API for TMapData and it has a findPathDataAll method which seems to generate all the points and return them in a single callback call rather than one by one. If this is indeed what it does (sorry, I can't read Korean), you could use this method and then generate the URL from the callback, because when it's called you know that the generation process has been completed. If you do this, be careful to make sure that you're on the main thread before interacting with the UI or Activity.
Hope that helps.

get JSON object with API client

Im trying to get JSONobject from api but i cant get this piece of code to work.
I am new to android and java and JSON. i keep getting the error: in JSONobject cannot be applied
Main code:
try {
APIClientJSONObject api = new APIClientJSONObject();
JSONObject result = null;
try {
result = api.execute(URL).get();
} catch (Exception e) {
e.printStackTrace();
}
List<CustomListView> contents = new ArrayList<CustomListView>();
try {
JSONObject row = result.getJSONObject(result**ERROR HERE**);
String content = row.optString("FormattedName");
String content2 = row.optString("Title");
String content3 = row.optString("Subtitle");
String content4 = row.optString("Text");
EditText name = (EditText) findViewById(R.id.etInternNaam);
name.setText(content);
EditText titel = (EditText) findViewById(R.id.etName);
titel.setText(content2);
EditText ondertitel = (EditText) findViewById(R.id.etOndertitel);
ondertitel.setText(content3);
EditText EditText = (EditText) findViewById(R.id.etTekst);
EditText.setText(Html.fromHtml(content4));
} catch (JSONException e) {
e.printStackTrace();
}
Api client:
public class APIClientJSONObject extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = new JSONObject(builder.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
JSON output:
{
"FormattedName": "Home page | Footer grijs",
"Title": null,
"Subtitle": null,
"Text": "<div style=\"text-align: center;\"><img style=\"max-width: 80%;\" src=\"/MoxieManager/code.PNG\" alt=\"\"></div>",
"WebsiteId": "6869a7a1-0d65-4cfa-9df1-b0b0d346212e",
"Id": "b9906cb0-cdb2-484a-b603-020e8b64f97b",
"DateCreated": "2016-01-25T12:09:50.367",
"DateModified": "2016-02-11T08:51:54.223",
"CreatedBy": "Drie-O Automatisering",
"ModifiedBy": "Drie-O Automatisering",
"SortOrder": 0
}
Reason:
You are already getting the JSONObject from AsycnTask. There is no need of
JSONObject row = result.getJSONObject(result);
When you try to used this it means you are trying to find a object result inside object result. Which is not the case here.
Solution:
You should remove the above mentioned call and use result in these calls like below.
String content = result.optString("FormattedName");
String content2 = result.optString("Title");
String content3 = result.optString("Subtitle");
String content4 = result.optString("Text");
Is the error coming at this line?
JSONObject row = result.getJSONObject(result);
result is a JSONObject, and the method requires a String.
Why not try to convert result to String and pass it. Something like.
JSONObject resultJson = new JSONObject();
result.toString();
JSONObject row = result.getJSONObject(resultJson );
You have already got the JSON output as given from the APIClient.
JSONObject row = result.getJSONObject(result);
this line is redundant unless your real response is an array list enclosed object and you are getting only a row from it.
Directly you can access internal elements in main object now.

Categories