2014-04-01 48 views
1

我正在學習JsonParsing。在這我有一些category_list陣列。我解析數組中的數據並將其綁定到android中的listView。從那個列表中,我還需要對該Web服務進行API調用,並檢查sub-category是否存在?如果沒有子類別,那麼它將是product list。我已經嘗試如下,但我無法從productList解析json如何檢查天氣JsonArray值可用或不從web服務的android並獲取其數據?

如何決定或給我任何解決方案的邏輯。我的代碼如下:

main.java

package com.epe.yehki.ui; 

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

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import com.epe.yehki.backend.ServiceHandler; 
import com.epe.yehki.uc.Header; 
import com.example.yehki.R; 

import android.R.string; 
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.AdapterView; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 
import android.widget.AdapterView.OnItemClickListener; 

public class SubCategoryActivity extends ListActivity { 
    // SUB CATEGORIES... 
    private static final String TAG_CAT_LlIS = "categories_list"; 
    private static final String TAG_CAT_ID = "category_id"; 
    private static final String TAG_CAT_NAME = "category_name"; 
    int flag; 
    public Header header; 
    public TextView title; 
    // PRODUCTS.... 
    private static final String TAG_PRODUCT_ID = "product_id"; 
    private static final String TAG_PRODUCT_LlST = "product_list"; 
    private static final String TAG_PRODUCT_NAME = "product_name"; 
    private static final String TAG_PRODUCT_IMG = "image"; 
    private static final String TAG_PRODUCT_DESCRIPTION = "detail_description"; 

    // contacts JSONArray 
    JSONArray subcategories = null; 
    JSONArray products = null; 
    public String catid; 
    public String id; 
    String name; 
    JSONObject jsonObj; 

    // Hashmap for ListView 
    ArrayList<HashMap<String, String>> subcategoryList; 
    ArrayList<HashMap<String, String>> productList; 

    private ProgressDialog pDialog; 

    // URL to get contacts JSON 
    private static String url = "http://yehki.epagestore.in/app_api/categories.php"; 

