Why the Views are not updated with JSON parsed information - android

I'm having Problem in updating JSON parsed informations in my Views. Nothing is problem with getting JSON text from internet it works fine. I hope parsing process also looks good. Im having problem with Displaying contents in the Views.
package rev.app.revlearningdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class JsonFromInternet extends Activity {
String jsonText, name, weather_main, description, lon, lat, temp, pressure,
humidity, temp_min, temp_max, speed, deg;
long dt, sunrise, sunset;
TextView area, info, main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
area = (TextView) findViewById(R.id.weatherAreaName);
info = (TextView) findViewById(R.id.weatherInfo);
main = (TextView) findViewById(R.id.weatherMain);
Thread net = new Thread() {
public void run() {
URL url;
BufferedReader buff = null;
StringBuilder build = new StringBuilder();
try {
url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
buff = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
for (String l; (l = buff.readLine()) != null;)
build.append(l.trim());
} catch (IOException e1) {
Log.e("REV DEMO", "ERROR");
} finally {
if (buff != null)
try {
buff.close();
} catch (IOException e) {
Log.e("REV DEMO", "ERROR");
}
jsonText = build.toString();
interrupt();
}
};
};
net.start();
if (net.getState()==Thread.State.TERMINATED) {
parseJsonText(jsonText);
area.setText(name);
info.setText(description + "\n" + "Longitude, Lattitude " + lon
+ ", " + lat + "\nTemperature " + temp + "\n(Min:"
+ temp_min + ", Max:" + temp_max + ")\nPressure "
+ pressure + "\nHumidity " + humidity + "\nWind Speed "
+ speed + ", direction " + deg);
main.setText(weather_main);
}
}
private void parseJsonText(String jsonFromInternet) {
JSONObject root, coord, main, wind, sys, weather;
try {
root = new JSONObject(jsonFromInternet);
coord = root.getJSONObject("coord");
lon = coord.optString("lon");
lat = coord.optString("lat");
main = root.getJSONObject("main");
temp = main.optString("temp");
pressure = main.optString("pressure");
humidity = main.optString("humidity");
temp_min = main.optString("temp_min");
temp_max = main.optString("temp_max");
wind = root.getJSONObject("wind");
speed = wind.optString("speed");
deg = wind.optString("deg");
sys = root.getJSONObject("sys");
sunrise = sys.optLong("sunrise");
sunset = sys.optLong("sunset");
dt = root.optLong("dt");
name = root.optString("name");
weather = root.optJSONArray("weather").getJSONObject(0);
weather_main = weather.optString("main");
description = weather.optString("description");
} catch (JSONException e) {
e.printStackTrace();
}
}
}

You start asynchronous Thread to download the JSON and it means that your views are getting updated immediately (when your jsonText is not initialized yet).
Move updating your views into the end of run() method and update your views when you finished parsing data, not earlier. Warning: to call setText from thread you will have to use runOnUiThread method.
Thread net = new Thread() {
public void run() {
URL url;
BufferedReader buff = null;
StringBuilder build = new StringBuilder();
try {
url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
buff = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
for (String l; (l = buff.readLine()) != null;)
build.append(l.trim());
// parse and update views now:
jsonText = build.toString();
parseJsonText(jsonText);
runOnUiThread(new Runnable() {
#Override
public void run() {
area.setText(name);
info.setText(description + "\n" + "Longitude, Lattitude " + lon
+ ", " + lat + "\nTemperature " + temp + "\n(Min:"
+ temp_min + ", Max:" + temp_max + ")\nPressure "
+ pressure + "\nHumidity " + humidity + "\nWind Speed "
+ speed + ", direction " + deg);
main.setText(weather_main);
}
});
} catch (IOException e1) {
Log.e("REV DEMO", "ERROR");
} finally {
if (buff != null)
try {
buff.close();
} catch (IOException e) {
Log.e("REV DEMO", "ERROR");
}
interrupt();
}
};
};

Related

How to open epub files with Images and contents and when we click on contents then it move to particular part

