我想在Android的recyclerview中显示来自Json的数据

时间:2017-03-08 09:17:10

标签: android json

我希望在另一项活动中显示评论文字及其评分。

这是我的AddReview类

public class AddReview extends AppCompatActivity implements ServerRequests.AddReviewreponse {
    private Button submit;
    EditText addReview;
    RatingBar ratingBar;
    Toolbar toolbar;

    ServerRequests serverRequests;
    JSONParser jsonParser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_review);

        jsonParser = new JSONParser();
        serverRequests = new ServerRequests(getApplicationContext());
        serverRequests.setAddReviewreponse(this);


        addReview=(EditText)findViewById(R.id.reviewBox);
        ratingBar=(RatingBar) findViewById(R.id.ratingBar);

        submit=(Button)findViewById(R.id.submit);
        toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top);

        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Add Review");


       // toolbar.setNavigationIcon(R.drawable.back_30);

      /*  toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });*/



       submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {

                    String ReviewTxt = addReview.getText().toString();
                    float rating = ratingBar.getRating();

                    JSONObject obj = jsonParser.makeAddReviewJson(1,1,ReviewTxt,rating);
                    Log.e("final Json", obj.toString());
                    serverRequests.addReview(obj);

                } catch (Exception e) {

                }


               /* Reviews.displayName.setText(RegisterActivity.name.getText().toString());

                Reviews.displayReview.setText("Your Review : "+addReview.getText().toString());

                Reviews.displayStars.setRating(ratingBar.getRating());*/

               /* Reviews.displayStars.setText("Your Rating : " + ratingBar.getRating());
                String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
                Reviews.displayDate.setText(currentDateTimeString);*/


                AlertDialog alertDialog = new AlertDialog.Builder(AddReview.this).create();

                alertDialog.setTitle("Review Submitted!");

                alertDialog.setMessage("Thanks for your valueable review!");

                alertDialog.setIcon(R.drawable.star_48);

                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Write your code here to execute after dialog closed
                        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
                    //    startActivity(new Intent(getApplicationContext(), Reviews.class));
                    }
                });

                // Showing Alert Message
                alertDialog.show();

            }
        });
    }

    @Override
    public void onAddReviewReposne(JSONObject object) {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home)
        {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}

这是Review类,我想在其中显示评论及其评分

public class Reviews extends AppCompatActivity implements ServerRequests.GetReviewResponse {

    public static TextView displayReview, displayDate, displayName;
    public static RatingBar displayStars;
    Button addReviewBtn;
    android.support.v7.widget.Toolbar toolbar;

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static String LOG_TAG = "CardViewActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reviews);

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view1);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
    //    mAdapter = new ReviewAdapter(getDataSet(jsonObject));
        mRecyclerView.setAdapter(mAdapter);


        toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top1);

        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Reviews");


        /*displayReview = (TextView) findViewById(R.id.review);
        displayStars = (RatingBar) findViewById(R.id.rating);
        displayDate = (TextView)findViewById(R.id.displayDate);
        displayName = (TextView)findViewById(R.id.displayName);*/

       addReviewBtn = (Button)findViewById(R.id.addReviewBtn);
        addReviewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), AddReview.class));
            }
        });

        ServerRequests serverRequests=new ServerRequests(getApplicationContext());
        serverRequests.setReviewResponse(this);
        serverRequests.getReviews("one");

    }


    private ArrayList<Review> getDataSet(JSONArray array) {
        ArrayList results = new ArrayList<Review>();
        for (int i = 0; i < array.length(); i++) {
            try {
                JSONObject object = array.getJSONObject(i);
                Review obj = new Review(object.getInt("reviewId"),object.getInt("userId"),object.getString("Name"),object.getString("Review"),object.getLong("rating"));
                results.add(i,obj);

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

        }
        return results;
    }


    @Override
    public void onGetReviewResponse(JSONArray jsonObject) {

        mAdapter = new ReviewAdapter(getDataSet(jsonObject));
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home)
        {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}

这是ReviewAdapter

public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<Review> mDataset;
    private static MyClickListener myClickListener;

    public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public static TextView name,review;
        public static RatingBar rating;

        public DataObjectHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            review = (TextView) itemView.findViewById(R.id.review);
            rating = (RatingBar) itemView.findViewById(R.id.rating);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(), v);
        }
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public ReviewAdapter(ArrayList<Review> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_review, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.name.setText(mDataset.get(position).getName());
        holder.review.setText(mDataset.get(position).getReview());
        holder.rating.setRating(mDataset.get(position).getRating());
    }

    public void addItem(Review dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }
}

