0

在尝试了一些提供的解决方案后,我能够从服务器检索响应,但仍然无法显示我收到的 JSON 数组并且应用程序崩溃,请帮助我:

Logcat 错误

07-07 11:12:09.500: E/AndroidRuntime(1829): FATAL EXCEPTION: main
07-07 11:12:09.500: E/AndroidRuntime(1829): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.g2k/com.example.g2k.HotelSearch}: java.lang.NullPointerException: println needs a message
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.os.Looper.loop(Looper.java:137)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.main(ActivityThread.java:5039)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at java.lang.reflect.Method.invokeNative(Native Method)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at java.lang.reflect.Method.invoke(Method.java:511)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at dalvik.system.NativeStart.main(Native Method)
07-07 11:12:09.500: E/AndroidRuntime(1829): Caused by: java.lang.NullPointerException: println needs a message
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.util.Log.println_native(Native Method)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.util.Log.v(Log.java:117)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at com.example.g2k.HotelSearch.onCreate(HotelSearch.java:22)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.Activity.performCreate(Activity.java:5104)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-07 11:12:09.500: E/AndroidRuntime(1829):     ... 11 more
07-07 11:12:14.430: E/Trace(1848): error opening trace file: No such file or directory (2)

源代码:

public class HotelBook extends Activity {
private String resp;

private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> hotelsList;
HashMap<String, String> map;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_HOTEL = "hotels";
private static final String TAG_PID = "hotel_id";
private static final String TAG_NAME = "hotel_name";
private static final String TAG_AREA = "area";
private static final String TAG_RATING = "star_rating";
private static final String TAG_IMAGE = "image";
private static final String TAG_GOVRATE = "govrating";
private static final String TAG_PRICE = "price";

private String city_id = "feedbacktype2";
// products JSONArray
JSONArray hotels = null;

Button sendPostReqButton;
private static final String url = "http://10.0.2.2/android_connect/search_hotel.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hotelbook);
    // Hashmap for ListView
    hotelsList = new ArrayList<HashMap<String, String>>();

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    sendPostReqButton = (Button) findViewById(R.id.button1);
    addListenerOnButton();
}

public void addListenerOnButton() {

    sendPostReqButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Get the data
            // Loading products in Background Thread
            new GetHotel().execute();
        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_hotelbook, menu);
    return true;
}

class GetHotel extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        /*
         * pDialog = new ProgressDialog(HotelbookActivity.this);
         * pDialog.setMessage("Loading hotels. Please wait...");
         * pDialog.setIndeterminate(false); pDialog.setCancelable(false);
         * pDialog.show();
         */
    }

    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("cityid", city_id));

        // getting JSON string from URL
        JSONObject json = null;
        try {
            json = jParser.makeHttpRequest(url, "GET", params);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            // Check your log cat for JSON reponse
            Log.e("All hotels: ", e1.toString());
        }

        // Check your log cat for JSON reponse
        Log.d("All hotels: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = 1;
            // json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                hotels = json.getJSONArray(TAG_HOTEL);

                // looping through All Products
                for (int i = 0; i < hotels.length(); i++) {
                    JSONObject c = hotels.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String area = c.getString(TAG_AREA);
                    String rating = c.getString(TAG_RATING);
                    String image = c.getString(TAG_IMAGE);
                    String price = c.getString(TAG_PRICE);
                    String govrate = c.getString(TAG_GOVRATE);
                    // creating new HashMap
                    map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_AREA, area);
                    map.put(TAG_RATING, rating);
                    map.put(TAG_IMAGE, image);
                    map.put(TAG_PRICE, price);
                    map.put(TAG_GOVRATE, govrate);

                    // adding HashList to ArrayList
                    hotelsList.add(map);
                }

            } else {

            }
        } catch (JSONException e) {
            Log.e("response error", json.toString(), e);
        }

        return null;
    }

    protected void onPostExecute(String file_url) {

        Intent intent = new Intent(HotelBook.this, HotelSearch.class);
        intent.putExtra("map", map);
        startActivity(intent);
    }
}

}

JSONParser 类:

public class JSONParser {

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

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) throws IOException {

    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

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

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            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");
        }

        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    } finally {
        is.close();
    }

    // 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;

}

}
4

2 回答 2

0

您的 logcat 指向 HotelbookActivity.java 第 154 行,您在其中对nulled 对象执行操作:

Caused by: java.lang.NullPointerException
07-05 08:36:07.533: E/AndroidRuntime(1073): at
        com.example.go2kashmir.HotelbookActivity$GetHotel
        .doInBackground(HotelbookActivity.java:154)

编辑

如果如您所说的第 154 行是在json访问附近,那么这一行:

Log.d("All hotels: ", json.toString());

应该记录:

All hotels: null

确认(toString()在这种情况下不需要明确)。记录您所做的原始响应以查看服务器返回的jParser内容。makeHttpRequest()问题潜伏在那里。

于 2013-07-05T09:33:58.543 回答
0

您没有按预期使用日志功能。第一个参数应该识别上下文,而消息应该是第二个参数。

相反,做类似的事情

Log.d("MyActivity", "Object of interest is " + objectOfInterest);

这样,如果对象为空,您将收到一条日志消息,而不是异常。

于 2013-07-07T12:55:19.883 回答