addOnScrollListener,传递基数和限制

时间:2016-07-06 12:02:44

标签: android onscrolllistener

我正在学习如何使用onscrolllistner

RecyclerOkHttpHandler类将从服务器执行基数为0且限制为5的select。我想要的是再次执行RecyclerOkHttpHandler以获取新数据,对于基础5的限制10.但在onscrolllistner上添加以下内容

       handler.execute().get();

我收到了这个错误:

Cannot execute task: the task has already been executed (a task can be executed only once)

好吧,我明白我不能再执行任务了,但我应该如何过去和限制?

这(它正在工作)将执行一个将从服务器获取图像的类,但是我需要传递基数0和限制5

   final RecyclerOkHttpHandler handler = new RecyclerOkHttpHandler( this, new RecyclerOkHttpHandler.MyInterface() {
        @Override
        public void myMethod(ArrayList result) {
            mAdapter_first = new MyAdapter(result,SearchActivity.this);
            mAdapter_first.notifyDataSetChanged();
            mRecyclerView_first.setAdapter(mAdapter_first);
        }
    },"girls",base,limit);

    try {
         handler.execute().get();

    } catch (Exception e) {
       Log.d("SearchActivity error", "error in mRecyclerView_first");

        e.printStackTrace();
    }

这是addOnScrollListener,

 mRecyclerView_first.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            visibleItemCount = mRecyclerView_first.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                    System.out.println("previousTotal:" + previousTotal);
                    System.out.println("totalItemCount:" + totalItemCount);
                    System.out.println("visibleItemCount:" + visibleItemCount);

                }
            }
            if (!loading && (totalItemCount - visibleItemCount)
                    <= (firstVisibleItem + visibleThreshold)) {
                // End has been reached
                System.out.println(totalItemCount);

                Log.i("Yaeye!", "end called");
         //       base =String.valueOf(firstVisibleItem);
       //         limit=String.valueOf(visibleItemCount);

                // Do something
                try {
                    handler.execute().get();

                } catch (Exception e) {
                    Log.d("SearchActivity error", "error in mRecyclerView_first");

                    e.printStackTrace();
                }
                loading = true;
            }
        }
    });

这是RecyclerOkHttpHandler类

public class RecyclerOkHttpHandler extends AsyncTask<String, Void, String> {
    private Context mContext;
    private MyInterface mListener;
    public String category;
    public String basestart;
    public String limitend;
    public RecyclerOkHttpHandler(Context context, MyInterface mListener, String categ, String base, String limit){
        mContext = context;
        this.mListener  = mListener;
        category=categ;
        basestart=base;
        limitend=limit;
    }
    public interface MyInterface {
        public void myMethod(ArrayList result);
    }

    private final String Fetch_URL = "http://justedhak.com/old-files/Recyclerview_data.php";
    // ArrayList<Listitem> Listitem;
    ArrayList<CategoryList> Listitem;
    int resulta;

    OkHttpClient httpClient = new OkHttpClient();
    ListView list;
    String myJSON;
    JSONArray peoples = null;
    InputStream inputStream = null;

    @Override
    protected String doInBackground(String... params) {
        Log.d("okhttp Fetch_URL", Fetch_URL);



        RequestBody formBody = new FormEncodingBuilder()
                .add("category", category)
                .add("base", basestart)
                .add("limit", limitend)
                .build();
        Request request = new Request.Builder()
                .url(Fetch_URL)
                .post(formBody)
                .build();


        String result = null;
        try {
            Response response = httpClient.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            inputStream = response.body().byteStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            result = sb.toString();
            resulta = 1; //"Success
            //  return response.body().bytes();
        } catch (Exception e) {
            Toast.makeText(mContext, "Connection failed, check your connection",
                    Toast.LENGTH_LONG).show();
            e.printStackTrace();        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }
        return result;
    }
    @Override
    protected void onPostExecute(String result){
        if( resulta ==1){
            myJSON=result;
            Log.e("result",result);

            showList();
        }
        else{
            Log.e("d","there is an error on postexecute in okhhttphandler.java");

        }
    }

    protected void showList(){
        try {

            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray("result");
            System.out.println("Length:"+peoples.length());
            int J_length=peoples.length()-1;
            //JSONObject maxj  = peoples.getJSONObject(peoples.length() - 1);
            // max of arrray

            jsonObj= peoples.getJSONObject(J_length);

            String j_id=  jsonObj.getString("id");
            int _id = Integer.parseInt(j_id);
            System.out.println(j_id);

            //max of
            DatabaseHandler db = new DatabaseHandler(mContext);
            String db_id="";
            db_id = db.getmax();
            if (db_id== null)
            {
                db_id="0";
            }
            int d_id = Integer.parseInt(db_id);
            Log.e("db_id", db_id);
            Log.e("j_id",j_id);

            //  if (_id < d_id) {
            System.out.println("Getting json result ");

            Listitem = new ArrayList<CategoryList>();
            for (int i = 0; i < peoples.length(); i++) {
                JSONObject c = peoples.getJSONObject(i);

                String id = c.getString("id");
                String url = c.getString("url");



                Listitem.add(new CategoryList(id, url));
            }

            if (mListener != null)
                mListener.myMethod(Listitem);


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





}

1 个答案:

答案 0 :(得分:0)

我再次阅读了您的问题,解决方案可能只是每次都创建一个新的RecyclerOkHttpHandler。这就是错误消息所说的内容以及AsyncTasks的工作方式。如果在无法再次调用它时调用.execute(),则必须创建一个新对象。

仍然应该覆盖onPostExecute(),否则你阻止了UI线程。看看AsyncTask。 我需要RecyclerOkHttpHandler的代码来说更多......