Tuesday, April 12, 2016

How can I choose to update a particular view with a JSON request

Leave a Comment
    public class AdapterQuestion extends RecyclerView.Adapter<AdapterQuestion.ViewQuestion>{     private LayoutInflater mLayoutInflater;     private ArrayList<QuestionData> mListblogs =new ArrayList<>();     public AdapterQuestion(Context context){          mLayoutInflater=LayoutInflater.from(context);      }     public void setBloglist(ArrayList<QuestionData> listBlogs){         this.mListblogs =listBlogs;         notifyItemRangeChanged(0, listBlogs.size());     }      @Override     public ViewQuestion onCreateViewHolder(ViewGroup parent, int viewType) {         View view= mLayoutInflater.inflate(R.layout.customquestion, null);         ViewQuestion holder=new ViewQuestion(view);         return holder;     }      @Override     public void onBindViewHolder(ViewQuestion holder, int position) {         QuestionData currentBlog= mListblogs.get(position);         holder.answerText.setText(currentBlog.getMtext());         holder.answerId.setText(currentBlog.getId());         holder.mVotes.setText(currentBlog.getVotes());     }      @Override     public int getItemCount() {         return mListblogs.size();     }      public static class ViewQuestion extends RecyclerView.ViewHolder{         private TextView answerText;         private TextView answerId;         private TextView mVotes;         private LikeButton mLikeButton;          public ViewQuestion (View view){             super(view);             answerText=(TextView)itemView.findViewById(R.id.answerText);             answerId=(TextView)itemView.findViewById(R.id.answerId);             mVotes=(TextView)itemView.findViewById(R.id.VoteTextView);             mLikeButton=(LikeButton)itemView.findViewById(R.id.heart_buttons);              mLikeButton.setOnLikeListener(new OnLikeListener() {                 @Override                 public void liked(LikeButton likeButton) {                     Voting vote = new Voting();                     vote.onUpVote(convertToString(),mVotes);                 }                 @Override                 public void unLiked(LikeButton likeButton) {                     Voting onDown=new Voting();                     onDown.onDownVote(convertToString());                 }             });          }         public String getVoteView(){             String voteView=mVotes.getText().toString();             return voteView;         }         public String convertToString(){             String converted=answerId.getText().toString();             return converted;         }     } }      public class Voting {      public void onUpVote(String Id,final TextView VoteView) {         final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();         final String PUT_VOTE_UP = "url";         StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {             @Override             public void onResponse(String response) {                 VoteView.setText("likes");             }         }, new Response.ErrorListener() {             @Override             public void onErrorResponse(VolleyError error) {              }         });         mrequestQueue.add(PostVoteUp);         System.out.println("VOTED UP");     }     public void onDownVote( String Id) {         final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();         final String PUT_VOTE_DOWN = "url";         StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, new Response.Listener<String>() {             @Override             public void onResponse(String response) {              }          }, new Response.ErrorListener() {             @Override             public void onErrorResponse(VolleyError error) {                 error.printStackTrace();                 System.out.println("************Answer" + error + "error");             }         });         mrequestQueue.add(PostVoteUp);         System.out.println("VOTED DOWN");     }  } 

I have Two classes, an adapter class for my fragment activity and a voting class. I am calling the voting class in my adapter class when a user presses a button, However, I also have a JSON request and a parse method in my fragment activity as shown below and I would like to only update the "votes" when the button is pressed How can I do this?

private ArrayList<QuestionData> parseJSONResponseQuestion(JSONArray response) {     if (!response.equals("")) {         ArrayList<QuestionData> questionDataArrayList = new ArrayList<>();         try {             StringBuilder data = new StringBuilder();             for (int i = 0; i < response.length(); i++) {                 JSONObject currentQuestions = response.getJSONObject(i);                 String text = currentQuestions.getString("text");                 String votes = currentQuestions.getString("votes");                 int voteInt=Integer.parseInt(votes);                 QuestionData questionData = new QuestionData();                 questionData.setMtext(text);                 questionData.setVotes(votes);             }             System.out.println(data.toString());         } catch (JSONException e) {             e.printStackTrace();         }     }      return mListblogs; } 

3 Answers

Answers 1

First you should add a method into your adapter for updating single QuestionData. For example:

public void setBlogItem(int index, QuestionData questionData) {     if (mListblogs.get(index).getVotes() != questionData.getVotes()) {         mListblogs.set(index, questionData);         notifyItemChanged(index);     } } 

Second. Update question. For doing this you have to know index of the item. I suggest that the whole list doesn't change. So, modify your json parser:

private ArrayList<QuestionData> parseJSONResponseQuestion(JSONArray response) {     if (!response.equals("")) {         ArrayList<QuestionData> questionDataArrayList = new ArrayList<>();         try {             StringBuilder data = new StringBuilder();             for (int i = 0; i < response.length(); i++) {                 JSONObject currentQuestions = response.getJSONObject(i);                 String text = currentQuestions.getString("text");                 String votes = currentQuestions.getString("votes");                 int voteInt=Integer.parseInt(votes);                 QuestionData questionData = new QuestionData();                 questionData.setMtext(text);                 questionData.setVotes(votes);                 recyclerAdapter.setBlogItem(i, questionData); /// Put attention here!             }             System.out.println(data.toString());         } catch (JSONException e) {             e.printStackTrace();         }     }      return mListblogs; } 

Answers 2

I'm assuming you're using a LinearLayoutManager for your RecyclerView.

Pass the clicked position from your ViewQuestion's onClick() to your onUpVote() and onDownVote() methods.

From the onUpVote() and onDownVote() methods, post a Broadcast specifying whatever data in your intent.putExtras and also include the clicked position.

Now on your Activity, write a BroadcastReceiver which captures the broadcasts sent from the onUpVote() or onDownVote() methods. Now from the Activity, call your LinearLayoutManager.findViewByPosition(position) method to get a reference to your View which was clicked. Now you can use findViewById() method to find your required view and update the values.

Answers 3

Sounds like your application needs a bit of architecture work. Have you considered restricting your use of JSON to only when you need to read or write the data to a file or network or something similar. If your mixing JSON up in your model then you might be writing much more code than you need.

Just a thought ...

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment