1

我查看了无数项目和教程,但无法弄清楚为什么我的应用程序一运行就崩溃。如果我注释掉 try catch "JSONObject dataObject = json.getJSONObject("data");" 中的第一行,它似乎运行良好 我试图解析的 JSON 格式如下:

    {"recordcount":3,
 "columnlist":"department,emailaddress,firstname,has_photos,job_full_title,job_title,kid,lastname,location,middlename,no_show_photo,phone,school",
 "data":
 {"department":["Public Safety","Information Technology","Information Technology"],
 "emailaddress":["todd.mongeon@wne.edu","amutti@wne.edu","fatemeh.shams@wne.edu"],
 "firstname":["Todd","Tony","Toffee"],
 "has_photos":["Y","Y","N"],
 "job_full_title":["Officer","Director, Administrative Information Systems","Sr.Technical Programmer/Analyst and Integ Specialist"],
 "job_title":["Officer","Director, Administrative Information Systems","Sr.Technical Programmer/Analyst and Integ Specialist"],
 "kid":[286899,2497,297411],
 "lastname":["Mongeon","Mutti","Shams"],
 "location":["PS","12 V","12 V"],
 "middlename":["A.","M.",""],
 "no_show_photo":["","",""],
 "phone":["413-782-1207","413-782-1212","413-796-2398"],
 "school":["Public Safety Group","Information Technology Group","Information Technology Group"]}}

我的程序看起来像这样(请原谅格式/不需要的东西......它需要从我试图让它工作的很多东西中清理出来......)

    public class Directory_finalActivity extends ListActivity {

public static String url = "http://www1.wne.edu/webservices/directorydemo.cfc?wsdl&method=getEmployees&limit=25&firstname=to&outputtype=JSON";

// JSON array names
private static final String TAG_FIRST = "firstname";
private static final String TAG_LAST = "lastname";
private static final String TAG_SCHOOL = "school";
private static final String TAG_DEPARTMENT = "department";
private static final String TAG_EMAIL = "emailaddress";
private static final String TAG_PHONE = "phone";
private static final String TAG_JOB = "job_title";
private static final String TAG_LOCATION = "location";




//create JSON array
JSONArray firstNames = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();        
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);


    String[] firstNames = null;
    try {
        // Getting the data object
        JSONObject dataObject = json.getJSONObject("data");  //This is the line that seems to be causing the error.
        int numResults = json.getInt("recordcount");
        /**
        JSONArray firstNameArray =  dataObject.getJSONArray("firstname");
        JSONArray lastNameArray =  dataObject.getJSONArray("lastname");
        JSONArray schoolArray =  dataObject.getJSONArray("school");
        JSONArray departmentArray =  dataObject.getJSONArray("department");
        JSONArray eMailArray = dataObject.getJSONArray("emailaddress");
        JSONArray phoneNumberArray = dataObject.getJSONArray("phone");
        JSONArray jobTitleArray = dataObject.getJSONArray("job_title");
        JSONArray locationArray = dataObject.getJSONArray("location");
        //Loop through index of array(s)
        for(int i = 0; i <= numResults; i++)
        {   
            //Store value of JSONArray at index "i" into string variables.
            String firstName = firstNameArray.getString(i);
            String eMail = eMailArray.getString(i);
            String phone = phoneNumberArray.getString(i);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_FIRST, firstName);
            map.put(TAG_EMAIL, eMail);
            map.put(TAG_PHONE, phone);

            //add the hashmap to array list.
            contactList.add(map);
        }*/
    }
    catch (JSONException e) {
        e.printStackTrace();
    }

    /**
     * Updating parsed JSON data into ListView
     * */
    //ListAdapter adapter = new SimpleAdapter(this, contactList,
    //      R.layout.list_item,
    //      new String[] { TAG_FIRST, TAG_EMAIL, TAG_PHONE }, new int[] {
    //              R.id.name, R.id.email, R.id.mobile });

    //setListAdapter(adapter);



}

}

我的 JSONParser 类 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;

}

}

我可能在这里做了一些非常愚蠢的事情,我是新手,所以请让我休息一下,哈哈。我很感激你们可能为我提供的任何信息。

出于好奇,最终目标是搜索数据库(名字、姓氏、学校和部门)并将结果放入列表视图中,单击时会弹出一个窗口,显示其他相关信息以及其他一些功能。

似乎我看到他们从 url 收到的 JSON 输出的每个示例的格式都大不相同,所以即使有大量可用的示例,我也无法完成此操作(抱歉重新发布)。再次感谢您的任何帮助。

编辑 1:LOGCAT:

 04-17 00:45:35.828: W/System.err(305): java.net.UnknownHostException:     api.androidhive.info
