我创建了一个活动“Messages”,它应该从给定的URL获取JSON数据。我尝试制作一个循环来打印json数据,但问题出在其他地方。我在NullPointerException
,“json”上获得JSONArray
。
消息类:
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());
}
JSONfunctions类:
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:转换错误 result java.lang.NullPointerException:lock == null 08:11:43.703: 解析数据时出错org.json.JSONException:字符0处的输入结束 08:11:43.723:关闭VM 08:11:43.733:threadid = 1:thread 退出未捕获的异常(组= 0x40a70930)08:11:43.923:ATAL EXCEPTION:main 08:11:43.923:java.lang.RuntimeException:无法执行 开始活动 ComponentInfo {com.example.sound / com.example.sound.Messages}: java.lang.NullPointerException 08:11:43.923:at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 08:11:43.923:at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 08:11:43.923:at android.app.ActivityThread.access $ 600(ActivityThread.java:141) 08:11:43.923:at 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:at java.lang.reflect.Method.invokeNative(Native Method) 08:11:43.923:at java.lang.reflect.Method.invoke(Method.java:511) 08:11:43.923:at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793) 08:11:43.923:at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 08:11:43.923:at dalvik.system.NativeStart.main(Native Method) 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:at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 08:11:43.923:at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
第18行是:
tv.setText(json.length());
在出现上述错误之前,我也得到了很多:
Unexpected value from nativeGetEnabledTags: 0
我正在使用的网址(用于测试目的,http://docs.blackberry.com/sampledata.json)正常运行。 我是Android开发和JSON的新手。 提前谢谢。
答案 0 :(得分:2)
这是因为您正在主线程上执行网络操作,而不允许Android版本> = 3.0。
要解决此问题,请使用
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
OR
Use AsyncTask
从http://developer.android.com/reference/android/os/AsyncTask.html
阅读答案 1 :(得分: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);
}
}
}