2013-05-06 89 views
0

我編寫了這個代碼來讀取和寫入web服務器(mysql databse)的數據,然後所有的數據將顯示在我的andriod應用程序上。從網絡服務器獲取數據的問題

在這方面,我使用PHP服務從Web服務器讀取和寫入數據。一切工作正常它正確地獲取來自Web服務器的數據,但是,當它到達這條線:

int success = jsonObject.getInt(TAG_SUCCESS); 

它顯示了一個空指針異常,我不知道爲什麼,但它實際上讓我瘋了。

代碼:

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

     import org.apache.http.NameValuePair; 
     import org.apache.commons.collections.*; 


     //import org.json.JSONObject; 

     import android.os.AsyncTask; 
     import android.os.Bundle; 
     import android.app.Activity; 
     import android.app.ProgressDialog; 
     import android.util.Log; 
     import android.view.Menu; 
     import android.view.View; 
     import android.widget.Button; 
     import android.widget.ListAdapter; 
     import android.widget.ListView; 
     import android.widget.SimpleAdapter; 
     import org.json.*; 
     public class MiddleActivity extends Activity { 

      Button btnMiddleDB; 

      ProgressDialog pDialog ; 

      JSONParser jsonParser = new JSONParser(); 

      JSONArray places = null; 


      private static final String URL = "http://192.168.1.2/android_connect/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_PID = "pid"; 
      private static final String TAG_NAME = "name"; 

      ArrayList<HashMap<String, String>> placesList; 



      @Override 
      protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_middle); 

       new LoadGettingFromDatabase().execute(); 
       btnMiddleDB = (Button) findViewById(R.id.button1); 

       btnMiddleDB.setOnClickListener(new View.OnClickListener() { 

        @Override 
        public void onClick(View arg0) { 


        } 
       }); 

      } 

運行後臺線程從網絡服務器

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

       @Override 
       protected void onPreExecute() { 
        super.onPreExecute(); 
        pDialog = new ProgressDialog(MiddleActivity.this); 
        pDialog.setMessage("Getting from database..."); 
        pDialog.setIndeterminate(false); 
        pDialog.setCancelable(true); 
        pDialog.show(); 
       } 
     **after getting data from webserver parse it to json and store it into string** 
       @Override 
       protected String doInBackground(String... args) { 

        List<NameValuePair> params = new ArrayList<NameValuePair>(); 
        Log.d("Seen","seen1"); 
        JSONObject jsonObject = jsonParser.makeHttpRequest(URL, "GET" ,params); 
        Log.d("String","JSON 2"); 

        //Log.d("All entries","Entries" + jsonObject.toString()); 

        try{ 
         Log.d("Seen","seen2"); 

獲取數據實際上問題是在這裏

int success = jsonObject.getInt(TAG_SUCCESS); 
          Log.d("Seen","seen5"); 
          if(success == 1){ 
           //Entries found 
           Log.d("Seen","seen6"); 
           places = jsonObject.getJSONArray(TAG_PRODUCTS); 
           for(int i=0;i<places.length();i++){ 
            JSONObject temp = places.getJSONObject(i); 

            String id = temp.getString(TAG_PID); 
            String name = temp.getString(TAG_NAME); 

            HashMap<String, String> hashMap = new HashMap<String, String>(); 

            hashMap.put(TAG_PID, id); 
            hashMap.put(TAG_NAME, name); 

            placesList.add(hashMap); 
           } 

          } 
         } catch (Exception e) { 
          Log.e("success","success status " + e); 
         }  

         return null; 
        } 

        public void onProExecute(String file_url){ 
         pDialog.dismiss(); 
         runOnUiThread(new Runnable(){ 
          public void run(){ 
           ListAdapter listAdapter = new SimpleAdapter(MiddleActivity.this, placesList, R.layout.list_item, new String[]{ 
            TAG_PID, TAG_NAME},new int[]{R.id.ID, R.id.Name}); 
           ListView listView = (ListView) findViewById(R.layout.list_item); 
           listView.setAdapter(listAdapter); 
           }; 
          }); 
         }; 
        } 

       @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_middle, menu); 
        return true; 
       } 


       } 

     **and log cat is** 



05-07 00:29:54.419: D/Seen(30282): seen1 

     05-07 00:29:54.569: D/Seen(30282): seen3 

     05-07 00:29:54.909: D/Seen(30282): seen4 

     05-07 00:29:54.979: D/String(30282): JSON get_all_products.php 

     05-07 00:29:54.979: D/String(30282): db_connect.php 

     05-07 00:29:54.979: D/String(30282): db_config.php 

     05-07 00:29:54.979: D/String(30282): {"success":0,"message":"No products found 
     05-07 00:29:55.300: D/String(30282): JSON 1 

     05-07 00:29:55.300: D/String(30282): JSON 2 

     05-07 00:29:55.310: D/Seen(30282): seen2 

    **05-07 00:29:55.310: E/success(30282): success status 

java.lang.NullPointerException** 


and here is my jsonparser class 
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

你的JSONObject爲空,通過在線設置斷點來調試應用程序 - >

JSONObject jsonObject = jsonParser.makeHttpRequest(URL, "GET" ,params); 

並檢查jsonObject的值。

+0

我知道它返回null.actually這是要解決的問題:p – Shazar 2013-05-06 20:18:23

+0

你可以發佈JsonParser.makeHttpRequest()的代碼? – 2013-05-06 20:30:27

+0

我已經發布它PLZ通過 – Shazar 2013-05-06 21:34:46