代码在Jelly Beans中不起作用

时间:2012-11-01 05:27:10

标签: android json

我有这个代码从url返回Json个对象。 它在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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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;
}

答案 2 :(得分:1)

从Android API v15开始,它不需要在主线程上运行繁重的进程。因此,您应该将您的逻辑移动到另一个线程,如下面的源代码:

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

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

答案 3 :(得分: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