2013-07-05 86 views
0

嘗試了一些提供的解決方案後,我能夠從服務器獲取響應,但仍然無法顯示我收到的JSON數組,並且應用程序崩潰,請幫助我:與遠程服務器建立連接時發生logcat錯誤

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; 

} 

} 
+0

顯示您的源代碼。主要活動代碼。看來你想在android中不允許的主要活動線程上進行網絡操作。網絡操作可以通過使用AsyncTask –

回答

0

你的logcat點手指HotelbookActivity.java線154,在那裏你null編輯對象進行操作:

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()); 

手LD日誌:

All hotels: null 

確認(在這種情況下,不需要明確toString())。記錄原始響應您的jParsermakeHttpRequest()做看看真正的服務器返回。問題隱藏在那裏。

+0

謝謝,但我無法跟蹤哪個返回調用導致NullPointerException,我是一個Android新手對不起我。 – user2546015

+1

我們寧可不去猜測這行是154,所以如果你想幫助你需要告訴我們, –

+0

線154 \t \t \t \t如果(成功== 1){ \t \t \t酒店= json.getJSONArray( TAG_HOTEL); – user2546015

0

您沒有按照預期使用日誌功能。第一個參數應該是識別上下文,而該消息應該是第二個參數。

相反,這樣做

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

這樣一來,如果對象是不是一個例外空,你會得到一個日誌消息這樣說。

+0

Thnax,我的問題已解決:) – user2546015

相關問題