2012-08-16 64 views
0

蜂窩錯誤android.os.NetworkOnMainThreadException我設置我的目標sdk爲11後。我用下面的代碼忽略它。它會影響我的應用程序嗎?有人可以提出任何解決這個問題的方法。Android HoneyComb使用操作欄錯誤

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 

StrictMode.setThreadPolicy(policy); 



@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.grid_layout); 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 

     StrictMode.setThreadPolicy(policy); 

     ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); 

     XMLParser parser = new XMLParser(); 
     String xml = parser.getXmlFromUrl(URL); // getting XML from URL 
     Document doc = parser.getDomElement(xml); // getting DOM element 

     NodeList nl = doc.getElementsByTagName(KEY_SONG); 
     // looping through all song nodes <song> 
     for (int i = 0; i < nl.getLength(); i++) { 
      // creating new HashMap 
      HashMap<String, String> map = new HashMap<String, String>(); 
      Element e = (Element) nl.item(i); 
      // adding each child node to HashMap key => value 
      map.put(KEY_ID, parser.getValue(e, KEY_ID)); 
      map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE)); 
      map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST)); 
      map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION)); 
      map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL)); 

      // adding HashList to ArrayList 
      songsList.add(map); 
     } 

回答

2

這是不好的做法做就主線程(UI線程)的網絡接入。如果你的目標SDK是蜂窩或更高,將會給網絡上使用Asynac tasks避免這一主線exception.Try。

代碼EX:

public class yourclass extends Activity{ 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.uoyrlayout); 
     //this is UI thread you should not do network access from here. 
     new LongRunning().execute();//call to background thread to do network access 
} 
    public class LongRunning extends AsyncTask<Void, Void, Void> { 
     protected void onPreExecute() { 
      //UI updating goes here before background thread.. 
     } 
     @Override 
     protected Void doInBackground(Void... params) {  
      //This is not the UI thread 
      //do your network acces 
      return null;    
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      //update your UI after background thread 
     } 

    } 
} 
+0

您就可以在如何實現它的樣本? – 2012-08-16 03:53:23

+0

好的我編輯了代碼 – 2012-08-16 04:05:35

+0

謝謝。這看起來很困難。隨着那些upvote,我會接受你的答案。不敢要求更多,我需要找到幫助實施我的代碼到你的。 – 2012-08-16 05:32:33