2015-09-07 65 views
0
public class AllProductsActivity extends ListActivity { 

    ListView list; 
    TextView id; 
    TextView name; 
    // Progress Dialog 
    private ProgressDialog pDialog; 

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

    ArrayList<HashMap<String, String>> productsList; 

    // url to get all products list 
    private static String url_all_products = "http://192.168.1.3/app/a.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_TRUE = "true"; 
    private static final String TAG_PRODUCTS = "product"; 
    private static final String TAG_PID = "pid"; 
    private static final String TAG_NAME = "name"; 
    String pid,names,j; 
    String s; 
    // products JSONArray 
    JSONArray product = null; 
    JSONObject n = null; 

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

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


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

    // Response from Edit Product Activity 


    /** 
    * 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 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      id = (TextView) findViewById(R.id.pid); 
      name = (TextView) findViewById(R.id.name); 
      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... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      // getting JSON string from URL 
      JSONArray json = jParser.makeHttpRequest(url_all_products, "GET", params); 

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

      jsonResponse = new JSONObject(); 
      try { 
       product = jsonResponse.getJSONArray(TAG_TRUE); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      int c = jsonResponse.optInt(TAG_SUCCESS); 
      if(c==1) 
      { 

         j = jsonResponse.optString(TAG_PRODUCTS); 
         for(int i=0;i<j.length();i++){ 

    //      productsList.(json.getString(i));  
         pid = jsonResponse.optString(TAG_PID); 
         names = jsonResponse.optString(TAG_NAME); 


         } 


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


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

       // adding HashList to ArrayList 
       productsList.add(map); 
      } 
       else { 
        // no products found 
        // Launch Add New product Activity 
        Intent i = new Intent(getApplicationContext(), 
          MainActivity.class); 
     //    Closing all previous activities 
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(i); 
       } 


      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     @Override 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog after getting all products 
      pDialog.dismiss(); 
      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        /** 
        * Updating parsed JSON data into ListView 
        * */ 

        ListAdapter adapter = new SimpleAdapter(
    AllProductsActivity.this, productsList, R.layout.list_item, new String[] {     TAG_PID, TAG_NAME}, new int[] { R.id.pid, R.id.name }); 


    // updating listview 
    setListAdapter(adapter); 

       } 
      }); 
     } 
    } 
} 

PHP代碼解析JSON時出錯 - jsonarray,PHP錯誤沒有值?

<?php 

/* 
* Following code will list all the products 
*/ 

// array for JSON response 
$response = array(); 
$r = array(); 
// get all products from products table 
$db = new PDO('mysql:host=localhost;dbname=androidhive;charset=utf8', 'Sidd'); 

$stmt = $db->query('SELECT * FROM product'); 
$json= array(); 
$json[0]= 'true'; 
//$r["a"] = array(); 

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
    // looping through all results 
    // products node 
     // temp user array 

     $response["product"] = array(); 
     $product = array(); 
     $product["pid"] = $row["pid"]; 
     $product["name"] = $row["name"]; 

     // push single product into final response array 
     array_push($response["product"], $product); 
    // array_push($r["a"], $response); 
    // success 
    $response["success"] = 1; 
    $json[]= $response; 

} 
    // echoing JSON response 
    echo json_encode($json); 

//} 
?> 

錯誤消息

