如何将参数作为UserId传递并在android中获取json响应值?

时间:2017-07-17 12:20:33

标签: android json listview

我刚开始解析android中的JSON数据,我是这类问题的新手,这是我的代码。一切正常,但值没有显示在listView中。当我点击按钮时,它显示空白吐司,但JSON的值显示在logcat中。请任何人帮助在ListView中获取这些。

先谢谢。

JSON数据

Parameter
    {
    "UserId":"66"
    }
Response
    {
        "success": "1",
        "Review": [
            {
                "UserImages": "http:/example.org/upload/",
                "UserName": "jaspreet",
                "StoreReview": "5",
                "StoreReviewTitle": "kjhjk",
                "StoreReviewDescription": "hjkhk",
                "ReviewLike": 1,
                "TotalComments": 1,
                "ReviewTime": "2017-07-07 09:02:52",
                "Comments": [
                    [
                        {
                            "CommentId": "6",
                            "CommentUserPicture": "http://example.org/upload/",
                            "CommentUserName": "bvnb",
                            "Comment": "Avg",
                            "CommentTime": "2017-05-26 10:57:25"
                        }
                    ]
                ]
            }
        ]
    }

MainActivity.java

 public class MainActivity extends AppCompatActivity implements 
    View.OnClickListener {

    Button btn_submit;
    InternetConnectivity internetConnectivity;

    private static final String URLS ="http://xyz/webservice/xyz.php";

    ListView lvMovies;

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

        lvMovies = (ListView) findViewById(R.id.lvMovies);

        btn_submit = (Button) findViewById(R.id.btn_submit);

        assert btn_submit != null;
        btn_submit.setOnClickListener(this);

        internetConnectivity = new InternetConnectivity(MainActivity.this);
    }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_submit) {
                if (internetConnectivity.isInternetOn()) {
                       new AsyncTaskRunner().execute();
                    }

                }
            }

    public String connection(String action) {
        String result="";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(URLS);// replace with your url
        httpPost.addHeader("Content-type",
                "application/x-www-form-urlencoded");


        List<NameValuePair> nameValuePairList = new ArrayList<>();

        nameValuePairList.add(new BasicNameValuePair(
                "action", action));

        nameValuePairList.add(new BasicNameValuePair(
                "StoreId", "66"));


        try {
            UrlEncodedFormEntity urlEncodedFormEntity = new 
    UrlEncodedFormEntity(
                    nameValuePairList);
            Log.e("nameValuePairList", " " + nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);

            try {
                HttpResponse httpResponse = httpClient
                        .execute(httpPost);
                InputStream inputStream = httpResponse.getEntity()
                        .getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream);
                BufferedReader bufferedReader = new BufferedReader(
                        inputStreamReader);
                StringBuilder stringBuilder = new StringBuilder();
                String bufferedStrChunk = null;
                while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                    stringBuilder.append(bufferedStrChunk);
                }
                Log.e("result", stringBuilder.toString());
                result=stringBuilder.toString();
                return stringBuilder.toString();

            } catch (ClientProtocolException cpe) {
                System.out
                        .println("First Exception coz of HttpResponese :"
                                + cpe);
                cpe.printStackTrace();
            } catch (IOException ioe) {
                System.out
                        .println("Second Exception coz of HttpResponse :"
                                + ioe);
                ioe.printStackTrace();
            }

        } catch (UnsupportedEncodingException uee) {
            System.out
                    .println("An Exception given because of UrlEncodedFormEntity 
    argument :"
                            + uee);
            uee.printStackTrace();
        }
        return result;
    }

    private class AsyncTaskRunner extends AsyncTask<String, String, 
    List<ReviewModel>> {
        ProgressDialog mProgressBar;
        int success;
        String msg;

        @Override
        protected List<ReviewModel> doInBackground(String... params) {
            String result=connection("MainActivity");

            List<ReviewModel> reviewModelList = new ArrayList<>();
            try {
                JSONObject jsonObject = new JSONObject(result);
                success    = jsonObject.getInt("success");
                msg   =jsonObject.getString("message");


                JSONArray parentArray = jsonObject.getJSONArray("Review");

                for(int i = 0; i<parentArray.length();i++){

                    JSONObject finalObject = parentArray.getJSONObject(i);

                    ReviewModel reviewModel = new ReviewModel();


    reviewModel.setUserImages(finalObject.optString("UserImages"));
                    reviewModel.setUserName(finalObject.optString("UserName"));
                    reviewModel.setStoreReview((float) 
    finalObject.optDouble("StoreReview"));

    reviewModel.setStoreReviewTitle(finalObject.optString("StoreReviewTitle"));

    reviewModel.setStoreReviewDescription(finalObject.optString(
    "StoreReviewDescription"));
                    reviewModel.setReviewLike(finalObject.optInt("ReviewLike"));

    reviewModel.setTotalComments(finalObject.getInt("TotalComments"));

    reviewModel.setReviewTime(finalObject.optString("ReviewTime"));

    reviewModel.setUserImages(finalObject.optString("Comments"));

                    reviewModelList.add(reviewModel);
                }

                return reviewModelList;

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

        }

        /*
         * (non-Javadoc)
         *
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(List<ReviewModel> result) {

            super.onPostExecute(result);
            // execution of result of Long time consuming operation
            mProgressBar.dismiss();
            //   Toast.makeText(SignUpActivity.this,resp,Toast.LENGTH_SHORT).show();
            if(success == 0){
                Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
            }
            else if(success == 1){
                Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();

            }
            else if(success == 2){
                Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
            }
            ReviewAdapter reviewAdapter = new ReviewAdapter(getApplicationContext(),R.layout.row,result);
            lvMovies.setAdapter(reviewAdapter);
        }

        /*
         * (non-Javadoc)
         *
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            mProgressBar = new ProgressDialog(MainActivity.this);
            mProgressBar.setMessage("Connecting to server");

            mProgressBar.setCancelable(false);
            mProgressBar.show();
        }
    }

    public class ReviewAdapter extends ArrayAdapter{

        private List<ReviewModel> reviewModelList;
        private int resource;
        private LayoutInflater inflater;

        public ReviewAdapter(Context context, int resource, List<ReviewModel> objects) {
            super(context, resource, objects);

            reviewModelList = objects;
            this.resource = resource;
            inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if(convertView == null){
                convertView = inflater.inflate(resource,null);
            }

            ImageView userImages;
            TextView userName;
            RatingBar storeReview;
            TextView storeReviewdescription;
            TextView reviewLike;
            TextView storeReviewtitle;
            TextView totalComments;
            TextView riviewtime;
            TextView comments;

            userImages = (ImageView) convertView.findViewById(R.id.user_images);
            userName = (TextView) convertView.findViewById(R.id.user_name);
            storeReview = (RatingBar) convertView.findViewById(R.id.store_review);
            storeReviewtitle = (TextView) convertView.findViewById(R.id.store_review_title);
            storeReviewdescription = (TextView) convertView.findViewById(R.id.sotre_review_description);
            reviewLike = (TextView) convertView.findViewById(R.id.review_like);
            totalComments = (TextView) convertView.findViewById(R.id.total_comments);
            riviewtime = (TextView) convertView.findViewById(R.id.review_time);
            comments = (TextView) convertView.findViewById(R.id.comments);

            userName.setText(reviewModelList.get(position).getUserName());
            storeReviewtitle.setText(reviewModelList.get(position).getStoreReviewTitle());
            storeReviewdescription.setText(reviewModelList.get(position).getStoreReviewDescription());
            reviewLike.setText(reviewModelList.get(position).getReviewLike());
            totalComments.setText(reviewModelList.get(position).getTotalComments());
            riviewtime.setText("Year: " +reviewModelList.get(position).getReviewTime());
            comments.setText(reviewModelList.get(position).getComments());

            storeReview.setRating(reviewModelList.get(position).getStoreReview()/2);

            return convertView;
        }
    }

}

ReviewModel.java

public class ReviewModel {

    private String UserImages;
    private String UserName;
    private Float StoreReview;
    private String StoreReviewTitle;
    private String StoreReviewDescription;
    private String ReviewTime;
    private int ReviewLike;
    private int TotalComments;
    private String Comments;
    private List<Comments> commentsList;

    public String getUserImages() {
        return UserImages;
    }

    public void setUserImages(String userImages) {
        UserImages = userImages;
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public Float getStoreReview() {
        return StoreReview;
    }

    public void setStoreReview(Float storeReview) {
        StoreReview = storeReview;
    }

    public String getStoreReviewTitle() {
        return StoreReviewTitle;
    }

    public void setStoreReviewTitle(String storeReviewTitle) {
        StoreReviewTitle = storeReviewTitle;
    }

    public String getStoreReviewDescription() {
        return StoreReviewDescription;
    }

    public void setStoreReviewDescription(String storeReviewDescription) {
        StoreReviewDescription = storeReviewDescription;
    }

    public String getReviewTime() {
        return ReviewTime;
    }

    public void setReviewTime(String reviewTime) {
        ReviewTime = reviewTime;
    }

    public int getReviewLike() {
        return ReviewLike;
    }

    public void setReviewLike(int reviewLike) {
        ReviewLike = reviewLike;
    }

    public int getTotalComments() {
        return TotalComments;
    }

    public void setTotalComments(int totalComments) {
        TotalComments = totalComments;
    }

    public String getComments() {
        return Comments;
    }

    public void setComments(String comments) {
        Comments = comments;
    }

    public List<ReviewModel.Comments> getCommentsList() {
        return commentsList;
    }

    public void setCommentsList(List<ReviewModel.Comments> commentsList) {
        this.commentsList = commentsList;
    }

    public ReviewModel() {
    }

    public static class Comments{

        private String CommentUserPicture;
        private String CommentUserName;
        private String Comment;

        public String getCommentUserPicture() {
            return CommentUserPicture;
        }

        public void setCommentUserPicture(String commentUserPicture) {
            CommentUserPicture = commentUserPicture;
        }

        public String getCommentUserName() {
            return CommentUserName;
        }

        public void setCommentUserName(String commentUserName) {
            CommentUserName = commentUserName;
        }

        public String getComment() {
            return Comment;
        }

        public void setComment(String comment) {
            Comment = comment;
        }
    }

}

1 个答案:

答案 0 :(得分:0)

您的JSON响应应该是这样的,然后您可以提取。

{
    "UserId": "66",
    "success": "1",
    "Review": [{
        "UserImages": "http:/example.org/upload/",
        "UserName": "jaspreet",
        "StoreReview": "5",
        "StoreReviewTitle": "kjhjk",
        "StoreReviewDescription": "hjkhk",
        "ReviewLike": 1,
        "TotalComments": 1,
        "ReviewTime": "2017-07-07 09:02:52",
        "Comments": [
            [{
                "CommentId": "6",
                "CommentUserPicture": "http://example.org/upload/",
                "CommentUserName": "bvnb",
                "Comment": "Avg",
                "CommentTime": "2017-05-26 10:57:25"
            }]
        ]
    }]
}