04-17 00:45:35.828: W/System.err(305):  at java.net.InetAddress.lookupHostByName(InetAddress.java:513)
04-17 00:45:35.838: W/System.err(305):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:278)
04-17 00:45:35.838: W/System.err(305):  at java.net.InetAddress.getAllByName(InetAddress.java:242)
04-17 00:45:35.838: W/System.err(305):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
04-17 00:45:35.838: W/System.err(305):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-17 00:45:35.838: W/System.err(305):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-17 00:45:35.838: W/System.err(305):  at    org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
04-17 00:45:35.838: W/System.err(305):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-17 00:45:35.838: W/System.err(305):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-17 00:45:35.838: W/System.err(305):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-17 00:45:35.838: W/System.err(305):  at directory.plus.JSONParser.getJSONFromUrl(JSONParser.java:39)
04-17 00:45:35.838: W/System.err(305):  at directory.plus.Directory_finalActivity.onCreate(Directory_finalActivity.java:53)
04-17 00:45:35.849: W/System.err(305):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-17 00:45:35.849: W/System.err(305):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-17 00:45:35.849: W/System.err(305):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-17 00:45:35.849: W/System.err(305):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-17 00:45:35.849: W/System.err(305):  at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-17 00:45:35.849: W/System.err(305):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 00:45:35.849: W/System.err(305):  at android.os.Looper.loop(Looper.java:123)
04-17 00:45:35.849: W/System.err(305):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-17 00:45:35.849: W/System.err(305):  at java.lang.reflect.Method.invokeNative(Native Method)
04-17 00:45:35.849: W/System.err(305):  at java.lang.reflect.Method.invoke(Method.java:521)
04-17 00:45:35.858: W/System.err(305):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-17 00:45:35.858: W/System.err(305):  at  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-17 00:45:35.858: W/System.err(305):  at dalvik.system.NativeStart.main(Native Method)
04-17 00:45:35.858: E/Buffer Error(305): Error converting result java.lang.NullPointerException
04-17 00:45:35.868: E/JSON Parser(305): Error parsing data org.json.JSONException: End of input at character 0 of 
04-17 00:45:35.868: D/AndroidRuntime(305): Shutting down VM
04-17 00:45:35.868: W/dalvikvm(305): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-17 00:45:35.888: E/AndroidRuntime(305): FATAL EXCEPTION: main
04-17 00:45:35.888: E/AndroidRuntime(305): java.lang.RuntimeException: Unable to start activity ComponentInfo{directory.plus/directory.plus.Directory_finalActivity}: java.lang.NullPointerException
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.os.Looper.loop(Looper.java:123)
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-17 00:45:35.888: E/AndroidRuntime(305):  at java.lang.reflect.Method.invokeNative(Native Method)
04-17 00:45:35.888: E/AndroidRuntime(305):  at java.lang.reflect.Method.invoke(Method.java:521)
04-17 00:45:35.888: E/AndroidRuntime(305):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-17 00:45:35.888: E/AndroidRuntime(305):  at  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-17 00:45:35.888: E/AndroidRuntime(305):  at dalvik.system.NativeStart.main(Native Method)
04-17 00:45:35.888: E/AndroidRuntime(305): Caused by: java.lang.NullPointerException
04-17 00:45:35.888: E/AndroidRuntime(305):  at directory.plus.Directory_finalActivity.onCreate(Directory_finalActivity.java:59)
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-17 00:45:35.888: E/AndroidRuntime(305):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

编辑 2:新的 LOGCAT 输出:

04-17 01:26:12.899: E/JSON Parser(548): Error parsing data in JSONParser org.json.JSONException: Value <wddxPacket of type java.lang.String cannot be converted to JSONObject
04-17 01:26:12.899: D/AndroidRuntime(548): Shutting down VM
04-17 01:26:12.899: W/dalvikvm(548): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-17 01:26:12.919: E/AndroidRuntime(548): FATAL EXCEPTION: main
04-17 01:26:12.919: E/AndroidRuntime(548): java.lang.RuntimeException: Unable to start activity ComponentInfo{directory.plus/directory.plus.Directory_finalActivity}: java.lang.NullPointerException
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.os.Looper.loop(Looper.java:123)
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-17 01:26:12.919: E/AndroidRuntime(548):  at java.lang.reflect.Method.invokeNative(Native Method)
04-17 01:26:12.919: E/AndroidRuntime(548):  at java.lang.reflect.Method.invoke(Method.java:521)
04-17 01:26:12.919: E/AndroidRuntime(548):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-17 01:26:12.919: E/AndroidRuntime(548):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-17 01:26:12.919: E/AndroidRuntime(548):  at dalvik.system.NativeStart.main(Native Method)
04-17 01:26:12.919: E/AndroidRuntime(548): Caused by: java.lang.NullPointerException
04-17 01:26:12.919: E/AndroidRuntime(548):  at directory.plus.Directory_finalActivity.onCreate(Directory_finalActivity.java:59)
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-17 01:26:12.919: E/AndroidRuntime(548):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-17 01:26:12.919: E/AndroidRuntime(548):  ... 11 more
04-17 01:26:33.279: I/Process(548): Sending signal. PID: 548 SIG: 9

编辑最后:问题已解决:需要获取从 html 返回的结果的子字符串并将其传递给 json 对象

4

1 回答 1

3

java.net.UnknownHostException:api.androidhive.info

您的应用似乎无法访问网络。您是否添加了:

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

到您的代码 AndroidManifest.xml?

于 2012-04-17T01:06:04.347 回答