Json data fetching lag problem from jsonbin.io - java

I'm working on a app that is a simple game, so here's a picture for the UI I have, the problem is when I fetch a level using Json web service, the first time I choose the level from activity_level_list, the picture and level number doesn't show, only the 4 words works but neither the image nor the level number appear like this.
NOTE: The image URL variable is null (because of the lag that happens the first time I open first level activity) so an error happen (that's why it shows ic_launcher instead of showing the level picture).
So, I said the problem was "lag" because when I go back to LevelList and click on level 1, the picture and the level number get fetched and everything becomes good.
How can I make it both the image and level ID appears in the first time I open the activity?
NOTE: I use jsonbin.io for data fetching.
Here's my Json data fetching class:
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FetchData extends AsyncTask<Void,Void,Void> {
String update = "4";
String data ="";
String id;
String img;
String w1;
String w2;
String w3;
String w4;
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/" + update);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
// for(int i = 0 ;i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(1);
id = (String) JO.get("id");
img = (String) JO.get("img");
w1 = (String) JO.get("w1");
w2 = (String) JO.get("w2");
w3 = (String) JO.get("w3");
w4 = (String) JO.get("w4");
// }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
int levelId = Integer.parseInt(id);
levelId++;
LevelActivity.levelID = String.valueOf(levelId);
LevelActivity.imageURL = img;
LevelActivity.button1Word = w1;
LevelActivity.button2Word = w2;
LevelActivity.button3Word = w3;
LevelActivity.button4Word = w4;
}
}
Thanks ^-^

I just needed to update the image and level text view number in onPostExecute method to make it load from the first time.
Answer by NIKHIL AGGARWAL

Related

How to Retrieve Live Currency Information from xml file in Server

