我正在尝试使用this url从this class获取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)
答案 0 :(得分: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" />
答案 1 :(得分:0)
您正在尝试解析导致此错误的UI线程(主线程)。运行asynctask并执行它。它不会崩溃。任何网络或长时间运行的工作都不应该在UI线程上完成,因为它会阻止它。
答案 2 :(得分:0)
{
if (SDK_INT >= 10) {
StrictMode.ThreadPolicy tp = StrictMode.ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
}
}