2013-07-02 144 views
-1

我從Android Hive得到了一個代碼來解析來自url的JSON數據。然後我試圖在Rotten Tomatoes Upcoming Movies Api上實現相同的代碼。根據我的需要,我已經實現了幾乎修改所有xml文件的相同代碼。但問題是當我試圖運行代碼時,它顯示了NetworkOnMainThread Exception。NetworkOnMainThread異常發生

這是我的代碼..

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); 
     } 
    }); 
} 


} 

任何人都可以請幫助我什麼我失蹤?我現在完全瞎了。提前Thanx。

+0

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&波黑= 608 –

回答

0

你正在解析主UI線程。這就是爲什麼它會拋出錯誤..你應該使用runOnUiThread或AsycTask。

JSONObject json = jParser.getJSONFromUrl(url); 

放上面一行象下面這樣:

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(); 
0

請將您的互聯網連接程序代碼寫入ASyncTask或其他線程。由於ICS和果凍豆不允許您在主線程上進行互聯網進程。

2

不要使用在主線程(UI線程)的網絡連接使用Asyntask或線程做。

0

不要在UI /主線程上做你的http請求 - 你的同步http被阻塞,這樣做會阻塞屏幕上的實際繪製和佈局傳遞。

對於UI事件做出響應,就像你試圖在Android中常見的那樣,他們發明了一個叫做AsyncTask的驚人幫手。

使用對封閉Activity類的內部引用創建此類的匿名實例(即,實際上,在您的活動中定義類並且不要將其設置爲靜態)。

從上面的文檔:

當執行異步任務,任務經過...

doInBackground(參數...),onPreExecute後,立即在後臺線程調用( )完成執行。此步驟用於執行可能需要很長時間的後臺計算。 ...

onPostExecute(Result),在後臺計算完成後在UI線程上調用。後臺計算的結果作爲參數傳遞給此步驟。

[我忘了額外的細節,也是我的重點]。

您的適配器應該引用一個異步任務,該任務將您的所有同步http請求中執行的代碼塊中的信息從UI線程傳遞到UI線程上的代碼塊,該代碼塊可用於觸摸其視圖(你在這裏更新你的列表視圖)。

最好,

湯姆。

1

使用的AsyncTask

例如: -

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) 
} 
} 

在你的onCreate添加以下代碼()方法使用以下代碼來禁用嚴格模式

這不是解決辦法,但避免了主線程網絡IO,所以我建議的AsyncTask

if (android.os.Build.VERSION.SDK_INT > 9) { 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
      .permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 
}