0

您好,我正在尝试使用 JSON 从网站检索一些数据。我从教程中得到了一些代码,但教程没有用。我认为这是因为教程中的 url 不起作用,但是当我尝试工作 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" }] }

和日志猫:

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”,“name”:“Piet”,“age”:“10”},{“id”:“2”,“name”:“ Jaap", "age" : "6" }] } 但它仍然给出了 NPE。还是我的json仍然无效?

4

2 回答 2

0

检查网站地址..

如果您的网站是正确的并且如果您在模拟器中运行您的应用程序,您将获得 NullpointerException。一旦在您的设备中检查您是否收到 JSON 响应。仍然如果您收到错误检查您是否在清单文件中添加了权限。如果您未添加权限,请在清单文件中添加以下权限。

             <uses-permission android:name="android.permission.INTERNET"/>

并查看以下链接,这将对您有所帮助 http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

于 2013-03-12T12:33:59.933 回答
0

将所有代码放在单独的线程或 AsyncTask 中,并确保您保留了权限

 <uses-permission android:name="android.permission.INTERNET"/>

在你的清单中

尝试使用此代码从服务中获取数据

一个界面如何用于不同的后台android任务?

于 2013-03-12T12:36:46.643 回答