Problem retrieving the earthquake JSON results? - java

Greeting! After I removed hardcoded JSON data and moved to request data from the URL. I am having an exception error. The code is pretty much the same as the final official git but I am getting the errors.
The code that I am extracting data from JSON is:
private static final String USGS_REQUEST_URL =
"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=5&limit=10";
//
public static List<Earthquake> extractFeaturesfromJson(String earthquakeJSON) {
/*if the json is null then return earlu*/
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
// Create an empty ArrayList that we can start adding earthquakes to
List<Earthquake> earthquakes = new ArrayList<>();
// Try to parse the JsonResponseString. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// create an object form jsonString
JSONObject root = new JSONObject(earthquakeJSON);
JSONArray features = root.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
// Get a single earthquake at position i within the list of earthquakes
JSONObject currentEarthquake = features.getJSONObject(i);
// For a given earthquake, extract the JSONObject associated with the
// key called "properties", which represents a list of all properties
// for that earthquake.
JSONObject properties = currentEarthquake.getJSONObject("properties");
double mag = properties.getDouble("mag");
String location = properties.getString("place");
long time = properties.getLong("time");
//extract the value of key url
String url = properties.getString("url");
//create new object with magnitude, location ane time and url from json response
Earthquake earthquake = new Earthquake(mag, location, time, url);
earthquakes.add(earthquake);
}
} 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 the earthquake JSON results", e);
}
// Return the list of earthquakes
return earthquakes;
}
The logcat shows:
09-26 14:49:23.628 2551-2584/com.example.android.quakereport E/com.example.android.quakereport.QueryUtils: Problem retrieving the earthquake JSON results.

The json data from your url is not formatted correctly. Compare what you are receiving from the url to the hardcoded data.

This method runs on the main UI thread after the background work has been
completed. This method receives as input, the return value from the doInBackground() method.
First we clear out the adapter, to get rid of earthquake data from a previous
query to USGS.
Then we update the adapter with the new list of earthquakes, which will trigger the ListView to re-populate its list items. But made mistake on populating data to adapter.
#Override
protected void onPostExecute(List<Earthquake> data) {
//clear the adapter of previdous earthquake data
mAdapter.clear();
if (data != null && data.isEmpty()) { //====?????shourld be !data.isEmpty())
mAdapter.addAll(data);
}
}
The real problem was onPostExecute method to populate data in mainthread after do in background method.

If you're taking the Udacity android course and encountering this error for the quakereport/DidUfeelIt app then change the URL and try with some other URL your problem will be solved.
Eg:- The URL provided by during the course was
"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2012-01-01&endtime=2012-12-01&minmagnitude=6"
Then I was getting the same error that is "problem parsing the JSON"
So I tried different URL:
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson
And it worked..!!
Always try to get the latest URL's from the USGS website during the course.

Change your request URL to USGS_REQUEST_URL="https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=6&limit=10"
The difference is in the use of https instead of http.
According to the API doc of the USGS website this website now uses the HyperText Transfer Protocol Secure (https)
https://earthquake.usgs.gov/fdsnws/event/1/

Use Online Json Validator.
http://jsonlint.com/
they will validate if the json has problems.

Related

Volley JSON Object Request for POST-ing an array, having a (string) tag and a JSON object

After looking at many examples available on Stack Overflow, I still haven't been able to figure out how to make it work out in my case yet. So, could you please provide me with some guidelines wherever possible? Specifically, I have already built a JSON array containing a tag and a JSON object, which should look like below when being posted (including the square brackets "[]"):
[
"location",
{
"coordinateA":12.45817,
"coordinateB":23.9195856
}
]
The corresponding JAVA code is as follows:
JSONObject CoordinatesFinalObj = new JSONObject();
JSONObject Location = new JSONObject();
try {
CoordinatesFinalObj.put("location-one", LocationOne);
} catch (JSONException e) {
e.printStackTrace();
}
try {
LocationOne.put("coordinateA", 12.45817);
LocationOne.put("coordinateB", 23.9195856);
} catch (JSONException e) {
e.printStackTrace();
}
When I POST-ed such the JSON array to our server using Volley JSON Object Request, it always returned the error 417. I actually did something similar by posting a Python array with a tag and a JSON object inside without any problems. And there are no special requirements of the http request header as imposed by our server.
JsonObjectRequest CoordinatesJsonObjectReq = new JsonObjectRequest(Request.Method.POST,
url, **CoordinatesFinalObj**, new Response.Listener<JSONObject>()...).
So, my question here is: Is Volley JSON Object Request a good fit for this purpose or I shall simply switch to use a string-based POST method (e.g. HttpURLConnection though it is a deprecated module). I am very confused why it is not working here...

