0

我正在尝试使用此类从该 url获取 JSON 。

我正在使用 getJSONFromUrl 这样的:

JSONParser jParser = new JSONParser();//Instantiate class
JSONObject json = jParser.getJSONFromUrl("http://tcc-teste.aws.af.cm/api/get/aluno/1");//using getJSNOFromUrl method

我在 logcat 上收到此错误:

08-28 22:46:06.560: E/AndroidRuntime(905): FATAL EXCEPTION: main
08-28 22:46:06.560: E/AndroidRuntime(905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.br.edu.unifoa/com.example.br.edu.unifoa.MainActivity}: android.os.NetworkOnMainThreadException
08-28 22:46:06.560: E/AndroidRuntime(905):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-28 22:46:06.560: E/AndroidRuntime(905):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-28 22:46:06.560: E/AndroidRuntime(905):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-28 22:46:06.560: E/AndroidRuntime(905):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-28 22:46:06.560: E/AndroidRuntime(905):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-28 22:46:06.560: E/AndroidRuntime(905):  at android.os.Looper.loop(Looper.java:137)
08-28 22:46:06.560: E/AndroidRuntime(905):  at android.app.ActivityThread.main(ActivityThread.java:5103)
4

3 回答 3

1

在解析之前使用它

public static int SDK_INT = android.os.Build.VERSION.SDK_INT;

if (SDK_INT >= 10) {
                    ThreadPolicy tp = ThreadPolicy.LAX;
                    StrictMode.setThreadPolicy(tp);
                }

在清单文件中添加此权限

<uses-permission android:name="android.permission.INTERNET" />
于 2013-08-29T03:02:54.100 回答
0

谢谢兄弟,但是像这样更改 public static int SDK_INT = android.os.Build.VERSION.SDK_INT;

{
    if (SDK_INT >= 10) {
        StrictMode.ThreadPolicy tp = StrictMode.ThreadPolicy.LAX;
        StrictMode.setThreadPolicy(tp);
    }
}
于 2015-03-06T12:52:06.083 回答
0

您正在尝试解析导致此错误的 UI 线程(主线程)。运行一个 asynctask 并执行它。那就不会崩溃了。任何网络或长时间运行的工作都不应该在 UI 线程上完成,因为它会阻塞它。

于 2013-08-29T02:55:55.250 回答