【问题标题】:Retrieve JSON Object Android检索 JSON 对象 Android
【发布时间】:2012-11-20 14:20:31
【问题描述】:

我正在尝试从 URL 获取 JSON 字符串,但我不断收到“NetworkOnMainThreadException”。我以为我将网络代码移到了另一个线程,但显然没有。

这里是错误:

JSON解析器

package com.example.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public String getJSONFromUrl(String url) {

        DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
        HttpPost httppost = new HttpPost("http://api.androidhive.info/contacts/");
        // Depends on your web service
        httppost.setHeader("Content-type", "application/json");

        InputStream inputStream = null;
        String result = null;
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        HttpEntity entity = response.getEntity();

        try {
            inputStream = entity.getContent();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // json is UTF-8 by default i beleive
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result = sb.toString();
    }
}

主要活动

package com.example.jsonparsing;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends Activity{

    // url to make request
    private static String url = "http://api.androidhive.info/contacts/";

    // contacts JSONArray
    JSONArray contacts = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        RetrieveJSONString retrieveJSON = new RetrieveJSONString();
        retrieveJSON.run();
        String whatever = retrieveJSON.getJSONString();
    }
}

class RetrieveJSONString implements Runnable{

    JSONParser jParser;
    String jsonString;

    public void run() {
         // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        String jsonString = jParser.getJSONFromUrl("http://api.androidhive.info/contacts/");

    }

    public String getJSONString(){

        return jsonString;
    }

}

清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.jsonparsing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

如果有人能阐明这个问题,我将不胜感激!

【问题讨论】:

  • 你能发布错误堆栈吗?还有你的 Android Manifest 文件。
  • 已更新错误和清单

标签: java android json parsing


【解决方案1】:

您收到该错误是因为您尝试在 UI 线程上进行 HTTP 调用,并且您永远不应该这样做 :) 请改用 AsyncTask。这是一个简单的例子:

GetJsonAsync getJson = new GetJsonAsync();
getJson.execute();

private class GetJsonAsync extends AsyncTask <String, Void, String> {

        @Override
        protected void onPreExecute() {
            // Do stuff before the operation
        }

        @Override
        protected String doInBackground(String... params){
            getJSONFromUrl();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // Do stuff after the operation
        }
    }

【讨论】:

  • 顺便说一句,这个类需要在你的活动中,所以你必须在那里实例化你的 JSONparser 并从中调用 getJSONFromURL。除非您将其分配给线程,否则制作 Runnable 不会在单独的线程上运行它。
【解决方案2】:

来自Android SDK docs

当应用程序尝试执行 在其主线程上进行网络操作。

这仅针对以 Honeycomb SDK 为目标的应用程序或 更高。允许针对早期 SDK 版本的应用程序执行 在他们的主事件循环线程上联网,但它很重 灰心。请参阅文档设计响应性。

本质上,您想要执行某种线程应用程序,否则 GUI 可能会卡住。查看 AsyncTask 或只是线程化以满足您的 JSON 解析需求。

【讨论】:

    【解决方案3】:

    您应该在Thread 上调用start(),而不是直接调用run 方法。您正在调用将在 UI 线程上运行的 retrieveJSON.run();

     new Thread(new RetrieveJSONString()).start();
    

    我建议为此目的使用AsyncTask 而不是线程,因为您想在获取 JSON 后更新 UI。在 AsyncTask 中,当后台作业完成时,会调用 onPOstExecute() 方法,您可以在其中更新 UI。

    【讨论】:

    • 现在试试这个,但是“方法 start() 未定义 RetrieveJSONString 类型”
    • 使用这个:RetrieveJSONString retrieveJSON = new RetrieveJSONString(); new Thread(retrieveJSON).start();
    【解决方案4】:

    AscyTask 中调用getJSONFromUrl 方法。当处理时间较长时会出现此异常。使用此行调用此AscyTask 任务

    新的 AppTask().execute();

    public class AppTask extends AsyncTask<String, String, Void> {
       protected void onProgressUpdate(String... progress){}  protected void onPreExecute(){ }
    
       protected Void doInBackground(final String... args) {
           getJSONFromUrl();
           return null;
       }
    
       protected void onPostExecute(final Void unused) { }
    }
    

    【讨论】:

    • 这不是因为它需要很长时间。看我的回答。你的代码也不起作用:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2021-11-01
    • 2014-12-16
    相关资源
    最近更新 更多