post params如何截击请求并获取Json数组的列表?

时间:2016-06-02 07:18:59

标签: php android json android-volley

在我的Android应用程序中,我使用volley库从我的服务器获取提要列表,并在应用程序的列表视图中显示它们。 现在我想将一个参数发布到volley请求方法,以便从服务器获得前10个帖子,当用户向下滚动时发送新参数以从服务器获得第二个10个帖子。

我不知道post paramas如何截击请求以解决问题我使用sendpage()方法在服务器中保存请求的页面并从中读取用户想要的页面。实际上它有效,但我知道这不是真正的实施。

所以我的问题是如何将此参数(只是一个数字)发送给服务器以获取数据?

这是我的排球要求:

 public void requestData(String uri) {


        swipeRefreshLayout.setRefreshing(true);
        StringRequest request = new StringRequest(uri,

                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        //Changed your code here
                        postList = PostJSONParser.parseFeed(response);
                        updateDisplay();

                        offlineList = PostJSONParser.parseFeed(response);
                        for (Post post : offlineList){
                            dataSource.create(post);
                        }
                        adapter.notifyDataSetChanged();
                        swipeRefreshLayout.setRefreshing(false);
                    }

                },

                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError ex) {
                        Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();

                        swipeRefreshLayout.setRefreshing(false);
                    }
                });

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    } 

这是我的updateDisplay()方法:

 protected void updateDisplay() {
         adapter = new MyCustommAdapter(MainActivity.this, R.layout.list_item, postList);


        int index = myList.getFirstVisiblePosition();
        View v = myList.getChildAt(0);
        int top = (v == null) ? 0 : v.getTop();

        myList.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        myList.setSelectionFromTop(index, top);


    }

这适用于滚动更改:

 public class EndlessScrollListener implements AbsListView.OnScrollListener {

        private int visibleThreshold = 5;


        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {


            // private int currentPage = 0;


            if (scrollState == SCROLL_STATE_IDLE) {
                if (myList.getLastVisiblePosition() >= myList.getCount() - visibleThreshold) {
                    cpage++;
                    new sendpage(cpage).execute();
                    if (isOnline()) {
                        requestData2("http://192.168.1.3/android_login_api/include/get_post.php");
                    } else {
                        Toast.makeText(MainActivity.this, "Network isn't available", Toast.LENGTH_LONG).show();
                    }
                    updateDisplay();
                   // adapter.notifyDataSetChanged();




                }
            }
        }
    }

这是我的get_post.php文件:

<?php
    //Create Database connection
    error_reporting(E_ALL ^ E_DEPRECATED);
    include 'conf.php';


    $page = "select page from page";
    $resultpage= mysql_query($page);
    while ($row = mysql_fetch_assoc($resultpage)) {
    $pagei = $row['page'];
}

    $sql="select * from new_post order by ID DESC limit ".getpage($pagei);
    $result= mysql_query($sql);


    function getpage($p){
    $p--;
    return ($p*10).",10";
    }

    //Create an array
    $json_response = array();

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $row_array['id'] = $row['id'];

        $row_array['title'] = $row['title'];


         $fg = strip_tags($row['content']);
          $gt= str_replace("","",$fg);
          $ff = iconv(mb_detect_encoding($gt, mb_detect_order(), true), "UTF-8", $gt);
           $string = htmlentities($ff, null, 'utf-8');
            $string = str_replace("&nbsp;", "", $string);
            $content = html_entity_decode($string);

        $row_array['content'] = $content;
        $row_array['created_at'] = $row['created_at'];
        $row_array['url_image'] = $row['url_image'];


        //push the values in the array
        array_push($json_response,$row_array);
    }
    array_walk_recursive($json_response, function(&$val) {
    $val = utf8_encode($val);
});
    echo json_encode($json_response, JSON_UNESCAPED_SLASHES);

 print "ok";

?>

2 个答案:

答案 0 :(得分:0)

扩展StringRequest:

class VolleyStringRequest extends StringRequest
    {
        private Map<String, String> mParams;
        public VolleyStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener, Map<String, String> requestParams) {
            super(method, url, listener, errorListener);
            mParams = requestParams;
            Log.e("Request",url);
        }

        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
                try {
                    Log.e("errorResponse", new String( volleyError.networkResponse.data, "utf-8" ));
                }catch(Exception e){

                }

        }
        return super.parseNetworkError(volleyError);
    }

    @Override
    public RetryPolicy getRetryPolicy() {
        DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(
                TIMEOUT_IN_MILLISECONDS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        return retryPolicy;
    }

    @Override
    public Map getHeaders() throws AuthFailureError {
        Map headers = new HashMap();
        headers.put("Accept-Charset","utf-8");
        return headers;
    }

    @Override
    public Map<String, String> getParams() {
        return mParams;
    }

}

和用法:

  HashMap<String, String> paramMap = new HashMap<String, String>();
  paramMap.put("parameter1", "value1");
  paramMap.put("parameter2", "value2");

  VolleyStringRequest request = new VolleyStringRequest(Request.Method.POST, url, responseHandler, errorHandler, paramMap);

答案 1 :(得分:0)

requestData2("http://192.168.1.3/android_login_api/include/get_post.php");更改为此 - &gt;

requestData2("http://192.168.1.3/android_login_api/include/get_post.php?page_number="+cpage);

并从您的服务器端执行此操作 - &gt;  1.像这样接收分页号码 - &gt;

$pageNumber = $_GET['page_number'];
  1. 以这种方式更改查询 - &gt;

    $ sql =“按ID DESC限制从new_post顺序中选择*。”($ pageNumber * $ pagei)。“,”。getpage($ pagei);

  2. 它会像分页一样起作用。