尝试将互联网上的项目添加到Android列表会导致应用

时间:2016-11-28 08:46:29

标签: android json android-asynctask

我正在尝试设置一个Android列表,它从互联网上的JSON数组中获取信息,JSON是这样的:

[
{
    "id":1,
    "category":"Category1",
    "title":"Title1",
    "description":"description1",
    "studio":"studio1",
    "videoUrl":"https://example.com",
    "cardImageUrl":"http://example.com",
    "bgImageUrl":"http://example.com"},
{
    "id":2,
    "category":"category2",
    "title":"title2",
    "description":"description2",
    "studio":"studio2",
    "videoUrl":"http://example.com",
    "cardImageUrl":"http://example.com",
    "bgImageUrl":"http://example.com"
}
]

这是我用来从服务器检索数据的代码:

public static List<Movie> setupMovie()
{
    List<Movie> list = new ArrayList<>();

    try {
        URL data = new URL("http://example.com/data.php");
        URLConnection tc = data.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                tc.getInputStream()));

        String line = null;
        JSONArray array = new JSONArray(line);
        while ((line = in.readLine()) != null) {
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.getJSONObject(i);
                list.add(buildAppInfo(object.getString("category"), object.getString("title"), object.getString("description"),
                        object.getString("studio"), object.getString("videoUrl"), object.getString("cardImageUrl"),
                        object.getString("bgImageUrl")));
            }
        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return list;
}

当我在Android Studio中运行APK时,崩溃时出现以下错误:

Process: com.example.myapp, PID: 8034
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MainActivity}: android.os.NetworkOnMainThreadException
Application terminated.

我知道答案是做异步任务,我尝试在类似问题上阅读其他答案,但我仍然不了解如何在我的案例中正确设置异步任务。我也尝试过StrictMode,但它不起作用。

我的主要问题是我不了解如何在我的项目上设置异步任务工作。非常感谢任何帮助,谢谢。

0 个答案:

没有答案