搜索活动中带有ProgressBar的无尽RecyclerView

时间:2017-06-15 13:42:26

标签: java android listview android-recyclerview

我是android新手。我有一个搜索活动,使用异步任务搜索查询,我想在用户到达底部时实现无限/无限滚动。我想在异步任务中添加一个参数startrow,然后将其传递给服务器,告诉哪一行开始。

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
private  LinearLayoutManager mLayoutManager;
private String searchQuery;


SearchView searchView = null;

private String query;

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

每次按键盘上的搜索按钮时,都会重新创建一个活动,然后调用此功能

    @Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
          query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

类AsyncFetch将从服务器获取数据

private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // URL address wherephp file resides
            url = new URL("http://someurl/json/search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    try {
                        fishData.fileName = URLDecoder.decode(json_data.getString("file"), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    fishData.linkName = json_data.getString("link");
                    fishData.reg_date = json_data.getString("reg_date");
                    fishData.fileSize = json_data.getString("filesize");
                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(MainActivity.this, data);
               // mRVFish.setLayoutManager(new LinearLayoutManager(MainActivity.this));


                mLayoutManager = new LinearLayoutManager(MainActivity.this);
                mRVFish.setLayoutManager(mLayoutManager);
                mRVFish.setAdapter(mAdapter);


            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}

1 个答案:

答案 0 :(得分:0)

从链接添加EndlessScrollListener到recyclerView:

https://gist.github.com/zfdang/38ae655a4fc401c99789#file-endlessrecycleronscrolllistener-java

覆盖onLoadMore方法并调用您的AsyncFetch任务。