2013-05-06 67 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