I am trying to parse json object to populate it into list view,but i am facing some problem please help
I am getting NullpointerException
here is my full code:
I am parsing data from the following url
code for parsing data
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser(){
}
public JSONObject getJSONFromUrl(String url){
//making Http request
try{
//default httpclient
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;
}
}
here is activity code
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://www.kaverisoft.com/careers/assignments/android/a1.php";
// JSON NAme Node
private static final String TAG_BOOK = "book";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_AUTHORS = "authors";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_PRICE = "price";
//Book JSONArray
JSONArray book = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// HashMap for ListView
ArrayList<HashMap<String, String>> bookList = new ArrayList<HashMap<String, String>>();
// creating Json parser instance
JSONParser jParser = new JSONParser();
// getting Json String from url
JSONObject json = jParser.getJSONFromUrl(url);
try{
// getting array of books
book = json.getJSONArray(TAG_BOOK);
// looping through all books
for(int i=0;i<book.length();i++){
JSONObject c = book.getJSONObject(i);
// storing each json item in variable
String title = c.getString(TAG_TITLE);
String price = c.getString(TAG_PRICE);
String authors = c.getString(TAG_AUTHORS);
String id = c.getString(TAG_ID);
String description = c.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_PRICE, price);
map.put(TAG_AUTHORS, authors);
map.put(TAG_DESCRIPTION, description);
bookList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
// Updating Parsed Data into ListView
ListAdapter adapter = new SimpleAdapter(this, bookList,
R.layout.list_item,
new String[]{TAG_TITLE,TAG_DESCRIPTION,TAG_AUTHORS } , new int[] {
R.id.title,R.id.description,R.id.author });
setListAdapter(adapter);
// selecting single list view 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 title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String authors = ((TextView) view.findViewById(R.id.author)).getText().toString();
String description = ((TextView) view.findViewById(R.id.description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_AUTHORS, authors);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
}
}
I am trying to parse only book object
Please solve my problem.
LogCat detail’s
08-24 00:56:48.202: W/dalvikvm(949): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
08-24 00:56:48.263: E/AndroidRuntime(949): FATAL EXCEPTION: main
08-24 00:56:48.263: E/AndroidRuntime(949): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sree.androidjsonparser/com.sree.androidjsonparser.AndroidJSONParsingActivity}: java.lang.NullPointerException
08-24 00:56:48.263: E/AndroidRuntime(949): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-24 00:56:48.263: E/AndroidRuntime(949): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-24 00:56:48.263: E/AndroidRuntime(949): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-24 00:56:48.263: E/AndroidRuntime(949): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-24 00:56:48.263: E/AndroidRuntime(949): at android.os.Handler.dispatchMessage(Handler.java:99)
08-24 00:56:48.263: E/AndroidRuntime(949): at android.os.Looper.loop(Looper.java:123)
08-24 00:56:48.263: E/AndroidRuntime(949): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-24 00:56:48.263: E/AndroidRuntime(949): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 00:56:48.263: E/AndroidRuntime(949): at java.lang.reflect.Method.invoke(Method.java:521)
08-24 00:56:48.263: E/AndroidRuntime(949): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-24 00:56:48.263: E/AndroidRuntime(949): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-24 00:56:48.263: E/AndroidRuntime(949): at dalvik.system.NativeStart.main(Native Method)
08-24 00:56:48.263: E/AndroidRuntime(949): Caused by: java.lang.NullPointerException
08-24 00:56:48.263: E/AndroidRuntime(949): at com.sree.androidjsonparser.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:62)
08-24 00:56:48.263: E/AndroidRuntime(949): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-24 00:56:48.263: E/AndroidRuntime(949): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-24 00:56:48.263: E/AndroidRuntime(949): ... 11 more
08-24 00:56:53.812: I/Process(949): Sending signal. PID: 949 SIG: 9
Your issue is with your JSONParser..that and the JSON returned from the site isnt well formed. You have a bunch of JSONObjects with JSONObjects inside of them that have similar names. I made a quick and easy solution to deal with it but if you control the code that generates the JSON then I would suggest grouping the categories of items (books, music, camera) into their own JSONArrays
The JSON you’re getting back from the website is a JSONArray with JSONObjects.. you’re doing the following
jObj = new JSONObject(json);
You should be doing
jObj = new JSONArray(json);
Then you need to change your return to be a JSONArray instead of JSONObject
Then in the main activity change “json” to JSONArray and get rid of “book”..just loop through the JSONArray
Also move your try to be inside of the loop.
—–EDIT
As suggested in my comment, you should redo the code that creates the JSON output
In simple terms, you need a master array that contains JSONObjects for each “category”, and then each of those categories will be a JSONObject in a JSONArray
The JSON should look like this
This way you can do different actions (if needed) for the different categories and have any similar JSON Objects in the category all grouped together.
Or if the action will be the same regardless if it’s a book, music or camera then you can just add another field to your JSON Objects for “type” and then create the JSONObject in the array (JSON_array.put()) without a name so it would appear as
Again, the route you should take depends on what you’ll be doing with the data afterwards