您好我试图使用JSON从网站检索一些数据。我从教程中获得了一些代码,但是教程没有用。我认为这是因为教程中的url无法正常工作,但是当我尝试使用工作网址时,它仍然会出现同样的错误。 有人能告诉我我做错了什么。我到处都读到使用JSON应该非常简单和容易,但我真的很头疼尝试教程和阅读示例。
以下是名为Main.java的教程中的代码:
public class Main extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//the website I use lacks some security so I don't wanne put it here.
//its still under construction.
JSONObject json = JSONfunctions.getJSONfromURL("http://somewebsite/jsonexample.html");
try{
JSONArray student = json.getJSONArray("student");
for(int i=0;i<student.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = student.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Naam: " + e.getString("name"));
map.put("age", "Leeftijd: " + e.getString("age"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "age" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
以下是教程中名为JSONfunctions.java的代码:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
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{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
json:
{ “学生”:[{ “id”:“1”, “名字”:“Piet”, “年龄”:“10” } { “id”:“2”, “名字”:“Jaap”, “年龄”:“6” }] }
和logcat:
03-12 11:24:09.773: E/AndroidRuntime(911): FATAL EXCEPTION: main
03-12 11:24:09.773: E/AndroidRuntime(911): java.lang.RuntimeException: Unable to start activity ComponentInfo{me.mikey.my.games.galgjex/me.mikey.my.games.galgjex.Main}: java.lang.NullPointerException
03-12 11:24:09.773: E/AndroidRuntime(911): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.app.ActivityThread.access$600(ActivityThread.java:130)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.os.Handler.dispatchMessage(Handler.java:99)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.os.Looper.loop(Looper.java:137)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-12 11:24:09.773: E/AndroidRuntime(911): at java.lang.reflect.Method.invokeNative(Native Method)
03-12 11:24:09.773: E/AndroidRuntime(911): at java.lang.reflect.Method.invoke(Method.java:511)
03-12 11:24:09.773: E/AndroidRuntime(911): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-12 11:24:09.773: E/AndroidRuntime(911): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-12 11:24:09.773: E/AndroidRuntime(911): at dalvik.system.NativeStart.main(Native Method)
03-12 11:24:09.773: E/AndroidRuntime(911): Caused by: java.lang.NullPointerException
03-12 11:24:09.773: E/AndroidRuntime(911): at me.mikey.my.games.galgjex.Main.onCreate(Main.java:41)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.app.Activity.performCreate(Activity.java:5008)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
03-12 11:24:09.773: E/AndroidRuntime(911): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
03-12 11:24:09.773: E/AndroidRuntime(911): ... 11 more
将json更改为: { “学生”:[{ “id”:“1”, “名字”:“Piet”, “年龄”:“10” },{ “id”:“2”, “名字”:“Jaap”, “年龄”:“6” }] } 但它仍然给出了NPE。或者我的json仍然无效?
答案 0 :(得分:0)
查看网站地址..
如果您的网站是正确的,并且您在模拟器中运行应用程序,您将获得NullpointerException。一旦在您的设备中检查它是否获得JSON响应。 仍然如果您收到错误检查您是否在清单文件中添加了权限。 如果未添加权限,请在清单文件中添加以下权限。
<uses-permission android:name="android.permission.INTERNET"/>
查看以下链接,这将对您有所帮助 http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
答案 1 :(得分:0)
将所有代码放在单独的线程或AsyncTask中,并确保您已保留权限
<uses-permission android:name="android.permission.INTERNET"/>
你的清单中的
尝试使用此代码从服务中获取数据
How one interface can be used for different background android tasks?