Pull data from different APIs

I have created a news app and I wanted to pull articles from the different APIs via newsapi.org that would show up in different activities. I created
So for example, Techcrunch and Reuters. I have similar code for each activity but i switched the API link since it needs to pull from either TechCrunch and Reuters individually. Instead, only one of the activities work and the other is blank.
If i place the same API link in both activities, it works flawlessly. Please help
private void parseJSON () {
String url = "http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=*";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray =response.getJSONArray("articles");
for (int i = 0; i< jsonArray.length(); i++){
JSONObject article = jsonArray.getJSONObject(i);
String authorName = article.getString("author");
String imageUrl = article.getString("urlToImage");
String published = article.getString("publishedAt");
String description = article.getString("content");
String headline = article.getString("title");
mNewsList.add(new newsItem(imageUrl, authorName, published,description, headline ));
}
To get articles from a particular source use this URL :
https://newsapi.org/v2/top-headlines?sources=abc-news&apiKey="yourkey"
In you blank activity, do some break points and check network call returns success data or error. If network data success, then check your json parsing code to see it parses correctly.
You may try network logging interceptor to see what things are happening to your HTTP network calls.

Unable to retrieve data from POST request

I am working in JAVA 1.8 to write and using Apache Tomcat to run the server, I am unable to retrieve data from a POST request i.e in JSON.
I actually need it in an HashMap and I can even parse and convert it into HashMap even if it is readable in JSON. I have tried several links on the internet and I always get exception like Could not deserialize to type interface PACKAGE NAME.
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("ClassifyCase")
public Rules Classify(HttpServletRequest request) {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { System.out.println("Buffer Reader Error"); }
System.out.println("What I read: "+jb);
System.out.println("Here la la l ala ");
// System.out.println("Case: ++ "+Case.toString());
System.out.println("Here la la l ala ");
Rules foundRule = new Rules();
// List<Rules> objListRules = new ArrayList<Rules>();
try
{
DataAccessInterface objDAInterface = new RuleDataAdapter();
AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
// foundRule = objADBridge.Classify(Case);
logger.info("Classification done!");
}
catch(Exception ex)
{
logger.info("Error in classification");
System.out.println("Couldnt Classify Properly!");
// return
}
return foundRule;
}
Can someone please share a guide on how can I receive this data and convert it into a Map or either I can directly get a Map!
I strongly recommend you to use this library of JSON..
You can find it in Maven Repository and it's so easy to parse a JSON to a Map or to a JSONArray or JSONObject... depends of your necessity what you want to do..
Here is a example show how to parse a JSON to a HashMap
Map<String, Object> map = new JSONObject(--JSONString here--).toMap();
And that's all...
Now, if your JSON has a list of objects, i mean like a list of maps, what you just need to do is this...
JSONArray jsonArray = new JSONArray(--JSON string here--);
for(int i = 0; i < jsonArray.length(); i++){
Map<String, Object> map = jsonArray.getJSONObject(i).toMap();
}
Here is the explanation.
You take you JSON string and pass it as a parameter to the JSONArray,what JSONArray does is, take your json string a parse it to like a list
Then you make a for to get each Object of that list and parse it to a map.
Note: what the JSONObject does, is take the object of the JSONArray and parse it... you can parse it to a map or you can get each object of that map..
String jsonString = "{\n" +
"\t\"1\": \"1\",\n" +
"\t\"FPG\": \"50\",\n" +
"\t\"Symptoms\": \"Yes\"\n" +
"}";
Map<String, String> map = new Gson().fromJson(jsonString, Map.class);
for (String key: map.keySet()) {
System.out.println(map.get(key));
}
The request you send does not contain proper JSON in the body. You are missing the commas ",". It should be something like this:
{
"1":"1",
"FPG":"50",
"Symptoms":"yes"
}
Just change it and give proper JSON format to the message.
Even if the request was not in your control, I would strongly suggest that you contacted the service that creates the message and asked from them to fix it.
It would be the last resort for me to make my own deserializer to handle an "inproper" message.
An easy way to check if your JSON is properly formated is an online formatter, e.g. https://jsonformatter.org/

Getting simple Json string from url and converting it to String[] Android

I am trying to pull Json string from url and put it into String[] inside my android application.
String i am getting from my url is "[\"What is your name?\",\"How do you do?\"]"
I am trying to create Quizz class in my app where i want to call constructor and then it pull data from url and put it into private variables.
I have tried many things but getting multiple errors (with network and other stuff) and now i am somewhere with async tasks where i got lost and think i am going totally wrong way.
Class i want to have is like this:
public class Quizz {
private String[] Questions;
public Quizz() {
// Here i want to load data from url into variable Questions
}
public String getQuestion(int id) {
return "Not implemented!";
}
}
And when i create Quizz object in my main activity i want to have questions loaded.
you can use the following article to help you decode your json
Article Link
Also, You can use JSONArray in the Following Article
Use Retrofit to Connect to API, and Use its converter to deserialize the JSON Response.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
it's very effective and has error handling built into it.
I know you are looking for a string[] array but in this case its best to use a arraylist as sizes can change when retrieving the response.
//create empty strings arraylist
List<String> strings = new Arraylist<>()
//try parse the response as a JSONarray object
try{
//get url string response as a json array
JSONArray jsonArray = (JSONArray) urlStringResponse;
//parse through json array and add to list
for(int i = 0; i < jsonArray.length(); i++){
String str = (String) jsonArray.getJSONObject(i);
strings.add(str);
}
} catch (JSONException e) {
Log.e("JSON", "Problem parsing the JSON results", e);
}
What about to use String.split() method?
val string = "[\"What is your name?\",\"How do you do?\"]"
val split: List<String> = string.subSequence(1, string.length - 1).split(',')
val array = split.toTypedArray()
array.forEach { println(it) }
And result will be
"What is your name?"
"How do you do?"

Query a JSON Object in Java by index

In Java, is there a way to retrieve a piece of information from a JSON object by index? I am accessing a financial data table on quandl and want to return the most recent mortgage rate posted in the table. The key is the date the rate was posted in string form. The key for the most recent data will change weekly but the data I want will always be the first key-value pair in the table.
I was able to do this in JavaScript in about 5 minutes. But it seems more cumbersome in Java. Below is the iteration of my code that seems to be closest to getting me where I want to go. I am able to return the first key-value pair set in the table as an object in Java, which is ... ["2017-12-14",3.93]. The final step is eluding me. How do I grab the 3.93 and return that? Or is there a better way to go about this?
double baseRate = 0.0;
default double getBaseRate() throws MalformedURLException {
try {
// make a GET request
URL url = new URL("https://www.quandl.com/api/v3/datasets/FMAC/30US.json?api_key=-c-s9zf8s1NdLbhVin1p");
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
InputStreamReader is = new InputStreamReader((InputStream) request.getContent());
// Convert response stream to a JSON object
JsonReader reader = Json.createReader(is);
JsonObject obj = reader.readObject();
reader.close();
request.disconnect();
// Drill down to the desired piece of data
JsonObject dataset = obj.getJsonObject("dataset");
JsonArray data = dataset.getJsonArray("data");
Object currentData = data.get(0);
System.out.println(currentData);
} catch (IOException e) {
e.printStackTrace();
}
return baseRate;
}
I think that you need to go down another level of array to access the value you required.
JsonArray data = dataset.getJsonArray("data");
JsonArray firstPieceOfData = data.get(0);
Object firstRate = firstPieceOfData.get(1);
If you use Jackson for reading your JSON you can use the .at() method which allows you to access the node's value via a JSON Pointer Expression which in your case would be "/dataset/data/0/1"
I've truncated your json for the purpose of this demo:
String jsonString = "{\"dataset\":{\"id\":4644596,\"dataset_code\":\"30US\",\"database_code\":\"FMAC\",\"name\":\"30-Year Fixed Rate Mortgage Average in the United States\",\"description\":\"Units: Percent\\u003cbr\\u003e\\u003cbr\\u003eNot Seasonally Adjusted\",\"refreshed_at\":\"2017-12-18T04:09:32.892Z\",\"newest_available_date\":\"2017-12-14\",\"oldest_available_date\":\"1971-04-02\",\"column_names\":[\"Date\",\"Value\"],\"frequency\":\"weekly\",\"type\":\"Time Series\",\"premium\":false,\"limit\":null,\"transform\":null,\"column_index\":null,\"start_date\":\"1971-04-02\",\"end_date\":\"2017-12-14\",\"data\":[[\"2017-12-14\",3.93],[\"2017-12-07\",3.94],[\"2017-11-30\",3.9]],\"collapse\":null,\"order\":null,\"database_id\":582}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNodes = mapper.createObjectNode();
try {
jsonNodes = mapper.readTree(jsonString);
} catch (IOException e) {
//e.printStackTrace();
}
System.out.println(jsonNodes.at("/dataset/data/0/1").asDouble());// 3.93

Categories

Resources