I want to parse an xml file of this form from a url into my android application.
<ArrayOfCurrency xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MobileAssignmentApi.Models">
<Currency>
<Buy>21.19573</Buy>
<CurrencyId>53</CurrencyId>
<Name>USD/MXN</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>21.15679</Sell>
</Currency>
<Currency>
<Buy>1.46806</Buy>
<CurrencyId>22</CurrencyId>
<Name>EUR/NZD</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>1.46395</Sell>
</Currency>
<Currency>
<Buy>1.34658</Buy>
<CurrencyId>15</CurrencyId>
<Name>EUR/CAD</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>1.3445</Sell>
</Currency>
.
.
.
</ArrayOfCurrency>
It is an array of currencies.
After a lot of effort i managed to parse the xml file into a string into my application.
The string have now the following form.
[{"currencyId":53,"buy":21.23042,"sell":21.1921,"name":"USD/MXN","pipMultiplier":10000},{"currencyId":22,"buy":1.50225,"sell":1.49891,"name":"EUR/NZD","pipMultiplier":10000},{"currencyId":15,"buy":1.38201,"sell":1.38083,"name":"EUR/CAD","pipMultiplier":10000},{"currencyId":62,"buy":0.69619,"sell":0.69404,"name":"NZD/CHF","pipMultiplier":10000},{"currencyId":19,"buy":80.085,"sell":79.968,"name":"NZD/JPY","pipMultiplier":100},{"currencyId":13,"buy":1.23727,"sell":1.23613,"name":"GBP/CHF","pipMultiplier":10000},{"currencyId":16,"buy":0.95424,"sell":0.95167,"name":"AUD/CAD","pipMultiplier":10000},{"currencyId":5,"buy":1.00469,"sell":1.00414,"name":"USD/CHF","pipMultiplier":10000},{"currencyId":1,"buy":122.014,"sell":121.839,"name":"EUR/JPY","pipMultiplier":100},{"currencyId":60,"buy":0.9092,"sell":0.90615,"name":"NZD/CAD","pipMultiplier":10000},{"currencyId":97,"buy":30.806,"sell":30.793,"name":"TRY/JPY","pipMultiplier":100},{"currencyId":10,"buy":0.68269,"sell":0.6823,"name":"NZD/USD","pipMultiplier":10000},{"currencyId":23,"buy":1.61316,"sell":1.61245,"name":"GBP/CAD","pipMultiplier":10000},{"currencyId":9,"buy":1.31115,"sell":1.31023,"name":"USD/CAD","pipMultiplier":10000},{"currencyId":3,"buy":1.21594,"sell":1.21552,"name":"GBP/USD","pipMultiplier":10000},{"currencyId":27,"buy":1.75536,"sell":1.7494,"name":"GBP/NZD","pipMultiplier":10000},{"currencyId":63,"buy":3.6378,"sell":3.62206,"name":"USD/TRY","pipMultiplier":10000},{"currencyId":64,"buy":3.83117,"sell":3.81819,"name":"EUR/TRY","pipMultiplier":10000},{"currencyId":28,"buy":0.73074,"sell":0.72814,"name":"AUD/CHF","pipMultiplier":10000},{"currencyId":50,"buy":9.54563,"sell":9.51557,"name":"EUR/SEK","pipMultiplier":10000},{"currencyId":18,"buy":87.091,"sell":86.919,"name":"CAD/JPY","pipMultiplier":100},{"currencyId":14,"buy":1.43031,"sell":1.4289,"name":"EUR/AUD","pipMultiplier":10000},{"currencyId":8,"buy":0.71693,"sell":0.7154,"name":"AUD/USD","pipMultiplier":10000},{"currencyId":17,"buy":83.97,"sell":83.811,"name":"AUD/JPY","pipMultiplier":100},{"currencyId":11,"buy":0.84385,"sell":0.84329,"name":"EUR/GBP","pipMultiplier":10000},{"currencyId":4,"buy":115.641,"sell":115.555,"name":"USD/JPY","pipMultiplier":100},{"currencyId":61,"buy":0.75641,"sell":0.75508,"name":"CAD/CHF","pipMultiplier":10000},{"currencyId":20,"buy":1.67121,"sell":1.66758,"name":"GBP/AUD","pipMultiplier":10000},{"currencyId":76,"buy":1171.7,"sell":1170.674,"name":"XAU/USD","pipMultiplier":100},{"currencyId":6,"buy":142.45,"sell":142.188,"name":"GBP/JPY","pipMultiplier":100},{"currencyId":2,"buy":1.04081,"sell":1.03929,"name":"EUR/USD","pipMultiplier":10000},{"currencyId":54,"buy":13.77633,"sell":13.70746,"name":"USD/ZAR","pipMultiplier":10000},{"currencyId":7,"buy":1.05845,"sell":1.05868,"name":"EUR/CHF","pipMultiplier":10000},{"currencyId":52,"buy":8.53823,"sell":8.51386,"name":"USD/NOK","pipMultiplier":10000},{"currencyId":48,"buy":9.0615,"sell":9.03791,"name":"USD/SEK","pipMultiplier":10000},{"currencyId":12,"buy":113.73,"sell":113.454,"name":"CHF/JPY","pipMultiplier":100},{"currencyId":21,"buy":1.03599,"sell":1.03438,"name":"AUD/NZD","pipMultiplier":10000},{"currencyId":51,"buy":8.99332,"sell":8.96375,"name":"EUR/NOK","pipMultiplier":10000},{"currencyId":150,"buy":6.7165,"sell":6.7144,"name":"USD/CNH","pipMultiplier":1000},{"currencyId":77,"buy":15.142,"sell":15.112,"name":"XAG/USD","pipMultiplier":100},{"currencyId":93,"buy":7.182,"sell":7.129,"name":"ZAR/JPY","pipMultiplier":100}]
using the following code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
String str = "http://massignment.zulutrade.com/api/rates";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskClass().execute(str);
}
class AsyncTaskClass extends AsyncTask<String, Void,String > {
private Exception exception;
protected String doInBackground(String ...params) {
URLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(str);
connection = url.openConnection();
connection.setDoOutput(true);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
StringBuilder builder = new StringBuilder();
int i=0;
while ((line = reader.readLine()) != null) {
builder.append(line+"\n");
// Log.w("Response ", "> " + line );
i++;
}
String xml = builder.toString();
}
catch( IOException e) {
e.printStackTrace();
}
return "0k";
}
protected void onPostExecute() {
}
}
}
I need to parse that xml/string to its contents.
Any idea how can i do that parsing?
Assuming that your code is in Java - there are some good XML parsers available. You may want to use one of them to parse your XML.

Android Studio java.net.MalformedURLException: Protocol not found:

