1

我做了一个活动“消息”,它应该从给定的 URL 获取 JSON 数据。我尝试制作一个循环来打印 json 数据,但问题出在其他地方。我正在NullPointerException使用JSONArray“json”。

消息类:

public class Messages extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView tv = (TextView) findViewById(R.id.tv_messages);
    JSONArray json = JSONfunctions.getJSONfromURL("http://docs.blackberry.com/sampledata.json");

    tv.setText(json.length());
}

JSON函数类:

public class JSONfunctions {

    public static JSONArray getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray 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 get data string ",
                    "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag create object ",
                    "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

错误:

08:11:43.683:http连接错误android.os.NetworkOnMainThreadException 08:11:43.693:错误转换结果java.lang.NullPointerException:lock == null 08:11:43.703:解析数据时出错org.json.JSONException:结束08:11:43.723 的字符 0 处的输入:关闭 VM 08:11:43.733:threadid=1:线程以未捕获的异常退出(组=0x40a70930) 08:11:43.923:ATAL 异常:主 08:11:43.923 :java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.sound/com.example.sound.Messages}:java.lang.NullPointerException 08:11:43.923:在android.app.ActivityThread.performLaunchActivity(ActivityThread。 java:2180) 08:11:43.923: 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 08:11:43.923: 在 android.app.ActivityThread.access$600(ActivityThread.java:141) 08:11 :43.923: 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 08:11:43.923: 在 android.os.Handler.dispatchMessage(Handler.java:99) 08:11:43.923: 在 android.os .Looper.loop(Looper.java:137) 08:11:43.923: 在 android.app.ActivityThread.main(ActivityThread.java:5039) 08:11:43.923: 在 java.lang.reflect.Method.invokeNative(Native方法) 08:11:43.923: 在 java.lang.reflect.Method.invoke(Method.java:511) 08:11:43.923: 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 793) 08:11:43.923: 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 08:11:43.923: 在 dalvik.system.NativeStart.main(本机方法) 08:11:43.923 :引起:java.lang.NullPointerException 08:11:43.923:在 com.example.sound.Messages.onCreate(Messages.java:18) 08:11:43.923:在 android.app.Activity。performCreate(Activity.java:5104) 08:11:43.923: 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 08:11:43.923: 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)

第 18 行是:

tv.setText(json.length());

在出现上述错误之前,我也得到了很多:

Unexpected value from nativeGetEnabledTags: 0

我正在使用的 URL(出于测试目的,http://docs.blackberry.com/sampledata.json)已启动并正常工作。我是 Android 开发和 JSON 的新手。提前致谢。

4

2 回答 2

2

这是因为您要么在不允许的 android 版本 >= 3.0 的主线程上执行网络操作。

要解决此问题,请使用

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy); 

或者

Use AsyncTask 

从http://developer.android.com/reference/android/os/AsyncTask.html读取

于 2013-02-03T08:33:22.773 回答
0

感谢@TGMCians,ASyncTask 完成了这项工作。这是我的活动现在的样子:

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

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class Messages extends Activity {
    String THEURL = "http://docs.blackberry.com/sampledata.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_messages);
        new RetrieveMessages().execute(THEURL);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        finish();
    }
    private class RetrieveMessages extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            HttpClient client = new DefaultHttpClient();
            String json = "";
            try {
                String line = "";
                HttpGet request = new HttpGet(urls[0]);
                HttpResponse response = client.execute(request);
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while ((line = rd.readLine()) != null) {
                    json += line + System.getProperty("line.separator");
                }
            } catch (IllegalArgumentException e1) {
                e1.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            return json;
        }

        protected void onProgressUpdate(Void... progress) {

        }

        protected void onPostExecute(String result) {
            TextView tv = (TextView) findViewById(R.id.tv_messages);
            tv.setText(result);
        }
    }
}
于 2013-02-03T14:57:22.040 回答