2016-06-21 121 views
1

在我的應用程序中,我的json響應中有一個布爾變量。讀取JSON布爾值

[ 
{ 
    "id" : "001", 
    "firstName" : "Mark", 
    "lastName" : "Mason", 
    "role" : "CEO", 
    "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
}, 
{ 
    "teamName" : "iOS", 
    "members" : [ 
     { 
      "id" : "002", 
      "firstName" : "Olly", 
      "lastName" : "Berry", 
      "role" : "iOS Team Lead", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png", 
      "teamLead" : true 
     }, 
     { 
      "id" : "003", 
      "firstName" : "James", 
      "lastName" : "Frost", 
      "role" : "iOS Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "004", 
      "firstName" : "Liam", 
      "lastName" : "Nichols", 
      "role" : "iOS Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "005", 
      "firstName" : "Chris", 
      "lastName" : "Watson", 
      "role" : "iOS Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "006", 
      "firstName" : "Richard", 
      "lastName" : "Turton", 
      "role" : "iOS Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "007", 
      "firstName" : "Matt", 
      "lastName" : "Colliss", 
      "role" : "iOS Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "008", 
      "firstName" : "David", 
      "lastName" : "Gibson", 
      "role" : "iOS Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "009", 
      "firstName" : "Tom", 
      "lastName" : "Guy", 
      "role" : "iOS Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "010", 
      "firstName" : "Rich", 
      "lastName" : "Hodgkins", 
      "role" : "iOS Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     } 
    ] 
}, 
{ 
    "teamName" : "Android", 
    "members" : [{ 
      "id" : "011", 
      "firstName" : "David", 
      "lastName" : "Branton", 
      "role" : "Android Team Lead", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png", 
      "teamLead" : true 
     }, 
     { 
      "id" : "012", 
      "firstName" : "Dre", 
      "lastName" : "Pilipczuk", 
      "role" : "Android Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "013", 
      "firstName" : "Ray", 
      "lastName" : "Britton", 
      "role" : "Android Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "014", 
      "firstName" : "Charly", 
      "lastName" : "Murillo", 
      "role" : "Android Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     } 
    ] 
}, 
{ 
    "teamName" : "Web", 
    "members" : [{ 
      "id" : "015", 
      "firstName" : "Ryan", 
      "lastName" : "French", 
      "role" : "Web Team Lead", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png", 
      "teamLead" : true 
     }, 
     { 
      "id" : "016", 
      "firstName" : "James", 
      "lastName" : "Ward", 
      "role" : "Web Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "018", 
      "firstName" : "Adam", 
      "lastName" : "Smith", 
      "role" : "Web Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "019", 
      "firstName" : "Leonard", 
      "lastName" : "Da Costa", 
      "role" : "Web Developer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     } 
    ] 
}, 
{ 
    "teamName" : "Design", 
    "members" : [{ 
      "id" : "020", 
      "firstName" : "Hannah", 
      "lastName" : "Tempest", 
      "role" : "Design Team Lead", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png", 
      "teamLead" : true 
     }, 
     { 
      "id" : "021", 
      "firstName" : "Ellis", 
      "lastName" : "Reed", 
      "role" : "Designer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "022", 
      "firstName" : "Pete", 
      "lastName" : "Horsham", 
      "role" : "Designer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "023", 
      "firstName" : "Hemel", 
      "lastName" : "Dave", 
      "role" : "Designer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     }, 
     { 
      "id" : "024", 
      "firstName" : "Hannah", 
      "lastName" : "Corke", 
      "role" : "Designer", 
      "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png" 
     } 
    ] 
} 
] 

     @Override 
     public void onResponse(JSONArray response) { 
      Log.d("Theo", response.toString()); 
      //I use i=1 to bypass the first JSON object which doesn't contain 
      the object member. 
      //If i set i=0,then I will get an exception. 
      for(int i = 1;i<response.length();i++){ 


       try { 

        //Here I read the 4 objects. 
        JSONObject jsonObject = response.getJSONObject(i); 

         //I get the members array for JSON object 
         JSONArray teamMembersArray = jsonObject.getJSONArray("members"); 

         for(int j=0;j<teamMembersArray.length();j++){ 

          //The model class which contains the setters/getters 
          //in order to "deserialize" the JSON objects into string objects. 
          Model m = new Model(); 


          JSONObject teamObject = teamMembersArray.getJSONObject(j); 
          //I am searching if the teamLead object exists.If yes 
          //then set it to true by reading it! If not then read 
          //the next members! 
          if (teamObject.has("teamLead") && teamObject.isNull("teamLead")) { 
           m.setTeamLead(teamObject.getBoolean("teamLead")); 
          }else { 

           m.setId(teamObject.getInt("id")); 
           m.setProfileImageURL(teamObject.getString("profileImageURL")); 
           m.setFirstName(teamObject.getString("firstName")); 
           m.setLastName(teamObject.getString("lastName")); 
           m.setRole(teamObject.getString("role")); 


           //Finally I am adding the string objects into an ArrayList. 
           modelArrayList.add(m); 

          } 

         } 



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

      } 


      //modelArrayList.add(m); 
      // Update list by notifying the adapter of changes 
      myAdapter.notifyDataSetChanged(); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 

      //hidePD(); 
     } 
    }); 
    AppController.getInstance().addToRequestQueue(jsObjRequest); 

}

我用我我的模型類中創建了一個setter方法讀取它。到現在爲止還挺好。 現在我想要在我的自定義適配器中進行操作,如果該json變量爲true(teamLead),則更改所有相應團隊領導的文本顏色。

這是我的適配器代碼。

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.RowHolderClass> { 

private List<Model> modelList; 
private Context mContext; 
private int focused; 
private ImageLoader mImageLoader; 

public MyAdapter(Activity activity,List<Model> modelList) { 
    this.modelList = modelList; 
    this.mContext = activity; 
} 

@Override 
public RowHolderClass onCreateViewHolder(ViewGroup parent, int viewType) { 
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_row,null); 

    final RowHolderClass holder = new RowHolderClass(v); 
    return holder; 
} 

@Override 
public void onBindViewHolder(RowHolderClass holder, int position) { 
    final Model listItems = modelList.get(position); 
    holder.itemView.setSelected(focused==position); 

    holder.getLayoutPosition(); 


    mImageLoader = AppController.getInstance().getImageLoader(); 

    holder.imageView.setImageUrl(listItems.getProfileImageURL(),mImageLoader); 

    holder.fName.setText(Html.fromHtml(listItems.getFirstName())); 
    holder.lName.setText(Html.fromHtml(listItems.getLastName())); 
    holder.jobRole.setText(Html.fromHtml(listItems.getRole())); 
    holder.teamLeader.booleanValue(); 
    //holder.fName.setTextColor(mContext.getResources().getColor(R.color.textColors)); 


    holder.relativeLayout.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      String first_name = listItems.getFirstName(); 
      String last_name = listItems.getLastName(); 
      String job_role = listItems.getRole(); 
      String image_url = listItems.getProfileImageURL(); 
      String id= String.valueOf(listItems.getId()); 


      Intent i = new Intent(mContext, NewActivity.class); 
      i.putExtra("firstName",first_name); 
      i.putExtra("lastName",last_name); 
      i.putExtra("jobRole",job_role); 
      i.putExtra("imageUrl",image_url); 
      i.putExtra("memberId",id); 
      mContext.startActivity(i); 
     } 
    }); 
} 