I am working on the sunshine app from udacity tutorials. I am somewhere on lesson2. When I try to run a feature of the app I get this errors:
04-29 12:21:13.311 22025-22424/name.company.sunshine.app E/FetchWeatherTask﹕ Error
java.net.MalformedURLException: Protocol not found: "http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
at java.net.URL.<init>(URL.java:176)
at java.net.URL.<init>(URL.java:125)
at name.company.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:144)
at name.company.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:101)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
04-29 12:21:13.321 22025-22025/name.company.sunshine.app D/AbsListView﹕ unregisterIRListener() is called
04-29 12:21:13.321 22025-22025/name.company.sunshine.app E/ViewRootImpl﹕ sendUserActionEvent() mView == null
line 144 is
URL url = new URL(builtUri.toString());
I will provide the entire class if you need it.
And something else, I have this in the manifest
<uses-permission android:name="android.permission.INTERNET" />
but when I install the app it never asks for permission.
This is the file :
package name.company.sunshine.app;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id == R.id.action_refresh){
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
String forecastArray[] = {
"Today-Sunny-88/63",
"Tuesday-Foggy-14/32",
"Wednesday-Cloudy-22/33"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
#Override
protected String[] doInBackground(String... params) {
//If there's no zip code, there's nothing to look up. Verify size of params
if(params.length == 0){
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL =
"\"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM,params[0])
.appendQueryParameter(FORMAT_PARAM,format)
.appendQueryParameter(UNITS_PARAM,units)
.appendQueryParameter(DAYS_PARAM,Integer.toString(numDays)).build();
Log.v(LOG_TAG,"Built URI"+builtUri.toString());
URL url = new URL(builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try{
return getWeatherDataFromJson(forecastJsonStr,numDays);
} catch (JSONException e){
Log.e(LOG_TAG,e.getMessage(),e);
e.printStackTrace();
}
return null;
}
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
}
}
Now I don t have the error anymore after deleting "/" ", but this line is not being printed
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
probably it fails to connect or something. I can't see anything in logCat for some reason .
The issue is that you are escaping the " before the start of url and its considering it to be part of Url. since "http is not a valid protocol , valid values are http https ftp etc.
final String FORECAST_BASE_URL = "\"http://api.openweathermap.org/data/2.5/forecast/daily?";
should be
final String FORECAST_BASE_URL ="http://api.openweathermap.org/data/2.5/forecast/daily?";
Your URI is not a URI. There is no protocol component. It needs http:// or whatever other protocol you intend.
remove "/" from your FORECAST_BASE_URL
final String FORECAST_BASE_URL ="http://api.openweathermap.org/data/2.5/forecast/daily?";

Use getJSONObject(int)

I'm trying to parse some JSON. Here is the code. frc-manual.usfirst.org/a/GetAllItems/ManualID=3 I have been trying for several hours to get it work but every example I have seen online uses getJSONObject(int) but I can only use getJSONObject(String). This is making impossible. Am I overlooking something?
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.annotation.SuppressLint;
public class JSON {
private String html = "html";
private String version = "version";
private String pageString = null;
private String urlString = "http://frc-manual.usfirst.org/a/GetAllItems/ManualID=3";
public volatile boolean parsingComplete = true;
public JSON(String page){
this.pageString = page;
}
public String getHTML(){
return html;
}
public String getVersion(){
return version;
}
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
JSONObject head = reader.getJSONObject("data").getJSONObject("SubChapter").getJSONObject("3").getJSONObject("children").getJSONObject(pageString);
if(head != null){
html = head.getString("item_content_text");
html = html + head.length();
for(int i = 0; i < head.length();i++){
JSONObject children = head.getJSONObject(i);
if(children != null){
html = html + children.getString("item_content_text");
}
}
}
//html = html + listFromJsonSorted(head.getJSONObject("children"));
JSONObject main = reader.getJSONObject("data");
version = main.getString("LatestManualUpdate");
parsingComplete = false;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fetchJSON(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
String data = convertStreamToString(stream);
readAndParseJSON(data);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
Probably what you are seeing in this example is a JSONArray.
JSONArray arr = json.getJSONArray("array");
JSONObject obj = arr.getJSONObject(0);
In your case, i don't see any array in this JSON, head in your code is a JSONObject. To get the item_content_text you just need head.getString("item_content_text");
You can do this to get all childrens in your JSON:
html = head.getString("item_content_text");
JSONObject children = head;
while (children.containsKey("children")) {
children = children.getJSONObject("children");
html += children.getString("item_content_text");
}
You are only able to use getJSONObject(String) not getJSONObject(int) because the method only takes String.. Check documentation here..
The reason that is the because the keys in json are always strings only.. read here
I think you are looking to retrieve an int value from the json but you got confused.. The way to do that would be getInt("key_name") if the json indeed has a key with int value..
Sure you can, just that I think your "head" variable should have a return type of JSONArray instead of JSONObject.
I have this code running in my program -
//response = some http response
final JSONObject object = new JSONObject(response);
final JSONArray array = object.getJSONArray("repeatedStuff"); //$NON-NLS-1$
Assert.assertEquals(2, array.length());
for (int i = 0; i < array.length(); i++) {
final JSONObject element = array.getJSONObject(i);
//do something
}
Also you may refer this link to see what they are doing - android: The method getJSONObject(int) in the type JSONArray is not applicable for the arguments (String)
Let me know if that helped!
You have used JSONObject everywhere in your code. Thus you are only able to pass string parameter in getJSONObject().
I suggest you you change it to JSONArray and then you will be able to pass int parameter in getJSONObject().

Parsing the web page response as Json, in Java

I have a java code:
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
Which is opening the connection and printing the contents of it. The contents are indeed Json. The output is something like:
{
"merchantId": "guest",
"txnId": "guest-1349269250-001",
}
I wish to parse this in json simple jar. I changed the code loop like this:
JSONObject obj = new JSONObject();
while ((inputLine = in.readLine()) != null)
obj.put("Result",inputLine);
But that doesn't seem to be working. The output I'm getting is:
{"Result":"}"}
You should use the JSONParser#Parse() method or the JSONValue#parse() method :
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
Reader in = new InputStreamReader(oracle.openStream());
Object json = JSONValue.parse(in);
Are you sure you're following the documentation on how to parse a JSON string?
By the looks of it you have to obtain the entire string and call a JSONParse#parse() on it, but your code is filling up a HashMap (JSONObject's parent class) with each of the lines of the JSON. In fact it stores just the last line because you're calling put() with the same "Result" key on every iteration.
You should read whole contents to String variable first and parse it to json. Be careful of ""(double quote). Java uses \" for double quote. Like.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample3 {
public static void main(String args[]) {
JSONParser parser = new JSONParser();
//String str = "{\"merchantId\": \"guest\",\"txnId\": \"guest-1349269250-001\",}";
//intilize an InputStream
InputStream is = new ByteArrayInputStream("file content".getBytes());
//read it with BufferedReader and create string
BufferedReader br = new BufferedReader(new InputStreamReader(is));// Instead of is, you should use oracle.openStream()
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e1) {
e1.printStackTrace();
}
// parse string
try {
JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());
String merchantId = (String) jsonObject.get("merchantId");
System.out.println(merchantId);
String txnId = (String) jsonObject.get("txnId");
System.out.println(txnId);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
try this link its really helpful if you are going to be logging in or staff like that
Java Json simple
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
* {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
* "dataset":
* [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
* {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the title
System.out.println(genreJsonObject.get("title"));
// get the data
JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

search text only using Java

I am using ajax google API to search a string against google. It is returning me all HTML files which have all tags including text.
If I want to get text only, what should I use?
My program is in Java.
Regards
Manjot
I did some googling and found this:
http://www.ajaxlines.com/ajax/stuff/article/using_google_is_ajax_search_api_with_java.php
Here's the example code snippet from there:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.json.JSONArray; // JSON library from http://www.json.org/java/
import org.json.JSONObject;
public class GoogleQuery {
// Put your website here
private final String HTTP_REFERER = "http://www.example.com/";
public GoogleQuery() {
makeQuery("questio verum");
makeQuery("info:http://frankmccown.blogspot.com/");
makeQuery("site:frankmccown.blogspot.com");
}
private void makeQuery(String query) {
System.out.println(" Querying for " + query);
try
{
// Convert spaces to +, etc. to make a valid URL
query = URLEncoder.encode(query, "UTF-8");
URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", HTTP_REFERER);
// Get the JSON response
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
String response = builder.toString();
JSONObject json = new JSONObject(response);
System.out.println("Total results = " +
json.getJSONObject("responseData")
.getJSONObject("cursor")
.getString("estimatedResultCount"));
JSONArray ja = json.getJSONObject("responseData")
.getJSONArray("results");
System.out.println(" Results:");
for (int i = 0; i < ja.length(); i++) {
System.out.print((i+1) + ". ");
JSONObject j = ja.getJSONObject(i);
System.out.println(j.getString("titleNoFormatting"));
System.out.println(j.getString("url"));
}
}
catch (Exception e) {
System.err.println("Something went wrong...");
e.printStackTrace();
}
}
public static void main(String args[]) {
new GoogleQuery();
}
}
As a side note, you should be careful not to violate the Google TOS:
"You specifically agree not to access (or attempt to access) any of the Services through any automated means (including use of scripts or web crawlers) and shall ensure that you comply with the instructions set out in any robots.txt"
- http://www.google.com/accounts/TOS

Categories