2017-04-04 134 views
0

以下代碼用於在列表視圖的滾動中從json獲取新數據。但是在獲得新的json之後,它不會從json中添加新的json,而是採用與第一個json中相同的數據。分頁在列表中無法正常工作滾動視圖

請幫我解決這個問題。

我的活動。

 public class ProductView extends AppCompatActivity { 


ListView list_product; 

String json; 

ProgressActivity loadingview; 

int current_page = 1; 

int totalPage = 1; 

int Pagecount = 1; 

Toolbar toolbar; 

GetProductAdapter productAdapter; 
List<BeanGetProducts> beanGetProductses = new ArrayList<>(); 


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

    toolbar = (Toolbar) findViewById(R.id.back_toolbar); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    getSupportActionBar().setHomeButtonEnabled(true); 

    toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      onBackPressed(); 
     } 
    }); 

    ImageView img_home = (ImageView) findViewById(R.id.dr_image_home); 

    img_home.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(ProductView.this, AdminAccess.class); 
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intent); 
      finish(); 
     } 
    }); 
    list_product = (ListView) findViewById(R.id.list_products); 
    productAdapter = new GetProductAdapter(beanGetProductses, ProductView.this, getApplicationContext()); 

    list_product.setOnScrollListener(new AbsListView.OnScrollListener() { 
     @Override 
     public void onScrollStateChanged(AbsListView absListView, int i) { 
     } 

     @Override 
    public void onScroll(AbsListView absListView, int firstItem, int visibleItemCount, int totalItem) { 

     int total = firstItem + visibleItemCount; 

     if (Pagecount < totalPage) { 

      if (total == totalItem) { 

       Pagecount++; 
       new getProducts(Pagecount).execute(); 


       productAdapter.notifyDataSetChanged(); 
       list_product.setAdapter(productAdapter); 
      } 
     } 
    } 
}); 


    new getProducts(current_page).execute(); 
} 


public class getProducts extends AsyncTask<Void, Void, String> { 

    int pageNo; 


    public getProducts(int pageNo) { 
     this.pageNo = pageNo; 
    } 


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


      loadingview = new ProgressActivity(ProductView.this, ""); 
      loadingview.setCancelable(false); 
      loadingview.show(); 


     } catch (Exception e) { 


     } 
    } 

    @Override 
    protected String doInBackground(Void... voids) { 


     List<NameValuePair> pairs = new ArrayList<>(); 
     pairs.add(new BasicNameValuePair("", String.valueOf(pageNo))); 

     json = new ServiceHandler().makeServiceCall(GlobalLinks.mainLink + GlobalLinks.productDetails, ServiceHandler.POST, pairs); 


     Log.e("Parameters", "" + pairs); 


     return json; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 
     loadingview.dismiss(); 

     System.out.println(s); 

     try { 

      if (!Internet.isConnectingToInternet(getApplicationContext())) { 
       Internet.noInternet(getApplicationContext()); 
      } else { 

       if (s.equalsIgnoreCase(null) || s.equalsIgnoreCase("") || s.equalsIgnoreCase("null") || s.length() == 0) { 
        GlobalUse.nullJSON(getApplicationContext()); 
       } else { 

        JSONObject mainObject = new JSONObject(s); 

        boolean status = mainObject.getBoolean("status"); 
        String message = mainObject.getString("message"); 
        totalPage = mainObject.getInt("total_page"); 
        Log.e("total_page", "" + totalPage); 

        Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_LONG).show(); 

        if (status == true) { 

         JSONArray dataArray = mainObject.getJSONArray("data"); 

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


          JSONObject object = dataArray.getJSONObject(i); 
          JSONObject getProductObject = object.getJSONObject("GetProduct"); 

          BeanGetProducts getProducts = new BeanGetProducts(); 

          getProducts.setProduct_id(getProductObject.getString("product_id")); 
          getProducts.setImage(getProductObject.getString("image")); 
          getProducts.setSku(getProductObject.getString("sku")); 
          getProducts.setQuantity(getProductObject.getString("quantity")); 
          getProducts.setPrice(getProductObject.getString("price")); 
          getProducts.setStock_status_id(getProductObject.getString("stock_status_id")); 


          JSONObject product_description = object.getJSONObject("Product_Description"); 

          getProducts.setName(product_description.getString("name")); 
          getProducts.setDescription(product_description.getString("description")); 

          JSONObject SpecialPrice = object.getJSONObject("SpecialPrice"); 

          getProducts.setSpecialPrice(SpecialPrice.getString("price")); 


          beanGetProductses.add(getProducts); 
         } 


        // productAdapter = new GetProductAdapter(beanGetProductses, ProductView.this, getApplicationContext()); 
         productAdapter.notifyDataSetChanged(); 
         list_product.setAdapter(productAdapter); 


        } 


       } 


      } 


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


    } 
} 

public void onBackPressed() { 

    Intent intent = new Intent(getApplicationContext(), AdminAccess.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 
    startActivity(intent); 
    finish(); 


} 
    } 
+1

每當您進行網絡調用獲取產品時,都會創建一個新的適配器。您應該在onCreate()方法中設置適配器一次,並在列表中插入對象並通知。 –

+0

嘗試過,但它反映了同樣的問題。 @SachinSaxena –

+1

你能發佈完整的代碼嗎?你也可以使用這個無限的滾動監聽器https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews-and-RecyclerView –

回答

1

木箱命名爲EndlessScrollListener

import android.widget.AbsListView; 

public abstract class EndlessScrollListener implements AbsListView.OnScrollListener { 
    // The minimum number of items to have below your current scroll position 
    // before loading more. 
    private int visibleThreshold = 5; 
    // The current offset index of data you have loaded 
    private int currentPage = 0; 
    // The total number of items in the dataset after the last load 
    private int previousTotalItemCount = 0; 
    // True if we are still waiting for the last set of data to load. 
    private boolean loading = true; 
    // Sets the starting page index 
    private int startingPageIndex = 0; 

    public EndlessScrollListener() { 
    } 

    public EndlessScrollListener(int visibleThreshold) { 
     this.visibleThreshold = visibleThreshold; 
    } 

    public EndlessScrollListener(int visibleThreshold, int startPage) { 
     this.visibleThreshold = visibleThreshold; 
     this.startingPageIndex = startPage; 
     this.currentPage = startPage; 
    } 


    @Override 
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) 
     { 
     // If the total item count is zero and the previous isn't, assume the 
     // list is invalidated and should be reset back to initial state 
     if (totalItemCount < previousTotalItemCount) { 
      this.currentPage = this.startingPageIndex; 
      this.previousTotalItemCount = totalItemCount; 
      if (totalItemCount == 0) { this.loading = true; } 
     } 
     // If it's still loading, we check to see if the dataset count has 
     // changed, if so we conclude it has finished loading and update the current page 
     // number and total item count. 
     if (loading && (totalItemCount > previousTotalItemCount)) { 
      loading = false; 
      previousTotalItemCount = totalItemCount; 
      currentPage++; 
     } 

     // If it isn't currently loading, we check to see if we have breached 
     // the visibleThreshold and need to reload more data. 
     // If we do need to reload some more data, we execute onLoadMore to fetch the data. 
     if (!loading && (firstVisibleItem + visibleItemCount + visibleThreshold) >= totalItemCount) { 
      loading = onLoadMore(currentPage + 1, totalItemCount); 
     } 
    } 

    // Defines the process for actually loading more data based on page 
    // Returns true if more data is being loaded; returns false if there is no more data to load. 
    public abstract boolean onLoadMore(int page, int totalItemsCount); 

    @Override 
    public void onScrollStateChanged(AbsListView view, int scrollState) { 
     // Don't take any action on changed 
    } 
} 

然後如下更改代碼的新類。

您在asynctask中傳遞的pagecount實際上是列表的大小。所以你可以在網絡上傳輸數據後更新這個變量。

public class ProductView extends AppCompatActivity { 

ListView list_product; 

String json; 

ProgressActivity loadingview; 

int Pagecount = 0 

Toolbar toolbar; 

GetProductAdapter productAdapter; 
List<BeanGetProducts> beanGetProductses = new ArrayList<>(); 


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

    toolbar = (Toolbar) findViewById(R.id.back_toolbar); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    getSupportActionBar().setHomeButtonEnabled(true); 

    toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      onBackPressed(); 
     } 
    }); 

    ImageView img_home = (ImageView) findViewById(R.id.dr_image_home); 

    img_home.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(ProductView.this, AdminAccess.class); 
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intent); 
      finish(); 
     } 
    }); 
    list_product = (ListView) findViewById(R.id.list_products); 
    productAdapter = new GetProductAdapter(beanGetProductses, ProductView.this, getApplicationContext()); 

    // Load first time data and insert into list. 
    new getProducts(Pagecount).execute(); 

    list_product.setOnScrollListener(new EndlessScrollListener() { 
     @Override 
     public boolean onLoadMore(int page, int totalItemsCount) { 
      // Triggered only when new data needs to be appended to the list 
      // Add whatever code is needed to append new items to your AdapterView 
      new getProducts(Pagecount).execute(); 
      // or loadNextDataFromApi(totalItemsCount); 
      return true; // ONLY if more data is actually being loaded; false otherwise. 
     } 
    }); 

} 


public class getProducts extends AsyncTask<Void, Void, String> { 

    int pageNo; 
    public getProducts(int pageNo) { 
     this.pageNo = pageNo; 
    } 


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


      loadingv 

iew = new ProgressActivity(ProductView.this, ""); 
       loadingview.setCancelable(false); 
       loadingview.show(); 


      } catch (Exception e) { 


      } 
     } 

     @Override 
     protected String doInBackground(Void... voids) { 


      List<NameValuePair> pairs = new ArrayList<>(); 
      pairs.add(new BasicNameValuePair("", String.valueOf(pageNo))); 

      json = new ServiceHandler().makeServiceCall(GlobalLinks.mainLink + GlobalLinks.productDetails, ServiceHandler.POST, pairs); 


      Log.e("Parameters", "" + pairs); 


      return json; 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      loadingview.dismiss(); 

      System.out.println(s); 

      try { 

       if (!Internet.isConnectingToInternet(getApplicationContext())) { 
        Internet.noInternet(getApplicationContext()); 
       } else { 

        if (s.equalsIgnoreCase(null) || s.equalsIgnoreCase("") || s.equalsIgnoreCase("null") || s.length() == 0) { 
         GlobalUse.nullJSON(getApplicationContext()); 
        } else { 

         JSONObject mainObject = new JSONObject(s); 

         boolean status = mainObject.getBoolean("status"); 
         String message = mainObject.getString("message"); 
         totalPage = mainObject.getInt("total_page"); 
         Log.e("total_page", "" + totalPage); 

         Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_LONG).show(); 

         if (status == true) { 

          JSONArray dataArray = mainObject.getJSONArray("data"); 
    // Update Pagecount here 
Pagecount = Pagecount + dataArray.length(); 
          for (int i = 0; i < dataArray.length(); i++) { 


           JSONObject object = dataArray.getJSONObject(i); 
           JSONObject getProductObject = object.getJSONObject("GetProduct"); 

           BeanGetProducts getProducts = new BeanGetProducts(); 

           getProducts.setProduct_id(getProductObject.getString("product_id")); 
           getProducts.setImage(getProductObject.getString("image")); 
           getProducts.setSku(getProductObject.getString("sku")); 
           getProducts.setQuantity(getProductObject.getString("quantity")); 
           getProducts.setPrice(getProductObject.getString("price")); 
           getProducts.setStock_status_id(getProductObject.getString("stock_status_id")); 


           JSONObject product_description = object.getJSONObject("Product_Description"); 

           getProducts.setName(product_description.getString("name")); 
           getProducts.setDescription(product_description.getString("description")); 

           JSONObject SpecialPrice = object.getJSONObject("SpecialPrice"); 

           getProducts.setSpecialPrice(SpecialPrice.getString("price")); 


           beanGetProductses.add(getProducts); 
           productAdapter.notifyDataSetChanged(); 
          } 
         } 
        } 
       } 

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


     } 
    } 

    public void onBackPressed() { 

     Intent intent = new Intent(getApplicationContext(), AdminAccess.class); 
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     startActivity(intent); 
     finish(); 


    } 

    }