2012-11-03 25 views
0

我的應用程序似乎沒有正確拉取來自PHP webservice的JSON數據。應用程序不會從PHP webservice檢索JSON數據。 Webservice正常工作

訪問webservice的函數以從數據庫獲取所有數據記錄會正確生成JSON,但我的應用程序無法獲取該數據,並且似乎以NullPointerException結尾。

logcat的問題我:

更新:

注意到黃色此錯誤下面的錯誤之前出現這種情況:

W/System.err的(835): org.apache.http.conn.HttpHostConnectException: 連接到http://本地主機拒絕

如果我無法連接到我的本地主機上的web服務,那麼我沒有得到我的應用程序的JSON。但爲什麼它會拒絕連接到本地主機?

W/System.err的(1159):在 com.example.myfirstapp.MainActivity $ LoadAllCars.doInBackground(MainActivity.java:113) W/System.err的(1159):在 com。示例(MainActivity.java:116) E/AndroidRuntime(1159) :at com.example.myfirstapp.MainActivity $ LoadAllCars.doInBackground(MainActivity.java:1) E/WindowManager(1159):at com.example.myfirstapp.MainActivity $ LoadAllCars.onPreExecute(MainAc tivity.java:103)

113行:JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params); 線116:Log.d("All Cars: ", json.toString());

MainActivity

package com.example.myfirstproject; 

//imports 

public class MainActivity extends ListActivity implements OnItemClickListener { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

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

    ArrayList<HashMap<String, String>> carsList; 

    // url to get all products list 
    private static String url_all_cars = "http://localhost/webservice/get_all_cars.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_CARS = "cars"; 
    private static final String TAG_NAME = "name"; 

    // products JSONArray 
    JSONArray cars = null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // Hashmap for ListView 
     carsList = new ArrayList<HashMap<String, String>>(); 

     // Loading products in Background Thread 
     new LoadAllcars().execute(); 

     // Get listview 
     ListView lv = getListView(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 

    /** 
    * Background Async Task to Load all product by making HTTP Request 
    * */ 
    class LoadAllcars extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Loading cars. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     /** 
     * getting All products from url 
     * */ 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      // getting JSON string from URL 
      JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params); 

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

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

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

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

         // Storing each json item in variable 
         String title = c.getString(TAG_NAME); 

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

         // adding each child node to HashMap key => value 
         map.put(TAG_NAME, name); 

         // adding HashList to ArrayList 
         carsList.add(map); 
        } 
       } else { 
        // no products found 
        pDialog = new ProgressDialog(MainActivity.this); 
        pDialog.setMessage("No cars found"); 
        pDialog.setIndeterminate(false); 
        pDialog.setCancelable(false); 
        pDialog.show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog after getting all products 
      pDialog.dismiss(); 
      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        /** 
        * Updating parsed JSON data into ListView 
        * */ 
        ListAdapter adapter = new SimpleAdapter(
          MainActivity.this, carsList, 
          android.R.id.list, new String[] {TAG_NAME}, 
          new int[] { R.id.title }); 
        // updating listview 
        setListAdapter(adapter); 
       } 
      }); 

     } 
    } 
} 

EDIT

JSONParser:

public class JSONParser { 

    static InputStream is = null; 
    static 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) { 

     // 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"); 
      } 
      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; 

    } 
} 
+0

什麼'makeHttpRequest(...)'看起來像?什麼類型的類是'jParser' –

+0

@JamesM 我的不好。我已經用具有該功能的JSONParser類更新了答案。 – user1701467

回答

1

那麼,如果你是在這條線得到一個空指針異常

JSONObject的JSON = jParser.makeHttpRequest(url_all_cars, 「GET」,則params);

那麼其中的一個或多個東西必須爲空。 jParser被實例化,url字符串也是,params是一個列表,但是列表中沒有任何內容。看看jParser,看看那些參數列表中發生了什麼。你需要他們嗎?它需要它們嗎?

編輯

所以jParser是您的列表(爲空)轉換爲用字符串生成的字符串。這是返回一個空洞的刺痛。

所以當它被髮送到服務器您的網址看起來像這樣

http://localhost/webservice/get_all_cars.php? 

所以正常的URL,但上有一個問號。那是對的嗎?

這將是有意義的記錄從您的HttpResponse的的StatusCode和狀態的原因,所以你可以看到服務器responsing你會做這樣的...

Log.d("Class Name", "Status code: " + httpResponse.getStatusLine().getStatusCode() + " Status Phrase: " + httpResponse.getStatusLine().getReasonPhrase()); 

編輯

該網址設置爲「本地主機」,所以我認爲它正在設備內而不是在您的服務器。把你的服務器的IP地址代替

+1

這個問題很有可能當它試圖讀取__json__對象時,這意味着返回值不爲參數之一。 –

+0

公平地說,有很多事情可能會出錯。我們只是看到調用某些東西來創建請求的代碼,連接到服務器然後解碼響應。我猜想在logcat中應該有更多他可以發佈的內容,因爲該特定行上沒有任何空值。 –

+0

@samdoward 對不起,延遲迴復。試圖弄清楚。我用更多的代碼更新了我的答案。 JSONParser是導致此問題的對象,但我無法明白原因。 – user1701467

1

我認爲你的問題可能是你從來沒有把任何東西放在params。這只是一個空的List

+0

但我已按照本教程進行操作:'http://www.androidhive.info/2012/05/how-to-connect-android-with-php -mysql /'應該沒問題。我只是沒有包含任何CRUD功能。 – user1701467

+1

如果我有任何建議給,在調試模式下運行你的應用程序,並通過,你可以看到什麼是空的,並導致此錯誤。 –

0

問題在這裏:

private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";

不能使用localhost,因爲模擬手機本身localhost/127.0.0.1

您需要更改localhost10.0.2.2

private static String url_all_cars = "http://10.0.2.2/webservice/get_all_cars.php";

+0

您運行的任何設備都是本地主機。它不是特定於仿真器 –

相關問題