Im loading data (url) from a json file to a WebView (with gson). When i load the data from a different Activity through a static variable (WebView) i get the 12th url entry of my JSON file. When im loading the data to a inner WebView of my Activity i get the 1st url like it should be.
OtherActivity.mWebView1.loadUrl(JsonData.getUrl()); --> here i get the 12th url
mWebView2.loadUrl(JsonData.getUrl()); --> here i get the 1st url
They both use the same method to load the Data from the JSON file (gson):
#SerializedName("url")
#Expose
private String url;
public String getUrl() {return url;}
public void setUrl(String url) {
this.url = url;
}
Here my LoadJsonFromAsset class:
public class SwipeUtils {
public static List<AdInfo> loadProfiles(Context context){
try{
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
JSONArray array = new JSONArray(loadJSONFromAsset(context, "adInfo.json"));
List<AdInfo> adInfoList = new ArrayList<>();
adInfoList.indexOf("");
for(int i=0;i<array.length();i++){
AdInfo adInfo = gson.fromJson(array.getString(i), AdInfo.class);
adInfoList.add(adInfo);
Log.d("test",adInfo.toString());
}
return adInfoList;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
private static String loadJSONFromAsset(Context context, String jsonFileName) {
String json = null;
InputStream is=null;
try {
AssetManager manager = context.getAssets();
Log.d(TAG,"path "+jsonFileName);
is = manager.open(jsonFileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
The problem was the method where i set the loadUrl(). It was in a loop an in the time where the loadUrl() worked it was already at the 12th entry.
Related
I want to get a list of JSON objects with JSON from a API. For example affiliate.itunes
but with gson I can't go throw a jsonObject and i have to use java JSONObject and JSONArray class for this mater.
Is it possible to handle this completely with gson lib ?
This is json file that I copied into my android raw folder
and this is my code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
InputStream inputStream = getResources().openRawResource(R.raw.file);
String jsonStr = streamToString(inputStream);
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("results");
Type type = new TypeToken<List<BandJsonResult>>(){}.getType();
List<BandJsonResult> jsonResults = gson.fromJson(jsonArray.toString(),type);
for(int i = 0 ; i < jsonResults.size() ; i++){
Log.e("JSON " + i ,jsonResults.get(i).toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String streamToString(InputStream stream) {
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder result = new StringBuilder();
String line = "";
try {
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
}catch (IOException ex){
ex.printStackTrace();
}
return result.toString();
}
}
Gson uses reflection by default to (de-)serialize classes (unless you provide custom adapters), see also this example in the Gson user guide. Based on the screenshot you could add these two classes:
// You can give these classes any name
class ApiResponse {
// Uses the field names for (de-)serialization by default, but you can also
// specify custom names using #SerializedName
private int resultCount;
private List<BandResult> results;
}
class BandResult {
// You can also use enums and then either name the enum constants the same
// as the values, or annotate the enum constants with #SerializedName
private String wrapperType;
private String kind;
private int artistId;
...
}
And then use them when calling Gson.fromJson:
ApiResponse apiResponse = gson.fromJson(jsonStr, ApiResponse.class);
When I run my app, In logcat, "Problem parsing the earthquake Json results
org.json.JSONException: No value for fields"
Could you check my JSON code..? I'm beginner of JSON Parsing, So I searched a lot inf But I'm not sure about my code.
public class Utils {
private static List<News> extractFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject response = baseJsonResponse.getJSONObject("response");
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentNews = jsonArray.getJSONObject(i);
JSONObject fields = currentNews.getJSONObject("fields");
Drawable thumbnail = LoadImageFromUrl (fields.getString("thumbnail"));
String section = currentNews.getString("sectionName");
String title = currentNews.getString("webTitle");
String url = currentNews.getString("webUrl");
String date = currentNews.getString("webPublicationDate");
news.add(new News( section, title, url, date,thumbnail));
}
return news;
} catch (JSONException e) {
Log.e("Utils", "Problem parsing the news Json results", e);
}
return null;
}
private static Drawable LoadImageFromUrl(String imageurl) {
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = new URL(imageurl).openStream();
drawable = Drawable.createFromStream(inputStream, null);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return drawable;
}
}
Try this to validate
Problem occur may be you dont have a field jsonobject in your json list. It may be not present in the some of other jsonobjects. So check if jsonobject has actual field jsonobject before parsing.
Use this condition whenever your json value might give null sometimes.
if(currentNews.has("fields"))
{
JSONObject fields = currentNews.getJSONObject("fields");
}
else
{
Log.d("JSON_TAG","NO FIELD JSON OBJECT");
}
I am sorry for I am a beginner.
I try to put the value into string name[], int age [], int hand[],
but all the value is null.
I don't know which part have problem. Since i learn this from youtube.
I just want to store the data to array.
Thank you
public class main extends AppCompatActivity {
String oName[] = new String [];
int oAge [] = new int [];
int oHand [] = new int [];
protected void onCreate(Bundle savedInstanceState) {...}
private class DownloadTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground (String... values) {
InputStream is = null;
String result = ""; //Get json?
String line;
try {
URL ua = new URL("https://api.myjson.com/bins/r5kim"); //json address
HttpURLConnection conn = (HttpURLConnection) ua.openConnection();
conn.setRequestMethod("GET");
conn.connect();
is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
JSONObject jo = new JSONObject(result); //get json
JSONArray op = jo.getJSONArray("opponents"); //json array?? parse??
for(int i = 0; i < op.length(); i++) {
oName[i] = op.getJSONObject(i).getString("name"); //Get null
oAge[i] = op.getJSONObject(i).getInt("age"); //Get null
oHand[i] = op.getJSONObject(i).getInt("hand"); //Get null
}
} catch (MalformedURLException e) { //exception
e.printStackTrace();
} catch (IOException e) { //exception
e.printStackTrace();
} catch (JSONException e) { //exception
e.printStackTrace();
}
return null;
}
}
Since you didn't post the json string it is hard to determinate what you are doing wrong.
The best advice I can give you is to check out gson library which is the most common json parser on Android (there are obv more, this is the one I use). how to add reference.
Watching videos, searching on google and also here on SO you will find thousands of "how to use gson posts", but anyway I will give you the fastest "how to" for it.
1. Assume you have a string like this:
{
"id":1,
"name":"Little Mouse"
}
2. Create an object matching the one passed by json string
public class MyObject{
private int id;
private String name;
//getters and setters
}
3. Now initialize gson and parse the string to the desired object
//Initialize Gson object with GsonBuilder (you can customize it, you will learn)
Gson gson = new GsonBuilder().create();
//parse your string using an object matching your output
MyObject myObject = gson.fromJson(myJsonString, MyObject.class);
It is pretty simple, but if you need help, ask freely
Post scriptum:
you can obiouvsly parse any kind of class, with also custom parameters and nested classes. You just have to create a model class with the parameters you need written with the same name (or you can explicit the desired name) and with the same property type (int, string, ...)
This is your model:
public class myJsonModel{
private List<Opponent> opponents;
//getters and setters
}
public class Opponent{
private String name;
private String age;
private String hand;
//getters and setters
}
So your result should be
myJsonModel myObject = gson.fromJson(myJsonString, myJsonModel.class);
I want to fetch json data from json object.
My json data is:{"avg":2.5} and my android code is
public class AsyncTaskParseJson extends AsyncTask < String, String, String > {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.bsservicess.com/photoUpload/star_avg.php?bookName=" + book_name;
// contacts JSONArray
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String...arg0) {
try {
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
JSONObject dataJsonArr = json.getJSONObject(str);
String c = dataJsonArr.getString("avg");
na = c;
starts = Float.parseFloat(c);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
super.onPostExecute(strFromDoInBg);
netRate.setRating(starts);
Toast.makeText(mybookview.this, Float.toString(starts), Toast.LENGTH_SHORT).show();
}
But somehow its not working.I have trie every tutorial and evrything but nothing works.plz help me
your getting the json data in response is as {"avg":2.5}
simple remove the below code
JSONObject dataJsonArr = json.getJSONObject(str);
String c = dataJsonArr.getString("avg");
with below line
String c = json.getString("avg");
this is for simple get data from url example:
Parse JSON from HttpURLConnection object
and if you want use library then try Volley:
tutorial link:
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
A very simple solution to your problem
String str = "{ \"avg\" :0 }";
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(str);
String value = object.get("avg").getAsString();
But first of all you have to correct the warning in your backend.
EDIT the complete solution
public class AsyncTaskParseJson extends AsyncTask < String, String, String > {
HttpURLConnection urlConnection;
#Override
protected String doInBackground(String...args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://www.bsservicess.com/photoUpload/star_avg.php?bookName=" + book_name);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader( in ));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(result);
String value = object.get("avg").getAsString();
}
}
But first of all remove the warning from the web response!
I have a rss feed reader application. The goal is to store the title and image for each item in a custom object named RSSItem, and oll the RSSItem objects in another object named RSSFeed. The problem is that if an item element does not have an enclosure element SaxException is thrown. How should I handle the errors with this parser? Here is the parser code:
public class Parser {
private final String RSS_ELEMENT = "rss";
private final String CHANNEL_ELEMENT = "channel";
private final String ITEM_ELEMENT = "item";
private final String ENCLOSURE_ELEMENT = "enclosure";
private final String TITLE_ELEMENT = "title";
private final String URL_ATTRIBUTE = "url";
private final String TYPE_ATTRIBUTE = "type";
private final String IMAGE_TYPE = "image/jpeg";
RSSItem rssItem;
RSSFeed rssFeed;
final URL mFeedUrl;
public Parser(String feedUrl) {
try {
mFeedUrl = new URL(feedUrl);
} catch (MalformedURLException e) {
Log.e(e.getClass().getSimpleName(), e.getMessage());
throw new RuntimeException(e);
}
rssFeed = new RSSFeed();
}
protected InputStream getInputStream() {
try {
return mFeedUrl.openConnection().getInputStream();
} catch (IOException e) {
Log.e(e.getClass().getSimpleName(), e.getMessage());
return null;
}
}
public RSSFeed parse() {
InputStream istream = getInputStream();
RootElement root = new RootElement(RSS_ELEMENT);
Element channel = root.requireChild(CHANNEL_ELEMENT);
Element itemElement = channel.requireChild(ITEM_ELEMENT);
Element enclosure = itemElement.requireChild(ENCLOSURE_ELEMENT);
Element title = itemElement.requireChild(TITLE_ELEMENT);
enclosure.setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
String imageType = attrs.getValue(TYPE_ATTRIBUTE);
if (imageType.equals(IMAGE_TYPE)) {
try {
String imageUrl = attrs.getValue(URL_ATTRIBUTE);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
rssItem.setImage(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
title.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
rssItem.setTitle(body);
}
});
itemElement.setStartElementListener(new StartElementListener() {
public void start(Attributes arg0) {
rssItem = new RSSItem();
}
});
itemElement.setEndElementListener(new EndElementListener() {
public void end() {
rssFeed.addItem(rssItem);
}
});
try {
Xml.parse(istream, Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
e.printStackTrace();
}
return rssFeed;
}
}
I would not recommend trying to implement your own RSS parser , but rather using a standard library for that.
It's fairly easy to setup an implementation of a SAX parser but the hard part is to be able to parse any and every feed under the sun.
You need to cater to all formats RSS 1, RSS 2, Atom etc. Even then you will have to contend with poorly formatted feeds.
I had faced similar problems in the past so decided to do my feed parsing on a server and just get the parsed contents. This allows me to run more complex libraries and parser which I can modify without pushing out updates for my app.
I have the following service running on AppEngine which allows for a much simpler XML / JSON parsing at your end. There is a fixed and simple structure to the response. You can use this for parsing
http://evecal.appspot.com/feedParser
You can send both POST and GET requests with the following parameters.
feedLink : The URL of the RSS feed response : JSON or XML as the response format
Examples:
For a POST request
curl --data-urlencode "feedLink=http://feeds.bbci.co.uk/news/world/rss.xml" --data-urlencode "response=json" http://evecal.appspot.com/feedParser
For GET request
evecal.appspot.com/feedParser?feedLink=http://feeds.nytimes.com/nyt/rss/HomePage&response=xml
My android app "NewsSpeak" uses this too.