2013-03-27 79 views
0

我需要從MySQL數據庫收集數據並顯示在ListView中,因此我創建了一個Web服務並將其託管在服務器上。然後我開始開發應用程序,但我無法得到結果,我的應用程序崩潰,錯誤日誌中沒有錯誤。調用Web服務時應用程序崩潰

這是我到顯示結果代碼

package com.hotelapp.test; 

import android.app.Activity; 
import android.app.ListActivity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.*; 
import org.apache.http.NameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

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

public class AllProductsActivity extends ListActivity { 

    //Progress Dialog 

    private ProgressDialog pDialog; 


    //JSONPraser 
JSONParser jParser = new JSONParser(); 

ArrayList<HashMap<String,String>> productsList; 

//url to get records 
private static String url_all_products = "http://54.243.58.156/get_all_products.php"; 

//Json Node Names 
private static final String TAG_SUCCESS="success"; 
private static final String TAG_PRODUCTS="products"; 
private static final String TAG_HID="hid"; 
private static final String TAG_NAME="name"; 

JSONArray products = null; 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.all_products); 

    //Hashmap for List 

    productsList = new ArrayList<HashMap<String, String>>(); 

    //Load Products In Backgound 
    new LoadAllProducts().execute(); 

    //GEt Listview 
    ListView lv = getListView(); 

    // on seleting single product 
    // launching Edit Product Screen 
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      // getting values from selected ListItem 
      String hid = ((TextView) view.findViewById(R.id.hid)).getText().toString(); 
      //Starting new Intnet 
      Intent in = new Intent(getApplicationContext(),EditProductActivity.class); 
      in.putExtra(TAG_HID,hid); 
      startActivityForResult(in,100); 
     } 
    }); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    // if result code 100 
    if (resultCode == 100) { 
     // if result code 100 is received 
     // means user edited/deleted product 
     // reload this screen again 
     Intent intent = getIntent(); 
     finish(); 
     startActivity(intent); 
    } 

} 

/** 
* Background Async Task to Load all product by making HTTP Request 
* */ 

class LoadAllProducts extends AsyncTask<String,String,String>{ 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 

    protected void onPerExecute(){ 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(AllProductsActivity.this); 
     pDialog.setMessage("Loading Products...Please Wait"); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 


    /** 
    * getting All products from url 
    * */ 
    @Override 
    protected String doInBackground(String... strings) { 
     // Building Parameters 
     List<NameValuePair> param = new ArrayList<NameValuePair>(); 

     JSONObject json = jParser.makeHttpRequest(url_all_products,"GET",param); 

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

     try { 
      //Cehck for SUCCESS TAG 


      int success = json.getInt(TAG_SUCCESS); 

      if(success ==1){ 
       //Get Product Arra 

       products = json.getJSONArray(TAG_PRODUCTS); 

       //Looping arrays 
       for(int i=0; i<products.length();i++){ 
        JSONObject c = products.getJSONObject(i); 

        String id = c.getString(TAG_HID); 
        String name = c.getString(TAG_NAME); 

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

        map.put(TAG_HID,id); 
        map.put(TAG_NAME,name); 

        productsList.add(map); 

       } 
      } else { 
       // no products found 
       // Launch Add New product Activity 
       Intent i = new Intent(getApplicationContext(), 
         NewProductActivity.class); 
       // Closing all previous activities 
       i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(i); 
      } 

     } catch (JSONException e){ 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    protected void onPostExecute (String file_url){ 
     //dismiss the dialog after getting all products 
     pDialog.dismiss(); 

     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       ListAdapter adapter = new SimpleAdapter(
         AllProductsActivity.this,productsList,R.layout.list_item,new String[]{TAG_HID,TAG_NAME}, 
         new int[]{R.id.hid,R.id.name} 
       ); 

       setListAdapter(adapter); 
      } 
     }); 
    } 
} 
} 

這是我的JSON分析器

package com.hotelapp.test; 


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

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
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() { 

} 

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

您是否將INTERNET權限添加到清單中? – Blackbelt 2013-03-27 14:20:56

+0

在logcat – 2013-03-27 14:21:11

回答

3

我的猜測是,你的問題是因爲在你的AsyncTask的方法之一是不正確命名:

protected void onPerExecute(){ 

它應該是:

protected void onPreExecute(){ 

您可能正在獲取NULL指針,因爲您要在此方法中創建的資源實際上並未創建。

+0

+1中必須有一些錯誤或警告, – Blackbelt 2013-03-27 14:21:32

0

要檢測此類拼寫錯誤,最好使用註釋@overwrite。如果名稱不正確,它將產生編譯錯誤。它似乎已被意外刪除