这是Pojo的评论课

public class Review {
    private String name,review;
    private float rating;
    private int reviewId,userId;

    public Review (int ReviewId, int UserId, String Name, String Review, float Rating){
        reviewId = ReviewId;
        userId = UserId;
        name = Name;
        review = Review;
        rating = Rating;

    }

    public int getReviewId() {
        return reviewId;
    }

    public void setReviewId(int reviewId) {
        this.reviewId = reviewId;
    }


    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getReview() {
        return review;
    }

    public void setReview(String review) {
        this.review = review;
    }

    public float getRating() {
        return rating;
    }

    public void setRating(float rating) {
        this.rating = rating;
    }


}

这是用于添加和获取审核的ServerRequests

 //------------For add review------------------------------

    public void setAddReviewreponse(AddReviewreponse addreviewreponse) {
        this.addreviewreponse = addreviewreponse;
    }

    private AddReviewreponse addreviewreponse;

    public interface AddReviewreponse {
        void onAddReviewReposne(JSONObject object);
    }

    public void addReview(JSONObject jsonObject) {


        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.ADD_REVIEW, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.e("Json response", "" + response);
                            boolean b = response.getBoolean("success");

                            if (addreviewreponse != null) {
                                addreviewreponse.onAddReviewReposne(response);

                            }

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

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error ", "" + error);
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }

    //------------For get review------------------------------

    public void setReviewResponse(GetReviewResponse reviewResponse) {
        this.getReviewResponse = reviewResponse;
    }

    public GetReviewResponse getReviewResponse;

    public interface GetReviewResponse {
        void onGetReviewResponse(JSONArray jsonObject);
    }

    public void getReviews(final String id) {

        StringRequest request = new StringRequest(Request.Method.GET, Services.GET_REVIEW,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray(response);
                            Log.e("Server response", response);
                            if (array.length() > 0) {
                                if (getReviewResponse != null) {
                                    getReviewResponse.onGetReviewResponse(array);
                                }

                            } else {
                                Log.e("Error is occured", "asd");

                            }


                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //send error repsonse back to user
                Log.e("Error: ", error.getMessage());

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> params = new HashMap<>();
                params.put("courseId", id);
                return params;

            }
        };
        queue.add(request);
    }

这是AddReview的JSONParser类

 //--------For Add review---------------------------------

    public JSONObject makeAddReviewJson(int studentID, int courseID, String reviewTxt, float rating) throws JSONException {

        JSONObject object = new JSONObject();

        object.put("studentId", studentID);
        object.put("courseId", courseID);
        object.put("review", reviewTxt);
        object.put("ratings", rating);
        return object;
    }

这是我在发布评论后得到的JSON响应

E/final Json: {"studentId":1,"courseId":1,"review":"Hellooooo","ratings":3}
E/Json response: {"success":true,"msg":"Your review has been added successfully","data":{"reviewsId":18}}

1 个答案:

答案 0 :(得分:1)

private ArrayList<Review> getDataSet(JSONArray array) {
        ArrayList results = new ArrayList<Review>();
        for (int i = 0; i < array.length(); i++) {
            try {
                JSONObject object = array.getJSONObject(i);
                Review obj = new Review(object.getInt("studentId"),object.getInt("courseId"),object.getString("Review"),object.getLong("rating"));
                results.add(i,obj);

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

        }
        return results;
    }

尝试使用上面的代码更改你的getDataSet函数,如果在某些行中遇到任何问题,请检查调试点。随时可以进一步询问是否会对您有所帮助

编辑:

您还需要更改您的Pojo类评论。因为在JSON响应中,您没有获得userId和reviewId。希望你理解