2017-04-04 8 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에서 전달할 페이지 수가 실제로는 목록의 크기입니다. 따라서 네트워크에서 데이터를 래핑 한 후에이 변수를 업데이트 할 수 있습니다.

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


    } 

    }