i want to open ebub files either in webview or by something else but content click and images,videos should be there
-I have tried using webview but images cant display in that
textView.setText(Html.fromHtml(data, new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
String imageAsStr = source.substring(source.indexOf(";base64,") + 8);
byte[] imageAsBytes = Base64.decode(imageAsStr, Base64.DEFAULT);
Bitmap imageAsBitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
int imageWidthStartPx = (pxScreenWidth - imageAsBitmap.getWidth()) / 2;
int imageWidthEndPx = pxScreenWidth - imageWidthStartPx;
Drawable imageAsDrawable = new BitmapDrawable(getResources(), imageAsBitmap);
imageAsDrawable.setBounds(imageWidthStartPx, 0, imageWidthEndPx, imageAsBitmap.getHeight());
return imageAsDrawable;
}
}, null));
-i tried this also but in this images are display but content click is no there
Use this code provided you have necessary libraries and sampleepubfile.epub in your assets...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.TOCReference;
import nl.siegmann.epublib.epub.EpubReader;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.webkit.WebView;
public class EPubDemo extends Activity {
WebView webview;
String line, line1 = "", finalstr = "";
int i = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
AssetManager assetManager = getAssets();
try {
// find InputStream for book
InputStream epubInputStream = assetManager
.open("sampleepubfile.epub");
// Load Book from inputStream
Book book = (new EpubReader()).readEpub(epubInputStream);
// Log the book's authors
Log.i("author", " : " + book.getMetadata().getAuthors());
// Log the book's title
Log.i("title", " : " + book.getTitle());
/* Log the book's coverimage property */
// Bitmap coverImage =
// BitmapFactory.decodeStream(book.getCoverImage()
// .getInputStream());
// Log.i("epublib", "Coverimage is " + coverImage.getWidth() +
// " by "
// + coverImage.getHeight() + " pixels");
// Log the tale of contents
logTableOfContents(book.getTableOfContents().getTocReferences(), 0);
} catch (IOException e) {
Log.e("epublib exception", e.getMessage());
}
String javascrips = "";
try {
// InputStream input = getResources().openRawResource(R.raw.lights);
InputStream input = this.getAssets().open(
"poe-fall-of-the-house-of-usher.epub");
int size;
size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
javascrips = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
// String html = readFile(is);
webview.loadDataWithBaseURL("file:///android_asset/", javascrips,
"application/epub+zip", "UTF-8", null);
}
#SuppressWarnings("unused")
private void logTableOfContents(List<TOCReference> tocReferences, int depth) {
if (tocReferences == null) {
return;
}
for (TOCReference tocReference : tocReferences) {
StringBuilder tocString = new StringBuilder();
for (int i = 0; i < depth; i++) {
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
Log.i("TOC", tocString.toString());
try {
InputStream is = tocReference.getResource().getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while ((line = r.readLine()) != null) {
// line1 = Html.fromHtml(line).toString();
Log.v("line" + i, Html.fromHtml(line).toString());
// line1 = (tocString.append(Html.fromHtml(line).toString()+
// "\n")).toString();
line1 = line1.concat(Html.fromHtml(line).toString());
}
finalstr = finalstr.concat("\n").concat(line1);
// Log.v("Content " + i, finalstr);
i++;
} catch (IOException e) {
}
logTableOfContents(tocReference.getChildren(), depth + 1);
}
webview.loadDataWithBaseURL("", finalstr, "text/html", "UTF-8", "");
}
}
I have tried this and its working for me

Concatenation inside try catch

try {
final List<NetworkType> dataReceived = getData();
int i = 0;
//Array Iteration
for(final NetworkType networkType : dataReceived) {
i++;
if (i > 3) {
Toast.makeText(getApplicationContext(), "Done!!", Toast.LENGTH_SHORT);
} else {
String mCell1CID = networkType.getCell1CID();
String mCell1LAC = networkType.getCell1LAC();
String mCell1MCC = networkType.getCell1MCC();
String mCell1MNC = networkType.getCell1MNC();
String mCell1CI = networkType.getCell1CI();
String mCell1TAC = networkType.getCell1TAC();
//API requestBody
String url = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyA8NAA3dUpECFn2j6pdcQT3wgqUM98UZ2Q";
String cellID = null;
String locationAreaCode = null;
if (mCell1CID.equals("") && mCell1LAC.equals("")) {
cellID = mCell1CI;
locationAreaCode = mCell1TAC;
} else if (mCell1CI.equals("") && mCell1TAC.equals("")) {
cellID = mCell1CID;
locationAreaCode = mCell1LAC;
} else {
Log.d("GeoL", "3");
}
String requestBody =
"{" +
"\"cellTowers\":[" +
"{" +
"\"cellId\" :" + cellID + "," +
"\"locationAreaCode\" :" + locationAreaCode + "," +
"\"mobileCountryCode\" :" + "\"" + mCell1MCC + "\"" + "," +
"\"mobileNetworkCode\" :" + "\"" + mCell1MNC + "\"" +
"}" +
"]" +
"}";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(String.valueOf(response));
JSONObject latitude = jsonObject.getJSONObject("location");
String lat = latitude.getString("lat");
String lng = latitude.getString("lng");
String acc = jsonObject.getString("accuracy");
if (!dataReceived.listIterator().hasNext()){
String print;
print = String.format("%s%s", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
} else {
String print;
print = String.format("%s%s,", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response", "error" + error.toString());
}
});
queue.add(jsObjRequest);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I need to concat the received value to the print variable.
But this the error which i receive
print needs to be initialized is what I receive.
also if declared outside the try/catch block it requires it to be final.
What to do?
just use String print = null; when you declare print
You are providing a value that is not initialized to the String.format
You need to initialize the variable "print" with what you want to be used in the String.format (for example an empty String) :
String print= ""
Or use String Builder:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("1");
stringBuilder.append("2");
String finalString = stringBuilder.toString();

How to display image based on weather from drawable

i would like to display an image based on the weather.
The image that I'm getting from is from drawable.
For example :
if the code = 30, it will display rainy day icon
I'm retrieving it from
<yweather:condition text="Light Rain with Thunder" code="4" temp="25" date="Thu, 18 Jul 2013 7:58 am SGT" />
Here is my code
MainActivity.java
public class MainActivity extends Activity {
TextView weather;
ImageView image;
class MyWeather{
String conditiontext;
String conditiondate;
String numberOfForecast;
String forecast;
public String toString(){
return "\n- "
+ "Weather:" + image + "\n"
+ "Condition: " + conditiontext + "\n"
+ conditiondate +"\n"
+ "\n"
+ "number of forecast: " + numberOfForecast + "\n"
+ forecast;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weather = (TextView)findViewById(R.id.weather);
image = (ImageView)findViewById(R.id.image);
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.toString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
if(conditionNode.getTextContent().equals("11")){
image.setImageResource(R.drawable.logo);
}
else {
image.setImageResource(R.drawable.old);
}
myWeather.conditiontext = conditionNode.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString();
myWeather.conditiondate = conditionNode.getAttributes()
.getNamedItem("date")
.getNodeValue()
.toString();
//Added to get elements of <yweather:forecast.../>
NodeList forecastList = srcDoc.getElementsByTagName("yweather:forecast");
myWeather.forecast = "";
if(forecastList.getLength() > 0){
myWeather.numberOfForecast = String.valueOf(forecastList.getLength());
for(int i = 0; i < forecastList.getLength(); i++){
Node forecastNode = forecastList.item(i);
myWeather.forecast +=
forecastNode
.getAttributes()
.getNamedItem("date")
.getNodeValue()
.toString() + " " +
forecastNode
.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString() +
" High: " + forecastNode
.getAttributes()
.getNamedItem("high")
.getNodeValue()
.toString() +
" Low: " + forecastNode
.getAttributes()
.getNamedItem("low")
.getNodeValue()
.toString() + "\n";
}
}else{
myWeather.numberOfForecast = "No forecast";
}
return myWeather;
}
private Document convertStringToDocument(String src){
Document dest = null;
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(MainActivity.this,
e1.toString(), Toast.LENGTH_LONG).show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return dest;
}
private String QueryYahooWeather(){
String qResult = "";
String queryString = "http://weather.yahooapis.com/forecastrss?w=1062617&u=c";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(queryString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return qResult;
}
}
Still not working?
I made the project myself, and if you do it like this it will work. :)
The R.id and drawables are not the same, you need to change those to make it work
TextView weather;
ImageView forecast;
private static Handler mHandler = new Handler();
class MyWeather{
String conditiontext;
String conditiondate;
String numberOfForecast;
String forecast;
public String forecastToString(){
return "\n- "
+ "Weather: " +"you wanted to have something here, I just dont understand what. " + "\n"
+ "Condition: " + conditiontext + "\n"
+ conditiondate +"\n"
+ "\n"
+ "number of forecast: " + numberOfForecast + "\n"
+ forecast;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weather = (TextView)findViewById(R.id.textView1);
forecast = (ImageView)findViewById(R.id.imageView1);
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.forecastToString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
String weatherCode = conditionNode.getAttributes()
.getNamedItem("code")
.getNodeValue()
.toString();
if(weatherCode.equals("28")){
mHandler.post(new Runnable() {
#Override
public void run() {
// This gets executed on the UI thread so it can safely modify
// Views
forecast.setImageResource(R.drawable.ic_launcher);
}
});
}
...
I found some problem in your code there is two image view
Image = (ImageView)findViewById(R.id.image);
Problem - : name of the image missing
ImageView foreImage = new ImageView(this);
foreImage.setImageResource(R.drawable.logo);
//Why are you using dynamic imageview
You should use Handler Thread for display image.

How do I structure my data to switch from using ParseJsonArray/ParseJsonObject to using GSON.fromJson(...)

I have been working with GSON to try and parse a Json response I am getting from a CakePHP server for about a week. Here is what the response looks like :
[{"BaseObject": {"field1":"1","field2":"1639","field3":"10","field4":"1","field5":"12","field6":"10.765984","field7":"-25.768357","field8":"1327790850"}},{"BaseObject":{"field1":"2","field2":"1934","field3":"19","field4":"30","field5":"2","field6":"10.758662","field7":"-25.769684","field8":"1327790850"}},{"BaseObject":{"field1":"3","field2":"2567","field3":"33","field4":"6","field5":"98","field6":"10.758786","field7":"-25.769843","field8":"1327790850"}},{"BaseObject":{"field1":"4","field2":"0","field3":"33","field4":"7","field5":"0","field6":"10.758786","field7":"-20.769843","field8":"1327790850"}},{"BaseObject":{"field1":"5","field2":"1097","field3":"33","field4":"1","field5":"0","field6":"15.758786","field7":"50.769843","field8":"1327790850"}},{"BaseObject":{"field1":"6","field2":"1936","field3":"50","field4":"0","field5":"9","field6":"19.234987","field7":"-67.340065","field8":"1327798560"}}]
I used a plugin for Notepad++ to verify that the response is valid Json and it is.
First I tried this function:
public static List<BaseObject> parserInputStreamGson(InputStream stream)
{
List<BaseObject> objList = new ArrayList<BaseObject>();
if(stream != null){
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG,"Trying to Parse Reader");
try{
objList = gson.fromJson(r, new TypeToken<List<BaseObject>>() {}.getType() );
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage() );
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage() );
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage() );
}
}
}
Log.d(TAG,"BaseObject[] = " + objList.toString());
return objList;
}
Then I tried this function:
public static BaseObject[] parserInputStreamGsonArray(InputStream stream)
{
BaseObject[] objectArray = null;
if (stream != null) {
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG, "Trying to Parse Reader");
try {
objectArray = gson.fromJson(r, new TypeToken<Event[]>() {}.getType());
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage());
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage());
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage());
}
}
}
if(eventArray != null){
for(int m=0;m<eventArray.length;m++){
Log.d(TAG, "objectArray[" + String.valueOf(m) + "] = " + objectArray[m].toString());
}
}
return objectArray;
}
And in both cases Gson returned 5 objects, but all of the fields were set to zero.
Finally I got this function to work, but it feels clunky.
public static List<BaseObject> ParseInputStream(InputStream stream) {
Reader r = new InputStreamReader(stream);
List<BaseObject> baseObjectList = new ArrayList<BaseObject>();
try {
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(r).getAsJsonArray();
JsonObject topObject = new JsonObject();
JsonObject subObject = new JsonObject();
for (int m = 0; m < array.size(); m++) {
if (array.get(m).isJsonObject()) {
topObject = array.get(m).getAsJsonObject();
if (topObject.get("BaseObject").isJsonObject()) {
subObject = topObject.get("BaseObject").getAsJsonObject();
BaseObject baseobject = new BaseObject();
baseobject.field1 = subObject.get("field1").getAsLong();
baseobject.field2 = subObject.get("field2").getAsInt();
baseobject.field3 = subObject.get("field3").getAsLong();
baseobject.field4 = subObject.get("field4").getAsInt();
baseobject.field5 = subObject.get("field5").getAsInt();
baseobject.field6 = subObject.get("field6").getAsDouble();
baseobject.field7 = subObject.get("field7").getAsDouble();
baseobject.field8 = subObject.get("field8").getAsLong();
baseObjectList.add(baseobject);
} else {
Log.e(TAG, "topObject[" + String.valueOf(m)+ "].subObject is not a JsonObject");
}
} else {
Log.e(TAG, "Array # " + String.valueOf(m)+ " is not a JsonObject!");
}
}
} catch (Exception ex) {
Log.e(TAG, "Exception thrown = " + ex.toString());
ex.printStackTrace();
}
return baseObjectList;
}
Here is the class I created for BaseObject.
public class BaseObject {
#SerializedName("field1")
public long field1;
#SerializedName("field2")
public int field2;
#SerializedName("field3")
public long field3;
#SerializedName("field4")
public int field4;
#SerializedName("field5")
public int field5;
#SerializedName("field6")
public double field6;
#SerializedName("field7")
public double field7;
#SerializedName("field8")
public long field8;
#Override
public String toString() {
return "(" +
"field1= " + String.valueOf(this.field1) + ", " +
"field2= " + String.valueOf(this.field2) + ", " +
"field3= " + String.valueOf(this.field3) + ", " +
"field4= " + String.valueOf(this.field4) + ", " +
"field5= " + String.valueOf(this.field5) + ", " +
"field6= " + String.valueOf(this.field6) + ", " +
"field7= " + String.valueOf(this.field7) + ", " +
"field8= " + String.valueOf(this.field8) +
")";
}
}
Can anyone tell me how I need to structure my data classes in order use Gson.fromJson to work.
Since your response is actually List<BaseObject>, you should be using
List baseObjectList = new Gson().fromJson(r,new TypeToken>() {}.getType())
Also I should mention that, you do not really need to use the #SerializedName annotations since your attribute names in the json reply and in the class are same.
UPDATE:
Oops.. Sorry, I should have tried your code before answering. Please refer to the following code. Everything boiled down to the Structuring of classes.
public class Sample {
public static class Wrapper{
private BaseObject BaseObject;
#Override
public String toString() {
return BaseObject == null? null : BaseObject.toString();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String json = "[{\"BaseObject\": {\"field1\":\"1\",\"field2\":\"1639\",\"field3\":\"10\",\"field4\":\"1\",\"field5\":\"12\",\"field6\":\"10.765984\",\"field7\":\"-25.768357\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"2\",\"field2\":\"1934\",\"field3\":\"19\",\"field4\":\"30\",\"field5\":\"2\",\"field6\":\"10.758662\",\"field7\":\"-25.769684\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"3\",\"field2\":\"2567\",\"field3\":\"33\",\"field4\":\"6\",\"field5\":\"98\",\"field6\":\"10.758786\",\"field7\":\"-25.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"4\",\"field2\":\"0\",\"field3\":\"33\",\"field4\":\"7\",\"field5\":\"0\",\"field6\":\"10.758786\",\"field7\":\"-20.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"5\",\"field2\":\"1097\",\"field3\":\"33\",\"field4\":\"1\",\"field5\":\"0\",\"field6\":\"15.758786\",\"field7\":\"50.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"6\",\"field2\":\"1936\",\"field3\":\"50\",\"field4\":\"0\",\"field5\":\"9\",\"field6\":\"19.234987\",\"field7\":\"-67.340065\",\"field8\":\"1327798560\"}}]";
List<Wrapper> results = new Gson().fromJson(json,new TypeToken<List<Wrapper>>(){}.getType());
System.out.println(results);
}
}
Just curious, do you have the liberty to change the JSON reply coming from server? IMHO, Its structure is a little complicated.

Android dom parser error

I'm facing a particular problem while parsing xml so the parser works fine until it encouters <Url/> tag which contains no value, I already made the test il my code :
static final String ImageHotel = "Url";
...
else if (name.equalsIgnoreCase("ImageHotel")){
message.setHotelImage(property.getFirstChild().getNodeValue());
if (!marchand.getImgHtlUrl().equalsIgnoreCase("")){
message.setHotelImageLink(new URL(marchand.getImgHtlUrl() + property.getFirstChild().getNodeValue()));
}else{
message.setHotelImageLink(new URL("http://localhost/noimage.jpg"));
}
}
This keep throwing error even when i tried to bypass by surrounding with try/catch..
any help is welcome
thanks.
Houssem.
I have reference to parse this file try to add your own data and get tag value....
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class NewsParsing {
NewsBeen Objnewsbeen;
Vector<NewsBeen> vectParse;
public NewsParsing() {
System.out.println("Constructor is calling Now ...");
try {
vectParse = new Vector<NewsBeen>();
// http://www.npr.org/rss/rss.php?id=1001
URL url = new URL(
"http://www.npr.org/rss/rss.php?id=1001");
URLConnection con = url.openConnection();
System.out.println("Connection is : " + con);
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
System.out.println("Reader :" + reader);
String inputLine;
String fullStr = "";
while ((inputLine = reader.readLine()) != null)
fullStr = fullStr.concat(inputLine + "\n");
InputStream istream = url.openStream();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
System.out.println("Builder : " + builder);
Document doc = builder.parse(istream);
System.out.println("Doc is : " + doc);
doc.getDocumentElement().normalize();
System.out.println("After Normlize : " + doc);
System.out.println("Root is : "
+ doc.getDocumentElement().getNodeName());
System.out
.println("-------------------------------------------------------------------------------------------------------------");
Element element = doc.getDocumentElement();
parseFile(element);
for (int index1 = 0; index1 < vectParse.size(); index1++) {
NewsBeen ObjNB = (NewsBeen) vectParse.get(index1);
System.out.println("Item No : " + index1);
System.out.println();
System.out.println("Title is : " + ObjNB.title);
System.out.println("Description is : " + ObjNB.description);
System.out.println("Pubdate is : " + ObjNB.pubdate);
System.out.println("Link is : " + ObjNB.link);
System.out.println("Guid is : " + ObjNB.guid);
System.out.println();
System.out
.println("-------------------------------------------------------------------------------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void parseFile(Node node) {
NodeList nodelist = node.getChildNodes();
for (int index = 0; index < nodelist.getLength(); index++) {
Node nodefromList = nodelist.item(index);
if (nodefromList.getNodeType() == Node.ELEMENT_NODE) {
// System.out.println("node.getNodeType() : " +
// nodefromList.getNodeType());
// System.out.println("Node is : " + node.getNodeName());
if (nodefromList.getNodeName().equalsIgnoreCase("item")) {
Objnewsbeen = new NewsBeen();
vectParse.addElement(Objnewsbeen);
}
if (nodefromList.hasChildNodes()) {
if (nodefromList.getChildNodes().item(0).getNodeName()
.equals("#text")) {
if (!nodefromList.getChildNodes().item(0)
.getNodeValue().trim().equals("")
&& Objnewsbeen != null)
if (nodefromList.getNodeName().equalsIgnoreCase(
"title")) {
Objnewsbeen.title = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("description")) {
Objnewsbeen.description = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("pubDate")) {
Objnewsbeen.pubdate = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("link")) {
Objnewsbeen.link = nodefromList.getChildNodes()
.item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("guid")) {
Objnewsbeen.guid = nodefromList.getChildNodes()
.item(0).getNodeValue();
} else {
// System.out.println();
}
}
parseFile(nodefromList);
}
}
}
}
public static void main(String[] args) {
new NewsParsing();
}
}
The NewsBeen class is::
public class NewsBeen {
public String title;
public String description;
public String pubdate;
public String link;
public String guid;
}
I told you that surrounding with try/catch did not work, so, now it does, because i had to track the NullPointerException instead of simple Exception, like this :
try{
message.setHotelImage(property.getFirstChild().getNodeValue());
}catch(NullPointerException nEx){
marchand.setImgHtlUrl("");
}
thank you guys and sorry for this alert ;)

Categories

Resources