@Override 
public int getItemCount() { 
    return (null != modelList?modelList.size() :0); 
} 
//ViewHolder algorithm used to read the data of the row fast. 
class RowHolderClass extends RecyclerView.ViewHolder { 

    protected NetworkImageView imageView; 
    protected TextView fName, lName, jobRole; 
    protected RelativeLayout relativeLayout; 
    protected Boolean teamLeader; 

    public RowHolderClass(View itemView) { 
     super(itemView); 

     this.relativeLayout = (RelativeLayout) itemView.findViewById(R.id.recLayout); 
     this.imageView = (NetworkImageView) itemView.findViewById(R.id.imageView); 
     this.fName = (TextView) itemView.findViewById(R.id.firstName); 
     this.lName = (TextView) itemView.findViewById(R.id.lastName); 
     this.jobRole = (TextView) itemView.findViewById(R.id.roleView); 

    } 
} 
} 

正如你所看到的,我得到了我想要的所有值,並讓它們顯示出來。但我不知道怎麼說

if(teamLeader is true){ 
    //then change the text colours of the corresponding team leaders. 
} 

感謝,

西奧

回答

2

沒有必要做起來很複雜。 Json還爲我們提供了一種簡單的方法來實現它的選項.i.e.,opt(optString(),optBoolean(),optJsonArray())而不是get(getString(),getBoolean(),getJsonArray())。這個選項的作用是,它會檢查給定的鍵是否存在於你的json字符串中。如果json字符串具有該鍵,則它將返回該值,否則默認情況下它將爲null(或)false,否則不會發生Json異常。這會減少不必要的條件。在你的情況下,你檢查了「teamLead」布爾對象是否存在,這可以很容易地實現,如下所示。

