-2

This is my JSONParser.java class

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.util.Log;

public class JSONParser {

    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;

    }
}

this is my MainActivity.java

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends ListActivity {

// url to make request
private static String url = 
"https://api.themoviedb.org/3/genre/list?api_key=d397dd2d354f088c6f0eb91c6b160bb0";

// JSON Node names
private static final String TAG_CONTACTS = "genre";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";

// contacts JSONArray
JSONArray genre = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = 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 Contacts
        genre = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for (int i = 0; i < genre.length(); i++) {
            JSONObject c = genre.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);

            // Phone number is agin JSON Object
            // JSONObject phone = c.getJSONObject(TAG_PHONE);
            // String mobile = phone.getString(TAG_PHONE_MOBILE);
            // String home = phone.getString(TAG_PHONE_HOME);
            // String office = phone.getString(TAG_PHONE_OFFICE);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_NAME, name);

            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.activity_main, new String[] { TAG_NAME, TAG_ID },
            new int[] { R.id.name, R.id.uid });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick1(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cobaid = ((TextView) view.findViewById(R.id.uid))
                    .getText().toString();
            // Starting new intent
        //  Intent in = new Intent(getApplicationContext(),
        //  SingleMenuItemActivity.class);
        //  in.putExtra(TAG_NAME, name);
        //  in.putExtra(TAG_ID, id);
        //  startActivity(in);
        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

        }
    });
}

}

this is my json format

{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},    {"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":105,"name":"Disaster"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":82,"name":"Eastern"},{"id":2916,"name":"Erotic"},{"id":10751,"name":"Family"},{"id":10750,"name":"Fan Film"},{"id":14,"name":"Fantasy"},{"id":10753,"name":"Film Noir"},{"id":10769,"name":"Foreign"},{"id":36,"name":"History"},{"id":10595,"name":"Holiday"},{"id":27,"name":"Horror"},{"id":10756,"name":"Indie"},{"id":10402,"name":"Music"},{"id":22,"name":"Musical"},{"id":9648,"name":"Mystery"},{"id":10754,"name":"Neo-noir"},{"id":1115,"name":"Road Movie"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10755,"name":"Short"},{"id":9805,"name":"Sport"},{"id":10758,"name":"Sporting Event"},{"id":10757,"name":"Sports Film"},{"id":10748,"name":"Suspense"},{"id":10770,"name":"TV movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}

But it is Force Close, and this is on LogCat

error parsing dataorg.json.JSONException: Value Not of type java.lang.String cannot be converted to JSONObject

Can you help with the source code right? sorry I am a newbie in web service android. I want to parse the json from URL

user3197499
  • 17
  • 1
  • 7
  • 3
    Well, *what* is the JSON? And on which *line* is the exception raised? The error means that the code is reading it *incorrectly*. – user2864740 Jan 20 '14 at 02:28
  • can you retrieve the json object on here `JSONObject json = jParser.getJSONFromUrl(url);` please post the json object. – Dinithe Pieris Jan 20 '14 at 02:37
  • I hope this will help: http://stackoverflow.com/questions/10267910/jsonexception-value-of-type-java-lang-string-cannot-be-converted-to-jsonobject – Hayi Nukman Jan 20 '14 at 07:32

3 Answers3

1

Here you have declared this as a

 private static final String TAG_CONTACTS = "genre";

and in your Json is

 {"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},    {"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":105,"name":"Disaster"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":82,"name":"Eastern"},{"id":2916,"name":"Erotic"},{"id":10751,"name":"Family"},{"id":10750,"name":"Fan Film"},{"id":14,"name":"Fantasy"},{"id":10753,"name":"Film Noir"},{"id":10769,"name":"Foreign"},{"id":36,"name":"History"},{"id":10595,"name":"Holiday"},{"id":27,"name":"Horror"},{"id":10756,"name":"Indie"},{"id":10402,"name":"Music"},{"id":22,"name":"Musical"},{"id":9648,"name":"Mystery"},{"id":10754,"name":"Neo-noir"},{"id":1115,"name":"Road Movie"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10755,"name":"Short"},{"id":9805,"name":"Sport"},{"id":10758,"name":"Sporting Event"},{"id":10757,"name":"Sports Film"},{"id":10748,"name":"Suspense"},{"id":10770,"name":"TV movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}

So there is missing "s" in your declare of string for TAG_CONTACTS

So change it from

 private static final String TAG_CONTACTS = "genre";

to

private static final String TAG_CONTACTS = "genres";
Piyush
  • 18,895
  • 5
  • 32
  • 63
0

We need the original JSON pasted with your answer and the stack trace. Sniffing through your code though,

  1. are you sure your JSON is valid? You can verify with this: http://jsonlint.com

  2. at JSONObject c = genre.getJSONObject(i);, are you sure the genre array contains JSONObjects, and not Strings representing JSON?

  3. at jObj = new JSONObject(json);, are you sure that json represents valid JSON?

  4. are you sure that the value corresponding to TAG_ID is a String type, and not a long say? String id = c.getString(TAG_ID); could perhaps be: long id = c.getLong(TAG_ID);

It is hard to be of more help without further assistance from you.

Edit: Based on your comment, where you post your JSON format, you will need to answer point (3) above. Your id field has an integer type, not String type.

Ken
  • 30,811
  • 34
  • 116
  • 155
  • **this is my json format:** {"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"} – user3197499 Jan 20 '14 at 02:45
  • @user3197499 Can you post the JSON with your question please? And make sure that it is valid JSON. What you've posted here is not valid (your array is not closed off, for instance). – Ken Jan 20 '14 at 02:58
  • That's invalid json, the array is not closed. – Jonathan M Jan 20 '14 at 02:59
0

Implement in this way.It may be help u..

 getJsonResponse(String url){
    try {
                JSONObject jObject = new JSONObject(url);
                    JSONArray list = jObject.getJSONArray("genres");

                    for (int i = 0; i < list.length(); i++) {
                        JSONObject element = list.getJSONObject(i);
    String id=element.getString("id);
    }
    }

}
Anjali Tripathi
  • 1,477
  • 9
  • 28