错误StrictMode $ AndroidBlockGuardPolicy.onNetwork

我创build了android应用程序,并使用JSON从服务器获取数据,但我得到了下面的错误显示:

 android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 

我怎样才能解决这个问题
谢谢

你必须在MainActivity类中插入2行“StrictMode”,例如下面的例子:

 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); try { // JSON here } catch (JSONException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } setContentView(R.layout.activity_main); Intent intent=new Intent(this,HomeActivity.class); startActivity(intent); } } 

Aey.Sakon

如上所述,最好使用AsyncTask ,一种替代方法就是使用:

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

或这个 :

 Thread thread = new Thread(new Runnable(){ @Override public void run() { try { //Your code goes here } catch (Exception e) { Log.e(TAG, e.getMessage()); } } }); thread.start(); 

在您的活动发生Exception

创build方法后只需添加两行

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