-1

I got a code from Android Hive to parse JSON data from url. Then I am trying to implement the same code on Rotten Tomatoes Upcoming Movies Api. I have implemented the same code with almost modifying all the xml files according to my needs. But the problem is when I am trying to run the code, its showing NetworkOnMainThread Exception.

This is my code.

public class Upcoming extends ListActivity
{
    String url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=yvvgsv722gy2zkey3ebkda5t";

    final String TAG_MOVIES = "movies";
    final String TAG_ID = "id";
    final String TAG_TITLE = "title";
    final String TAG_YEAR = "year";
    final String TAG_MPAA_RATING = "mpaa_rating";
    final String TAG_RUNTIME = "runtime";
    final String TAG_RELEASE_DATES = "release_dates";
    final String TAG_RATINGS = "ratings";
    final String TAG_CRITIC_RATING = "critics_ratings";
    final String TAG_AUDIENCE_RATING = "audience_ratings";
    final String TAG_SYNOPSIS = "synopsis";
    final String TAG_POSTERS = "posters";

    JSONArray upcomings = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upcoming_list);

        ArrayList<HashMap<String, String>> UpcomingList = 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
            upcomings = json.getJSONArray(TAG_MOVIES);

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

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String title = c.getString(TAG_TITLE);
                String year = c.getString(TAG_YEAR);
                String mpaa_rating = c.getString(TAG_MPAA_RATING);
                String runtime = c.getString(TAG_RUNTIME);

                JSONObject release_dates = c.getJSONObject(TAG_RELEASE_DATES);
                JSONObject ratings = c.getJSONObject(TAG_RATINGS);
                String critic_rating = c.getString(TAG_CRITIC_RATING);
                String audience_rating = c.getString(TAG_AUDIENCE_RATING);
                String synopsis = c.getString(TAG_SYNOPSIS);
                JSONObject posters = c.getJSONObject(TAG_POSTERS);


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

                map.put(TAG_TITLE, title);
                map.put(TAG_YEAR, year);
                map.put(TAG_CRITIC_RATING, critic_rating);
                map.put(TAG_AUDIENCE_RATING, audience_rating);

                UpcomingList.add(map);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ListAdapter adapter = new SimpleAdapter(this, UpcomingList,
                R.layout.activity_upcoming,
                new String[] { TAG_TITLE, TAG_YEAR, TAG_CRITIC_RATING, TAG_AUDIENCE_RATING }, new int[] 
                        {
                        R.id.title, R.id.year, R.id.critic_rating, R.id.audience_rating });

        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.title)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.year)).getText().toString();
                String critic_rating = ((TextView) view.findViewById(R.id.critic_rating)).getText().toString();
                String audience_rating = ((TextView) view.findViewById(R.id.audience_rating)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), Upcoming.class);
                in.putExtra(TAG_TITLE, name);
                in.putExtra(TAG_YEAR, cost);
                in.putExtra(TAG_CRITIC_RATING, critic_rating);
                in.putExtra(TAG_AUDIENCE_RATING, audience_rating);
                startActivity(in);
            }
        });
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Aishvarya Jaiswal
  • 1,793
  • 6
  • 34
  • 72
  • http://www.google.co.in/#q=NetworkOnMainThreadexception&spell=1&sa=X&ei=ILTSUeKIBIamrQfrgYGgAg&ved=0CCcQvwUoAA&bav=on.2,or.r_qf.&bvm=bv.48705608,d.bmk&fp=454708d46e718598&biw=1152&bih=608 – Dhaval Parmar Jul 02 '13 at 11:06

5 Answers5

2

Don't use the network connection in main thread(UI Thread) use Asyntask or threads to do .

Srikanth
  • 584
  • 1
  • 6
  • 21
1

use AsyncTask

for Example :--

 class YourTask extends AsyncTask<URL, Integer, String> {
 protected String doInBackground(URL... urls) {
     // Fetch Data (Task A)
     return "Result";
 }

 protected void onProgressUpdate(Integer... progress) {
     // Show progress
 }

 protected void onPostExecute(String result) {
     // Show UI after complete (Task B)
 }
}

or

add below code in your onCreate() method to disable the strict mode using following code:

this is not the solution but avoids network IO on main thread so i recommend AsyncTask

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
}
Selvin
  • 6,598
  • 3
  • 37
  • 43
Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71
0

Please put your internet connection process code in to ASyncTask or in other thread. As ICS and Jelly Bean do not allow you to make internet process on the main thread.

Rushabh Patel
  • 3,052
  • 4
  • 26
  • 58
0

you are parsing in main UI Thread. thats why it throws error.. you should use runOnUiThread or AsycTask for that.

JSONObject json = jParser.getJSONFromUrl(url);

put above line like below:

loadingDialog = ProgressDialog.show(youractivity.this, "", "Loading...", true, false);
new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    runOnUiThread(new Runnable() {
                        public void run() {
                                                loadingDialog.dismiss();
                                                JSONObject json = jParser.getJSONFromUrl(url);
                                           }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99
0

Don't do your http requests on the UI / Main thread- your syncronous http is blocking and to do so would block actual draws and layout passes on the screen.

Doing http in response to UI events like you're trying to do so common in Android they've invented an amazing helper called AsyncTask.

Create an anonymous instance of this class with an inner reference to the enclosing Activity class (i.e. in practical terms, define the class inside your activity and don't make it static).

From the docs above:

When an asynchronous task is executed, the task goes through...

doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. ...

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

[I've ommited extra details, also my emphasis].

Your adapter should refer to an async task, which passes information from a code block executed with all your syncronous http requests in it off the UI thread, to a code block on the UI thread that can be used to touch its views (you update your listview here).

Best,

Tom.

Community
  • 1
  • 1
Tom
  • 1,773
  • 15
  • 23