2017-03-24 226 views
-4

這是我的代碼時,我實現獲得項目計數1這表明非靜態方法不能引用當我實現計數2顯示它在return語句helpme空指針異常修復此的Android空指針異常

final int speedScroll = 1000; 
    final Handler handler = new Handler(); 
    final Runnable runnable = new Runnable() { 
     int count = 0; 
     @Override 
     public void run() { 
      if(count == Adapter4.getItemCount2()) 
       count =0; 
      if(count < Adapter4.getItemCount2()){ 
       recyclerView4.smoothScrollToPosition(++count); 
       handler.postDelayed(this,speedScroll); 
      } 
     } 
    }; 
    handler.postDelayed(runnable,speedScroll); 
} 


@Override 
public int getItemCount() { 
    return albumList.size(); 
} 
public static int getItemCount2() { 

    List<Album4> albumList=null; 
     return albumList.size(); 
} 
+0

你快把它'null',你怎麼能得到空變量的'size' ..嘗試用)像'名單 albumList =新的ArrayList <>('這將返回'0'; –

+0

我假設變量'albumList'是全局變量,所以嘗試刪除或至少重命名您的'getItemCount2'方法中具有相同名稱的變量 – Barak

+0

有兩件事可能會導致您的錯誤的問題 1st是: @Override public int getItemCount(){ return albumList.size(); } 可能是albumList尚未初始化,這導致空例外。 2nd is: public static int getItemCount2(){ List albumList = null; return albumList.size(); } 你用null初始化列表,然後返回將導致null異常的大小。 –

回答

0

試試這個。假設變量albumList是全局的。和albumList不爲空;

final int speedScroll = 1000; 
     final Handler handler = new Handler(); 
     final Runnable runnable = new Runnable() { 
      int count = 0; 
      @Override 
      public void run() { 
       if(count == albumList.size()) 
        count =0; 
       if(count < albumList.size()){ 
        recyclerView4.smoothScrollToPosition(++count); 
        handler.postDelayed(this,speedScroll); 
       } 
      } 
     }; 
     handler.postDelayed(runnable,speedScroll); 
    } 


    @Override 
    public int getItemCount() { 
     return albumList.size(); 
    }