2017-06-15 116 views
1

我是android新手。我有一個使用異步任務搜索查詢的搜索活動,當用戶到達底部時,我想實現無限/無限滾動。我想將一個參數startrow添加到異步任務中,然後傳遞給服務器,告訴哪一行開始。Endless RecyclerView with ProgressBar in Search activity

// 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(); 
      } 

     } 

    } 

} 
+0

我不確定這裏有個問題嗎?你能明確你所尋找的東西嗎? – Queso

+0

@Queso我想在用戶到達底部時添加無限/無限滾動,並再次與服務器聯繫以獲取數據 – Azr

回答

0

添加獲取數據EndlessScrollListener to recyclerView鏈接:

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

重寫onLoadMore方法並調用您的AsyncFetch任務。

+0

如何在異步任務中添加int當前頁面參數? – Azr

+0

@Azr如果服務器端支持分頁,您可以使用搜索查詢將其添加到構造函數中,並將其追加爲查詢參數。 –

+0

好了,現在應該如何增加下一頁'startrow'的參數? – Azr