0

我在 android 中制作了一个用于 JSON 解析的简单应用程序,我尝试从该 JSON Web 服务的 url 解析 JSON 数据并希望在 listView 中查看它,但我不知道为什么它不起作用,我已经尝试过以下代码。

主.java

package com.example.newjsondemo;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends ListActivity {
private static String url= "http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo";

private static final String TAG_POSTALCODES = "postalcode";
private static final String TAG_ADMINNAME1 = "adminName1";
private static final String TAG_ADMINNAME2 = "adminName2";
private static final String TAG_ADMINNAME3 = "adminName3";  
private static final String TAG_ADMINCODE1 = "adminCode1";
private static final String TAG_ADMINCODE2 = "adminCode2";
private static final String TAG_ADMINCODE3 = "adminCode3";
private static final String TAG_PLACENAME = "placeName";
private static final String TAG_POSTALCODE = "postalcode";
private static final String TAG_LNG = "lng";
private static final String TAG_LAT = "lat";
private static final String TAG_COUNTRY_CODE = "countryCode";

JSONArray postalcodes = null;


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Hashmap for ListView
                ArrayList<HashMap<String, String>> postalList = new ArrayList<HashMap<String, String>>();
                Jsonparser jParser = new Jsonparser();
                JSONObject json = jParser.getJSONFromUrl(url);

                try{
                    postalcodes = json.getJSONArray(TAG_POSTALCODES);

                        for(int i=0;i<postalcodes.length();i++)
                        {
                        JSONObject p = postalcodes.getJSONObject(i);
                        // Storing each json item in variable
                        String adminname1 = p.getString(TAG_ADMINNAME1);
                        String adminname2 = p.getString(TAG_ADMINNAME2);
                        String adminname3 = p.getString(TAG_ADMINNAME3);
                        String admincode1 = p.getString(TAG_ADMINCODE1);
                        String admincode2 = p.getString(TAG_ADMINCODE2);
                        String admincode3 = p.getString(TAG_ADMINCODE3);
                        String postalcode = p.getString(TAG_POSTALCODE);
                        String countrycode = p.getString(TAG_COUNTRY_CODE);
                        String placename = p.getString(TAG_PLACENAME);
                        String lng = p.getString(TAG_LNG);
                        String lat = p.getString(TAG_LAT);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(TAG_ADMINNAME1,adminname1);
                        map.put(TAG_COUNTRY_CODE, countrycode);
                        map.put(TAG_PLACENAME, placename);
                        postalList.add(map);
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                }


                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(this, postalList, R.layout.activity_list_item, 
                        new String[] { TAG_ADMINNAME1, TAG_COUNTRY_CODE, TAG_PLACENAME}, new int[] {
                        R.id.adminname1, R.id.countrycode, R.id.placename});
                setListAdapter(adapter);

                // selecting single ListView item
                ListView lv = getListView();
                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View view,
                            int position, long id) {
                        // TODO Auto-generated method stub
                        // getting values from selected ListItem
                    //  String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                        String adminname1 = ((TextView)view.findViewById(R.id.adminname1)).getText().toString();
                        String countrycode= ((TextView)view.findViewById(R.id.countrycode)).getText().toString();
                        String placename= ((TextView)view.findViewById(R.id.placename)).getText().toString();
                        // Starting new intent
                        Intent in = new Intent(getApplicationContext(), SIngleListItem.class);
                        in.putExtra(TAG_ADMINNAME1, adminname1);
                        in.putExtra(TAG_COUNTRY_CODE, countrycode);
                        in.putExtra(TAG_PLACENAME, placename);
                        //in.putExtra(TAG_ADDRESS, address);
                        //in.putExtra(TAG_GENDER, gender);
                        startActivity(in);
                    }

                });

}


}

JsonParser.java

   package com.example.newjsondemo;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Jsonparser {


    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public Jsonparser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

}

日志猫

02-14 17:07:04.411: E/Buffer Error(1932): Error converting result java.lang.NullPointerException
02-14 17:07:04.411: E/JSON Parser(1932): Error parsing data org.json.JSONException: End of input at character 0 of 
02-14 17:07:04.421: D/AndroidRuntime(1932): Shutting down VM
02-14 17:07:04.421: W/dalvikvm(1932): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
02-14 17:07:04.431: E/AndroidRuntime(1932): FATAL EXCEPTION: main
02-14 17:07:04.431: E/AndroidRuntime(1932): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonmydemo/com.example.jsonmydemo.MainActivity}: java.lang.NullPointerException
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.os.Looper.loop(Looper.java:123)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.app.ActivityThread.main(ActivityThread.java:4627)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at java.lang.reflect.Method.invokeNative(Native Method)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at java.lang.reflect.Method.invoke(Method.java:521)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at dalvik.system.NativeStart.main(Native Method)
02-14 17:07:04.431: E/AndroidRuntime(1932): Caused by: java.lang.NullPointerException
02-14 17:07:04.431: E/AndroidRuntime(1932):     at com.example.jsonmydemo.MainActivity.onCreate(MainActivity.java:51)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-14 17:07:04.431: E/AndroidRuntime(1932):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-14 17:07:04.431: E/AndroidRuntime(1932):     ... 11 more
4

2 回答 2

0

您没有考虑过下载 JSON 数据的延迟。您只需调用JSONObject json = jparser.getJSONFromURL(url);希望数据会在下一行 ( postalcodes = json.getJSONArray(TAG_POSTALCODES);) 出现。它不是那样工作的。

首先,您需要加载 JSON 数据并等待它完成。您应该熟悉AsyncTask才能正确执行此操作。然后在您的类中调用回调,MainActivity将检索到的数据返回给它。然后您应该使用该数据并构建您的适配器。

于 2013-02-14T12:33:11.627 回答
-1
HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(registerUrl);
                StringBuffer jsonString = new StringBuffer();
                try{
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    InputStream in = httpResponse.getEntity().getContent();
                    int ch = 0;
                    while ((ch = in.read()) != -1) {
                        jsonString.append((char) ch);
                    }
                    in.close();
                    JSONObject jsonObject = new JSONObject(jsonString.toString());
                    JSONArray jArray = jsonObject.getJSONArray("results");
                    int arraysize = jArray.length();
                        for (int i = 0; i < arraysize; i++){
                            JSONObject one = jArray.getJSONObject(i);
                            LogMsg.i("Confirm "+one.getString("ConfirmationMessage")+ " UserId "+one.getString("UserID")+ " userName "+one.getString("UserName")+" Email "+one.getString("Email"));
                            if (one.getString("ConfirmationMessage").equals("Account Created")){
                                isUserRegister = true;
                            }
                        }
                    }catch (Exception e) {}
于 2013-02-14T11:32:26.547 回答