MORE JSON AND ANDROID PROBLEMS
I'm trying to parse a JSON in my android APP. However I'm getting two
errors. First one is "Value of type string cannot be converted to JSON
Object(this error I have gotten rid of by changing a few lines of code,
but likely messed something up but I don't know yet cause the app is
running. The second error is a null pointer error. My description is after
all the code. The JSON is as follows:
{
"identified": "yes",
"Information":
[
{
"state": "Arkansas",
"type": "landlocked",
"additionalinfo": "{ search: 'online', website:
'http://states.arkansas.com', latitudeandlongitude: '93905,
63550}",
"outdoorfun": "yes",
"cold": "no"
},
{
"state": "chicago",
"type": "windy",
"additionalinfo": "{ search: 'online', website:
'http://states.chicago.com', latitudeandlongitude: '23905,
45355}",
"outdoorfun": "no",
"cold": "yes"
}
]
}
And the main part of the Activity class code is below:
// JSON Node names
private static final String TAG_IDENTIFIED = "id";
private static final String TAG_INFORMATION = "information";
private static final String TAG_STATE = "state";
private static final String TAG_TYPE = "type";
private static final String TAG_ADDITIONALINFO = "additionalinfo";
private static final String TAG_OUTDOORFUN = "outdoorfun";
private static final String TAG_COLD = "cold";
// contacts JSONArray
JSONArray information = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> stateList = new
ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
for(int i = 0; i < information.length(); i++){
information =json.getJSONArray(TAG_INFORMATION);
JSONObject c = information.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_STATE);
String type = c.getString(TAG_TYPE);
// Phone number is agin JSON Object
JSONObject additionalinfo = c.getJSONObject(ADDITIONALINFO);
String outdoorfun = c.getString(TAG_OUTDOORFUN);
String cold = c.getString(TAG_COLD);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_TYPE, type);
map.put(TAG_OUTDOORFUN, outdoorfun);
informationList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, informationList,
R.layout.list_item,
new String[] {TAG_NAME, TAG_TYPE, TAG_OUTDOORFUN }, new int[] {
R.id.name, R.id.type, R.id.outdoorfun });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView)
view.findViewById(R.id.name)).getText().toString();
String type = ((TextView)
view.findViewById(R.id.type)).getText().toString();
String outdoorfun = ((TextView)
view.findViewById(R.id.outdoorfun)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_TYPE, type);
in.putExtra(TAG_OUTDOORFUN, outdoorfun);
startActivity(in);
}
});
The Parser is here:
herepackage com.androidhive.jsonparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class JSONParser extends Activity {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And the Single List Activity is Here:
package com.androidhive.jsonparsing;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_ID = "id";
private static final String TAG_INFORMATION = "information";
private static final String TAG_STATE = "state";
private static final String TAG_TYPE = "type";
private static final String TAG_ADDITIONALINFO = "additionalinfo";
private static final String TAG_OUTDOORFUN = "outdoorfun";
private static final String TAG_COLD = "cold";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String type = in.getStringExtra(TAG_TYPE);
String outdoorfun = in.getStringExtra(TAG_OUTDOORFUN);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblType = (TextView) findViewById(R.id.type_label);
TextView lblOutdoorfun = (TextView)
findViewById(R.id.outdoorfun_label);
lblName.setText(name);
lblType.setText(type);
lblOutdoorfun.setText(outdoorfun);
}
}
I know there is alot of code on here about this already by they all use
the hive tutorial to jump straight into an array. I've tried editing this
code to get my JSON into a listview but just can't quite get it. I think
my problem is that I'm returning a JSON Object in the parser..which is
calling my very first object (Identified).. then my code immediately jumps
into the array, which there isn't one because Identified isn't the array,
information is. So how, in code, can I get the object of Identified, and
then get the object of information (thereby jumping into the information
array with the above code)? I've never done JSON parsing so it's kind of
difficult for me. I'm pretty sure this is the problem, I just don't know
how to get around it. It's driving me crazy. Everything I can find on
JSON/Android uses a JSON that begins with an array, which my code would
take care of. I just can't figure out how to do the above..get the second
object's array. Any help would be extremely appreciated. I've been racking
my brain for days trying different things. The app runs sometimes and
doesn't show anything on screen, other times the app just crashes with an
error that says String cannot convert JSONObject, and a few times I got
NULL pointer errors. Like I mentioned. I think it because I'm trying to
call the array on "Identified" when I should be calling it on
"information". But I can't figure out how to get past Identified and then
jump into the information array. I'm sure it's just a few lines of code in
the right place. but I don't know where.
No comments:
Post a Comment