1

我有这段代码Json从 url 返回对象。它工作正常,froyo但相同的代码在Jelly Beans.

我的代码有问题吗?

请帮助我,这是我的代码

    public static JSONObject getJSONfromURL(String url) {

    // initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}

这是我的日志错误

11-01 11:01:48.437: E/log_tag(1044): Error in http connection android.os.NetworkOnMainThreadException 11-01 11:01:48.437: E/log_tag(1044): Error converting result java.lang.NullPointerException 11-01 11:01:48.437: E/log_tag(1044): Error parsing data org.json.JSONException: End of input at character 0 of

4

4 回答 4

1

您正在尝试在主线程上建立网络连接。而是使用AsyncTask. 因为网络任务是长任务。在 froyo 中,您可以在主线程上建立网络,但在更高版本的 android 中,您必须使用Async Task.

于 2012-11-01T05:39:45.767 回答
1

在后台线程中调用服务器。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new AsyncTask<Void,Void,Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            JSONObject jObject = getJSONfromURL("http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%2248907%22&format=json");
            return null;
        }
    }.execute();
}
public JSONObject getJSONfromURL(String url) {

    // initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}
于 2012-11-01T05:42:30.067 回答
1

从 Android API v15 开始,它不需要在主线程上工作的繁重进程。所以你应该将你的逻辑移动到另一个线程,比如下面的源代码:

new Thread(new Runnable() {
   public void run() {
        // your logic
   }                        
}).start();

更多信息请参考 http://developer.android.com/guide/practices/responsiveness.html

于 2012-11-01T05:42:54.187 回答
1

是的,它关于android.os.NetworkOnMainThreadException 使用AsyncTask执行网络相关任务的错误。

以另一种方式,您可以通过在您的onCreate()

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

但是看到禁用StrictMode策略不是一个好主意,所以你最好去AsyncTask

于 2012-11-01T05:43:21.847 回答