m.setTeamLead(teamObject.optBoolean("teamLead", false)); 

如果要使用if條件檢查布爾值,可以按照以下方法進行。

if (m.getTeamLead()) { 
//True 
} else { 
//False 
} 

希望這會有所幫助。

+0

感謝您的回答。但有些奇怪的事情發生。當我第一次啓動應用程序時,只有團隊成員突出顯示這是我想要的:)。但是當我向下滾動回收站視圖時,也會突出顯示一些非主角成員。這是我改變顏色的方式。 if(listItems.getTeamLead())holder.fName.setTextColor(mContext.getResources()。getColor(R.color.textColors)); holder.lName.setTextColor(mContext.getResources()。getColor(R.color.textColors)); holder.jobRole.setTextColor(mContext.getResources()。getColor(R.color.textColors)); } – Theo

+0

有什麼問題,但我沒有看到它。 – Theo

+0

@Theo:您必須編寫其他條件,其中您將文本顏色更改爲默認值。我相信現在你的問題將得到解決。 – Jeevanandhan

1

試試這個

if(modelList.getTeamLead()) 
{ 
    // Change color 
} 
else 
{ 
    // Do not change 
} 

在API調用的其他的部分添加此。

m.setTeamLead(false); 
+0

感謝您的回覆。我得到一個JSON異常雖然:(java.lang.NullPointerException:試圖調用空對象引用虛擬方法'布爾java.lang.Boolean.booleanValue()' – Theo

+0

這意味着該布爾變量未初始化。 – Theo

+0

@Theo可能會嘗試調試它 – Nisarg

1

使用..

if(listItems.getTeamLead()) 
    { 
     //then change the text colours of the corresponding team leaders. 
    } 

if(listItems.getTeamLead()==true) 
{ 
    //then change the text colours of the corresponding team leaders. 
} 

,把默認值,並將其添加到modelArrayList.add(米); 出塊

if (teamObject.has("teamLead") && (!teamObject.isNull("teamLead"))) { 
          m.setTeamLead(teamObject.getBoolean("teamLead")); 
         }else { 
         m.setTeamLead(false); 
        //DEFAULTVALUE 
         }  
          m.setId(teamObject.getInt("id")); 
          m.setProfileImageURL(teamObject.getString("profileImageURL")); 
          m.setFirstName(teamObject.getString("firstName")); 
          m.setLastName(teamObject.getString("lastName")); 
          m.setRole(teamObject.getString("role")); 

          //Finally I am adding the string objects into an ArrayList. 


     modelArrayList.add(m); 

現在,應該可以解決的......

的適配器

if(listItems.getTeamLead()){ 
//color 
}else{ 
//default setcolor 

}

+0

不。空指針異常:( – Theo

+0

使用「listItems」而不是modelList – Kush

+0

這裏是「if(teamObject.has(」teamLead「)&& teamObject.isNull(」teamLead「))m.setTeamLead(teamObject.getBoolean(」teamLead「 )); }「所以你應該從響應中得到空值,請檢查.. – Kush