    private static String mainurl = "http://yehki.epagestore.in/"; 
    public String suburl = ""; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_sub); 
     this.header = (Header) findViewById(R.id.headersubcat); 
     title = (TextView) findViewById(R.id.title); 
     // getting intent data 
     Intent in = getIntent(); 

     // Get JSON values from previous intent 

     try { 
      catid = in.getStringExtra(TAG_CAT_ID); 
      name = in.getStringExtra(TAG_CAT_NAME); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     System.out.println("::::::::::::::MY CATEGORY ID::::::::::::::IN SUB " 
       + catid); 
     subcategoryList = new ArrayList<HashMap<String, String>>(); 

     suburl = "http://yehki.epagestore.in/app_api/categories.php?" 
       + TAG_CAT_ID + "=" + catid; 
     System.out.println("::::::::::::::::MY SUBCATEGORY URL::::::::::::" 
       + suburl); 
     title.setText(name); 

     // Displaying all values on the screen 

     ListView lv = getListView(); 
     new GetSubCategories().execute(); 

     // Listview on item click listener 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       // getting values from selected ListItem 
       String catname = ((TextView) view.findViewById(R.id.name)) 
         .getText().toString(); 

       Intent in = new Intent(getApplicationContext(), 
         SubCategoryTwoActivity.class); 
       in.putExtra(TAG_CAT_NAME, catname); 
       in.putExtra(TAG_CAT_ID, catid); 

       startActivity(in); 

      } 
     }); 

    } 

    private class GetSubCategories extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(SubCategoryActivity.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      // Creating service handler class instance 
      ServiceHandler sh = new ServiceHandler(); 
      System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::" 
        + suburl); 
      // Making a request to url and getting response 
      String jsonStr = sh.makeServiceCall(suburl, ServiceHandler.GET); 

      Log.d("Response: ", "> " + jsonStr); 
      if (jsonStr != null) { 
       try { 
        jsonObj = new JSONObject(jsonStr); 

        // Getting JSON Array node 
        if (jsonObj.has(TAG_CAT_LlIS)) { 
         subcategories = jsonObj.getJSONArray(TAG_CAT_LlIS); 
         if (subcategories != null 
           && subcategories.length() != 0) { 
          // looping through All Contacts 
          flag = 0; 
          System.out 
            .println(":::::::::::FLAG IN SUB:::::::::::" 
              + subcategories.length()); 
          for (int i = 0; i < subcategories.length(); i++) { 
           JSONObject c = subcategories.getJSONObject(i); 

           id = c.getString(TAG_CAT_ID); 
           String name = c.getString(TAG_CAT_NAME); 

           // tmp hashmap for single category 
           HashMap<String, String> subcategory = new HashMap<String, String>(); 

           // adding each child node to HashMap key => 
           // value 
           subcategory.put(TAG_CAT_ID, id); 
           subcategory.put(TAG_CAT_NAME, name); 

           // adding contact to contact list 
           subcategoryList.add(subcategory); 
          } 
         } 
        } else { 
         flag = 1; 
         products = jsonObj.getJSONArray(TAG_PRODUCT_LlST); 

         System.out 
           .println("==========SIZE OF MY ARRAY PRODUCT LIST===================" 
             + products.length()); 
         System.out 
           .println(":::::::::::::::::::Product array:::::::::::::::" 
             + products); 
         // looping through All Contacts 
         for (int i = 0; i < products.length(); i++) { 
          JSONObject p = products.getJSONObject(i); 

          String proId = p.getString(TAG_PRODUCT_ID); 
          String proName = p.getString(TAG_PRODUCT_NAME); 
          String productImg = p.getString(TAG_PRODUCT_IMG); 
          String productDesc = p 
            .getString(TAG_PRODUCT_DESCRIPTION); 
          System.out 
            .println("::::::::::::::::MY PRODUCT DETAILS::::::::::::::" 
              + TAG_PRODUCT_ID 
              + " PRODUCT NAME   " 
              + TAG_PRODUCT_NAME 
              + " PRODUCT_DESCRIPTION  " 
              + TAG_PRODUCT_DESCRIPTION 
              + " PRODUCT IMAGE " 
              + TAG_PRODUCT_IMG); 

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

          // adding each child node to HashMap key => value 
          // product.put(TAG_PRODUCT_ID, proId); 
          product.put(TAG_PRODUCT_NAME, proName); 

          product.put(TAG_PRODUCT_DESCRIPTION, productDesc); 
          /* 
          * product.put(TAG_PRODUCT_IMG, productImg); 
          */ 
          productList.add(product); 
         } 

        } 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } else { 
       Log.e("ServiceHandler", "Couldn't get any data from the url"); 
      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 
      /** 
      * Updating parsed JSON data into ListView 
      * 
      * */ 

      if (flag == 0) { 

       ListAdapter adapter = new SimpleAdapter(
         SubCategoryActivity.this, subcategoryList, 
         R.layout.list_item, new String[] { TAG_CAT_NAME }, 
         new int[] { R.id.name }); 
       setListAdapter(adapter); 
      } else { 
       ListAdapter adapter = new SimpleAdapter(
         SubCategoryActivity.this, subcategoryList, 
         R.layout.activity_single_produt, new String[] { 
           TAG_PRODUCT_NAME, TAG_PRODUCT_DESCRIPTION, 
           TAG_PRODUCT_IMG }, new int[] { 
           R.id.product_label, R.id.product_desc, 
           R.id.iv_product_img }); 
       setListAdapter(adapter); 
      } 

     } 

    } 
} 

回答

4

試試這個:

if(jsonObj.has("name_of_the_field")){ 
    //yes 
} 

JSONArray mJSONArray = jsonObj.optJSONArray("name of array"); 

方法optJSONArray("nameofarray")將返回一個空JSONArray如果找不到JSONArray與提供的名稱。

+0

@ SMR-謝謝you.sir –

0

嗯有一個方法來檢查,如果鑰匙JSON的存在與否。 就好像你有json數組並且你想要檢查是否存在子類別而不是該數組對象上的調用方法 。

0

JSONObject有方法檢查是否存在於JSON中。

從文檔引用。

public boolean has (String name)  
//Returns true if this object has a mapping for name. The mapping may be NULL. 

你可以找到的官方文檔here

相關問題