错误 StrictMode$AndroidBlockGuardPolicy.onNetwork

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22395417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:55:00  来源:igfitidea点击:

Error StrictMode$AndroidBlockGuardPolicy.onNetwork

androidjson

提问by user3415458

I created android application and use JSONget data from server but I got the error show below:

我创建了 android 应用程序并使用JSON从服务器获取数据,但出现以下错误:

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

how can I fix this problem
Thank you

我该如何解决这个问题
谢谢

回答by user3113670

you have to insert 2 lines "StrictMode" on MainActivity Class, example's below:

您必须在 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

爱沙空

回答by Arshad Ali

Better to use AsyncTaskas mentioned here, an Alternative for just getting rid of the Exceptionis use :

更好地使用这里AsyncTask提到的,只是摆脱is use的替代方法:Exception

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

or this :

或这个 :

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

in your Activity where Exceptionoccurs.

在您的活动中Exception发生。

回答by Viraj Patel

Just add two lines after on create method

只需在创建方法后添加两行

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