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.
Related
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.
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
My json is like this i want to parse newsitems to get tittle,url,contents,feelabel,url and feedlabel
{
"appnews": {
"appid": 466560,
"newsitems": [
{
"gid": "2284879949551103234",
"title": "These are the top 100 Steam games of 2017",
"url": "http://store.steampowered.com/news/externalpost/rps/2284879949551103234",
"is_external_url": true,
"author": "contact#rockpapershotgun.com (Alec Meer)",
"contents": "Another year over, a new one just begun, which means, impossibly, <em>even more games.</em> But what about last year? Which were the games that most people were buying and, more importantly, playing? As is now something of a tradition, Valve have let slip a big ol’ breakdown of the most successful titl...",
"feedlabel": "Rock, Paper, Shotgun",
"date": 1514919601,
"feedname": "rps",
"feed_type": 0,
"appid": 550
},
{
"gid": "2284879949546841782",
"title": "ShiroGames - Bye bye 2017 and WELCOME 2018 !!!",
"url": "http://store.steampowered.com/news/externalpost/steam_community_announcements/2284879949546841782",
"is_external_url": true,
"author": "Lord_brioche",
"contents": "Hello Northgardians, As the end of 2017 is upon us, we wanted to share with you a few thoughts. What a year! At the beginning of 2017, Northgard was about to start its 6-months Early Access period. At the time, the game was supposed to be a fun, solo strategy game with 4 clans and ShiroGames was onl...",
"feedlabel": "Community Announcements",
"date": 1514818282,
"feedname": "steam_community_announcements",
"feed_type": 1,
"appid": 466560
},
{
"gid": "2284879949521363459",
"title": "Best PC games of 2017",
"url": "http://store.steampowered.com/news/externalpost/rps/2284879949521363459",
"is_external_url": true,
"author": "contact#rockpapershotgun.com (RPS)",
"contents": "The calendar’s doors have been opened and the games inside have been eaten. But fear not, latecomer – we’ve reconstructed the list in this single post for easy re-consumption. Click on to discover the best games of 2017. (more…) ",
"feedlabel": "Rock, Paper, Shotgun",
"date": 1514206814,
"feedname": "rps",
"feed_type": 0,
"appid": 240720
}
]
,
"count": 57
}
}
Json parsing code is like this
#Override
protected Void doInBackground(Void... arg0) {
News news = new News();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=466560&count=3&maxlength=300&format=json";
String jsonStr = sh.makeServiceCall(url);
;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray("appnews");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
news.setTittle( c.getString("title"));
news.setContent(c.getString("content"));
news.setDate(c.getString("date"));
news.setFeed(c.getString("feedlabel"));
news.setUrl(c.getString("url"));
newsList.add(news);
}
} catch (final JSONException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
I got error like this i want to parse newsitems to get tittle,url,contents,feelabel,url and feedlabel i used this tutorial https://www.tutorialspoint.com/android/android_json_parser.htm
org.json.JSONException: Value {"appid":466560,"newsitems":[{"gid":"2284879949551103234","title":"These are the top 100 Steam games of 2017","url":"http:\/\/store.steampowered.com\/news\/externalpost\/rps\/2284879949551103234","is_external_url":true,"author":"contact#rockpapershotgun.com (Alec Meer)","contents":"Another year over, a new one just begun, which means, impossibly, <em>even more games.<\/em> But what about last year? Which were the games that most people were buying and, more importantly, playing? As is now something of a tradition, Valve have let slip a big ol’ breakdown of the most successful titl...","feedlabel":"Rock, Paper, Shotgun","date":1514919601,"feedname":"rps","feed_type":0,"appid":550},{"gid":"2284879949546841782","title":"ShiroGames - Bye bye 2017 and WELCOME 2018 !!!","url":"http:\/\/store.steampowered.com\/news\/externalpost\/steam_community_announcements\/2284879949546841782","is_external_url":true,"author":"Lord_brioche","contents":"Hello Northgardians, As the end of 2017 is upon us, we wanted to share with you a few thoughts. What a year! At the beginning of 2017, Northgard was about to start its 6-months Early Access period. At the time, the game was supposed to be a fun, solo strategy game with 4 clans and ShiroGames was onl...","feedlabel":"Community Announcements","date":1514818282,"feedname":"steam_community_announcements","feed_type":1,"appid":466560},{"gid":"2284879949521363459","title":"Best PC games of 2017","url":"http:\/\/store.steampowered.com\/news\/externalpost\/rps\/2284879949521363459","is_external_url":true,"author":"contact#rockpapershotgun.com (RPS)","contents":"The calendar’s doors have been opened and the games inside have been eaten. But fear not, latecomer – we’ve reconstructed the list in this single post for easy re-consumption. Click on to discover the best games of 2017. <a href=\"https:\/\/www.rockpapershotgun.com\/2017\/12\/25\/best-pc-games-of-2017\/#more-503951\" class=\"more-link\">(more…)<\/a> ","feedlabel":"Rock, Paper, Shotgun","date":1514206814,"feedname":"rps","feed_type":0,"appid":240720}],"count":57} at appnews of type org.json.JSONObject cannot be converted to JSONArray
appnews is JSONObject so
// fetch appnews jsonobject
JSONArray news= jsonObj.getJSONObject("appnews");
// fetch the news items jsonarray which actually contains your data
JSONArray contacts = news.getJSONArray("newsitems");
There is a typo and apparently, there's already a news object so
JSONArray appNews= jsonObj.getJSONObject("appnews");
JSONArray contacts = appNews.getJSONArray("newsitems");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
news.setTittle( c.getString("title"));
news.setContent(c.getString("contents"));
news.setDate(c.getString("date"));
news.setFeed(c.getString("feedlabel"));
news.setUrl(c.getString("url"));
newsList.add(news);
}
Try This
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonObjAppnews = jsonObj.getString("appnews");
JSONArray contacts = jsonObjAppnews.getJSONArray("newsitems");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
news.setTittle( c.getString("title"));
news.setContent(c.getString("contents"));
news.setDate(c.getString("date"));
news.setFeed(c.getString("feedlabel"));
news.setUrl(c.getString("url"));
newsList.add(news);
}
}
catch (final JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I´m doing a APP in Android using the API REST to get data from my wordpress page. I want to see the image, the title and the description of the post in my app.
Wordpress return the media with this format:
"author": 5,
"featured_media": 1836,
"comment_status": "open",
"ping_status": "open",
"sticky": false,
"format": "standard",
"meta":
The GET service only give me the media id and I want the source url. I have to call to "PAGEURL/wp-json/wp/v2/media/IDMEDIA" to get the source url. This is too inefficient and too low. How could I get the source url with 1 call to GET service? I try to edit the plugin but it isn´t work.
This is the function to get the data from Wordpress
public class FeedTask extends AsyncTask<String, Void, ArrayList<JSONArray>>{
private OnFeedListener listener;
public FeedTask(OnFeedListener listener){
this.listener=listener;
}
#Override
protected ArrayList<JSONArray> doInBackground(String... params) {
ArrayList<JSONArray> arrays=new ArrayList<>();
String url=params[0];
OkHttpClient client=new OkHttpClient();
Request.Builder builder=new Request.Builder();
Request request=builder.url(url).build();
try {
Response response=client.newCall(request).execute();
String json=response.body().string();
try{
JSONArray array= new JSONArray(json);
//Array de Imágenes
JSONArray arrayImages=new JSONArray();
for(int i=0; i<array.length(); i++) {
String urlImage=("http://PAGEURL/wp-json/wp/v2/media/")+array.optJSONObject(i).optString("featured_media");
request=builder.url(urlImage).build();
response=client.newCall(request).execute();
json=response.body().string();
arrayImages.put(new JSONObject(json));
}
arrays.add(array);
arrays.add(arrayImages);
return arrays;
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<JSONArray> array) {
super.onPostExecute(array);
if(array==null){
return;
}
if(listener!=null){
listener.onFeed(array);
}
}
}
You can get Featured image with one call.
You shouldn't edit the plugin, your edits will be overridden on an update.
You should use the _embed parameter to allow featured image to show
http://example.com/wp-json/wp/v2/posts?&_embed=true
Data would be returned to you as _embedded , which contains an Object
"wp:featuredmedia" => [ "media_details" => sizes => { thumbnail, medium, full } ]
I am creating an Android application, and I am trying to retrieve data from a Restful Web-service through JSON.
I have performed a call with get and post JSON data from a Restful Web service(from a URL)
By this Tutorial
So here I need to add price * quantity
like the example below:
But I don't know how to Post this calculation for JSON data
I googled and tried few Other options....
Can any one suggest me like this kind for Post JSON data..
I followed this to POST JSON Data
But this Should be Done OnClick, it should ask add enter quantity.
Offline(db) its possible But for Custom Listview(Async listview-Online) I am Unable to Build
Please let me Know to Use for this kind...
I google many options But I am Help less....
As I understood your question I'm trying to provide answer as follow. I hope that you understand Model class concept, which makes life easier.
Step - 1 :
First create one model class and make it Serializable to pass model object, because I can see that you have two activities one for products list and second for billing. In this you may add/remove some fields as per your requirements.
public class Product implements Serializable {
public String productName;
public int price;
public int quantity;
public int total;
}
Step - 2 : Now I'm assuming that you know how to assign data to ArrayList userProducts by using gson library, link1 and link2.
Step - 3 : Next step would be to calculate total = price * quantity in listview setOnItemClickListener like this,
Product product = userProducts.get(postiton);
product.total = product.price * product.quantity;
Step - 4 : Send arraylist with Serializable object from one activity to another,
Intent intent = new Intent(ProductActivity.this, BillingActivity.class);
intent.putExtra("user_products", userProducts);
startActivity(intent);
Step - 5 : Get values in billing activity,
if (getIntent() != null) {
userProducts = (ArrayList<Product>) getIntent()
.getSerializableExtra("user_products");
}
Step - 6 : Now your question is how to post them ? The thing is that you've to create jsonarray for list of products and jsonobject for some other fields, and then you can send main jsonobject as a string, a very good tutorial.
try {
JSONObject mainJObject = new JSONObject();
JSONArray productJArray = new JSONArray();
for (int i = 0; i < userProducts.size(); i++) {
JSONObject productJObject = new JSONObject();
productJObject.put("productname", userProducts.get(i).productName);
productJObject.put("price", userProducts.get(i).price);
productJObject.put("quantity", userProducts.get(i).quantity);
productJObject.put("total", userProducts.get(i).total);
productJArray.put(productJObject);
}
mainJObject.put("products", productJArray);
mainJObject.put("grandd_total", grandTotal);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It should look like this,
{
"products": [
{
"productname": "p1",
"price": "15",
"quantity": "6",
"total": 90
},
{
"productname": "p2",
"price": "25",
"quantity": "4",
"total": 100
}
],
"grandd_total": 190
}
You can use this json-structure data to post to the server:
{
"date": "2015-07-03",
"item": [
{
"itemname": "xyz",
"quantity": 6,
"price": 80
},
{
"itemname": "abc",
"quantity": 6,
"price": 80
}
],
"total": "960",
"currency": "Rs."
}
Everything where money is involved you should use BigDecimal how you will post data to server really doesn't meather as long data are secured.
I would use volley lib. It take care of a lot of stuff instead of you and you should really dig into, it will save you a lot of time: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
Also, I would use GSON for json objects. Its also simple for example create class:
public class Money{
String name;
int quantay;
BigDecimal rate;
BigDecimal total;
/* make seters and getters */
}
and the just create json like this:
money = new Money("name", 100, 0.54, 54);
Gson gson = new Gson();
String json = gson.toJson(money);
thats it. Well you need constructor in Money class.
how this answer help you.
you can read json right?
so by json object try this :-
Double Rate = Double.parseDouble(jsonobject.getString("Rate"));//put api parameter
int Qty= Integer.parseInt(jsonobject.getString("Qty"));
Double total = Rate * Qty;
//set total on your textview lable
textview.settext(""+total);
and save in your local database and when you need to post then post your database to server.
I would rather calculate the data before posting it to the php database. You can use something like the following:
double a = 1.50;
double b = 2.00;
double c = a * b;
Using the HTTPPost medthod (which by the way is depreciated) you need to then do something similar to the below:
public void postData(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yourdomain.com/post.php");
try {
List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("data1", c));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
text = new String(baf.toByteArray());
txtvw.setText(text);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Hope this helps :)
Hope this helps you , as per above ans i have checked, you need Grand_Total to post on Bill Webservice.
you just calculate and pass that data to Bill Screen like above given ans
if (getIntent() != null) {
userProducts = (ArrayList<Product>) getIntent()
.getSerializableExtra("user_products");
}
Here is one Grand Total is missing to pass as per looks in Billing screen
(Here we trying to get Grand total Rs.905)
double Grand_total = 0.0;
for(int i=0;i<userProducts.size();i++)
{
Product product = userProducts.get(postiton);
product.total = product.price * product.quantity;
Grand_total +=product.total;
}
Now you can pass all required data to Billing webservice like
try {
JSONObject mainJObject = new JSONObject();
JSONArray productJArray = new JSONArray();
for (int i = 0; i < userProducts.size(); i++) {
JSONObject productJObject = new JSONObject();
productJObject.put("productname", userProducts.get(i).productName);
productJObject.put("price", userProducts.get(i).price);
productJObject.put("quantity", userProducts.get(i).quantity);
productJObject.put("total", userProducts.get(i).total);
productJObject.put("total", userProducts.get(i).total);
productJArray.put(productJObject);
}
mainJObject.put("products", productJArray);
mainJObject.put("Grand_total", Grand_total);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am writing an Android news reader as a learning exercise and having lots of trouble parsing the data. I have searched everywhere. The tutorials I have found use JSON streams that are of a much simpler structure than what google is sending.
Here is a snippet of the string I capture - the JSON array starts with "entries" and I am showing two entries, with the middle of the second one deleted for brevity.
{
"responseData": {
"feed": {
"feedUrl": "http://news.google.com/news?output\u003drss",
"title": "Top Stories - Google News",
"link": "http://news.google.com/news? pz\u003d1\u0026amp;ned\u003dus\u0026amp;hl\u003den",
"author": "",
"description": "Google News",
"type": "rss20",
"entries": [{
"title": "Major air rescue planned in flooded Colorado county - Fox News",
"link": "http://news.google.com/news/url? sa\u003dt\u0026fd\u003dR\u0026usg\u003dAFQjCNHCJS1c-eurSg- 8tAt0PjZ4tiaLdA\u0026url\u003dhttp://www.foxnews.com/weather/2013/09/15/colorado-braces-for-more-heavy-rain-deadly-floods/",
"author": "",
"publishedDate": "Mon, 16 Sep 2013 04:49:21 -0700",
"contentSnippet": "U.S. News \u0026 World ReportMajor air rescue planned in flooded Colorado countyFox NewsResidents of Boulder County, Colorado are ...",
"content": "\u003ctable border\u003d\"0\" cellpadding\u003d\"2\" cellspacing\u003d\"7\" 3d\"\"border\u003d\"1\" width\u003d\"80\" height\u003d\"80\"\u003e\u003cbr\u003e\u003cfont size\u003d\"-2\"\u003eU.S. News \u0026amp; 03e\u003c/font\u003e\u003cbr\u003e\u003cfont size\u003d\"-1\"\u003eResidents of Boulder County, Colorado are being asked to help guide helicopter pilots to their locations Monday as a major air rescue is being planned to take advantage of a clear weather forecast. \u0026quot;The pilots are going to go anywhere and everywhere they \u003cb\u003e...\u003c/b\u003e\u003c/font\u003e\u003cbr\u003e\u003cfont size\u003d\"-1\"\u003e\u003ca href\u003d\"http://news.google.com/news/url? sa\u003dt\u0026amp;fd\u003dR\u0026amp;usg\u003dAFQjCNHc6lIe9u_YShLkh7NV5WR9rO6YHQ\u0026amp; url\u003dhttp://www.therepublic.com/view/story/b663f09bbf48403c9041a86623fe428e/CO-- Colorado-Flooding-National-Guard\"\u003eNational Guard members trapped during evacuations from flooded Colorado town\u003c/a\u003e\u003cfont size\u003d\"-1\" color\u003d\"#6f6f6f\"\u003eThe Republic\u003c/font\u003e\u003c/font\u003e\u003cbr\u003e\u003cfont size\u003d\"-1\"\u003e\u003ca href\u003d\"http://news.google.com/news/url? sa\u003dt\u0026amp;fd\u003dR\u0026amp;usg\u003dAFQjCNFij70BTG-5dO69JM0BVO32S0S- aA\u0026amp;url\u003dhttp://www.cnn.com/2013/09/15/us/colorado-flooding/? hpt%3Dhp_t1\"\u003eColorado floods: More than 500 still unaccounted for as \u0026#39;devastating\u0026#39; rain looms\u003c/a\u003e\u003cfont size\u003d\"-1\" Radio\u003c/a\u003e\u003c/font\u003e\u003cbr\u003e\u003cfont size\u003d\"-1\"\u003e\u003ca href\u003d\"http://news.google.com/news/more? ncl\u003ddQHisuNx5u46LtMZh5z80DBxCCRjM\u0026amp;ned\u003dus\u0026amp;topic\u003dh\"\u003e\u 003cb\u003eall 1,507 news articles »\u003c/b\u003e\u003c/a\u003e\u003c/font\u003e\u003c/div\u003e\u003c/font\u003e\u003c/td\u0 03e\u003c/tr\u003e\u003c/table\u003e",
"categories": ["Top Stories"]
},
{
"title": "Costa Concordia salvage begins: Will ship stay in one piece during righting? - CNN",
"link": "http://news.google.com/news/url? sa\u003dt\u0026fd\u003dR\u0026usg\u003dAFQjCNFD_8vBF3Gb6B2_6DnbCDwMELEkFQ\u0026url\u003dhtt p://www.cnn.com/2013/09/15/world/europe/italy-costa-concordia-salvage/",
"author": "",
....deletedcontentsforbrevity...."categories": ["Top Stories"]
}]
}
},
"responseDetails": null,
"responseStatus": 200
}
So I have successfully captured the string and now want to create a JSONArray and extract the JSONObjects from it. Here is the code:
private void parseJSONString( JSONObject Jobj) throws IOException, JSONException {
try {
// Getting Array of news
newsItems = Jobj.getJSONArray(ENTRIES);
// looping through All Contacts
for(int i = 0; i < newsItems.length(); i++){
JSONObject c = newsItems.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TITLE);
String link = c.getString(LINK);
String author = c.getString(AUTHOR);
String pubDate = c.getString(PUBLISHED_DATE);
String content = c.getString(CONTENT);
}
} catch (JSONException e) {
e.printStackTrace();
}
I am catching the JSONException with the message "No values for entries" from the very
first line of code: newsItems = Jobj.getJSONArray(ENTRIES);
The parameter jobj and call to this method is created onPostExecute like this:
protected void onPostExecute(Void result) {
mTextView.setText(mDataString);
if (mDataString != null)
try {
mJSONObj = new JSONObject(mDataString);
parseJSONString(mJSONObj);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("JSON Parser", "Error converting string to json " + e.toString());
}
}
Yet as you can see, "entries" clearly precedes the array marker "[" in the text file. I am truly stumped. Would appreciate a little help.
You must firstly get:
responseData -> feed -> entries
JSONObject responseData = Jobj.getJSONObject("responseData");
JSONObject feed = responseData.getJSONObject("feed");
and only after:
newsItems = feed.getJSONArray("entries");