09-07 14:54:00.285: D/AbsListView(10521): Get MotionRecognitionManager 
09-07 14:54:00.290: D/ProgressBar(10521): setProgress = 0 
09-07 14:54:00.290: D/ProgressBar(10521): setProgress = 0, fromUser = false 
09-07 14:54:00.290: D/ProgressBar(10521): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000 
09-07 14:54:00.310: D/AbsListView(10521): onVisibilityChanged() is called, visibility : 4 
09-07 14:54:00.310: D/AbsListView(10521): unregisterIRListener() is called 
09-07 14:54:00.310: D/AbsListView(10521): onVisibilityChanged() is called, visibility : 0 
09-07 14:54:00.310: D/AbsListView(10521): unregisterIRListener() is called 
09-07 14:54:00.335: D/ProgressBar(10521): updateDrawableBounds: left = 0 
09-07 14:54:00.335: D/ProgressBar(10521): updateDrawableBounds: top = 0 
09-07 14:54:00.335: D/ProgressBar(10521): updateDrawableBounds: right = 96 
09-07 14:54:00.335: D/ProgressBar(10521): updateDrawableBounds: bottom = 96 
09-07 14:54:00.395: D/AbsListView(10521): unregisterIRListener() is called 
09-07 14:54:00.445: D/AbsListView(10521): unregisterIRListener() is called 
09-07 14:54:00.520: D/All Products:(10521): ["true",{"product":[{"pid":"1","name":"sid"}],"success":1},{"product":[{"pid":"2","name":"shef"}],"success":1}] 
09-07 14:54:00.520: W/System.err(10521): org.json.JSONException: No value for true 
09-07 14:54:00.525: W/System.err(10521): at org.json.JSONObject.get(JSONObject.java:354) 
09-07 14:54:00.525: W/System.err(10521): at org.json.JSONObject.getJSONArray(JSONObject.java:548) 
09-07 14:54:00.525: W/System.err(10521): at com.example.jsontry.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:104) 
09-07 14:54:00.525: W/System.err(10521): at com.example.jsontry.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1) 
09-07 14:54:00.525: W/System.err(10521): at android.os.AsyncTask$2.call(AsyncTask.java:287) 
09-07 14:54:00.525: W/System.err(10521): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
09-07 14:54:00.525: W/System.err(10521): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
09-07 14:54:00.525: W/System.err(10521): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
09-07 14:54:00.525: W/System.err(10521): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
09-07 14:54:00.525: W/System.err(10521): at java.lang.Thread.run(Thread.java:841) 
09-07 14:54:00.760: D/AbsListView(10521): unregisterIRListener() is called 
09-07 14:54:00.890: D/AbsListView(10521): onDetachedFromWindow 

**

我無法分析的數據。我的代碼有什麼問題?
我是Android新手,我在這裏完全空白。任何幫助將非常感激!
我在這裏嘗試過所有的東西。
如果我必須從數據庫中檢索圖像並在ListView或Android中顯示它們顯示它們,該怎麼辦?

+0

嘗試運行PHP來看看你有沒有所需的輸出,如果它'OK,然後看看你的應用程序 –

+0

請發表您的JSON –

+0

@Rajsundar:我可以看到它是在調試日誌: { 「產品」:[{ 「PID」: 「1」, 「名稱」: 「SID」}]},{ 「產品」:[{ 「PID」: 「1」, 「名稱」: 「SID」},{ 「pid」:「2」,「name」:「shef」}]} –

回答

0

從JSON中刪除像product,success這樣的重複鍵,使用PHP代碼格式化您的JSON,並使其如下所示,例如,它可以幫助您輕鬆解析JSON。 例如:

{"product":[{"pid":"1","name":"sid"},{"pid":"2‌​","name":"shef"}],"success":"1","value":"true"} 

如果您將能夠創建類似上述的JSON。那麼你可以使用下面的代碼

    JSONArray productDetailsJsonArr = reader.getJSONArray("product"); 
        for (int i = 0; i < productDetailsJsonArr.length(); i++) { 
         JSONObject pJsonObj = productDetailsJsonArr.getJSONObject(i); 
         String pid = pJsonObj.getString("pid"); 
         String sid = pJsonObj.getString("sid"); 
        } 

        String success = reader.getString("success"); 
        String value = reader.getString("value"); 
+0

的問題是怎麼回事? :P –

+0

[「true」,{「pid」:「1」,「name」:「sid」},{「pid」:「2」,「name」:「shef」}] 這是正確的嗎? –

0

試試這個解析它:

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) 
{ 

     $product = array(); 
     $product["pid"] = $row["pid"]; 
     $product["name"] = $row["name"]; 
     $response["product"] = $product; 
     unset($product); 
} 
    $response["success"] = 1; 
    $json[]= $response; 
+0

[「true」,{「product」:{「pid」:「2」,「name」:「shef」},「success」:1}] return this。 沒有幫助。 :/ –

+0

預計O/P是什麼? –

+0

[「true」,{「product」:[{「pid」:「1」,「name」:「sid」}],「success」:1},{「product」:[{「pid」:「 2「,」name「:」shef「}],」success「:1}] –

0

有伴的你doInBackground代碼的問題

JSONArray json = jParser.makeHttpRequest(url_all_products, "GET", params);

這裏您得到在json可變數據和無處可用

0

解決了問題,謝謝大家的幫助!我的一些代碼和json回覆有問題! 修正了它。感謝大家的幫助。 :)