2014-04-04 5 views
0

View pager 이미지가있는 MainActivity에 Fragment Home.java가 있습니다. 타이머를 사용하여이 뷰 페이지 안에있는 이미지의 자동 슬라이딩을 예약했습니다. 장치에서 뒤로 단추를 클릭하여 응용 프로그램을 종료 할 때마다 NULL 포인터 예외가 발생합니다. 여기에 내 코드안드로이드 프래그먼트의 타이머 안의 Null 포인터 예외

public class Home extends Fragment { 


    Timer timer ; //Timer variable 
    int page = -1; //Page starts at zero. 
    int page1 = 8; //Number of images there are 
    int flag = 0; 
    int y =0; 

    ImageLoader imageLoader; 
    DisplayImageOptions options; 

    //Images to be displayed on top 
    String[] imageUrls = new String [] { 
       "https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s1024/Golden%252520Grass.jpg", 
       "https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s1024/Grand%252520Teton.jpg", 
       "https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s1024/Grass%252520Closeup.jpg", 
       "https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s1024/Highway%2525201.jpg", 
       "https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s1024/Lake%252520Tahoe%252520Colors.jpg", 
       "https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s1024/Leica%25252050mm%252520Summilux.jpg", 
       "https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s1024/Lost%252520in%252520a%252520Field.jpg", 
       "https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s1024/Sin%252520Lights.jpg"   
    }; 




    ViewPager pager; 
    CirclePageIndicator circleindicator; 



    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 

     View rootView = inflater.inflate(R.layout.home, container, false); 

     imageLoader = ImageLoader.getInstance(); 
     imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity())); 

     options = new DisplayImageOptions.Builder() 
     .showImageForEmptyUri(R.drawable.ic_launcher) 
     .showImageOnFail(R.drawable.add_marker) 
     .resetViewBeforeLoading(true) 
     .cacheOnDisc(true) 
     .imageScaleType(ImageScaleType.EXACTLY) 
     .bitmapConfig(Bitmap.Config.RGB_565) 
     .considerExifParams(true) 
     .displayer(new FadeInBitmapDisplayer(300)) 
     .build(); 


     pager = (ViewPager) rootView.findViewById(R.id.view_pagerhome); 
     pager.setAdapter(new ImagePagerAdapter(imageUrls)); 

     circleindicator = (CirclePageIndicator) rootView.findViewById(R.id.indicatorhome); 
     circleindicator.setViewPager(pager); 

     pageSwitcher(); //This method will change the images automatically after a certain period of time 


     return rootView; 
    } 

    public static Timer getTimerValue() 
{ 
    return timer; 
} 
    private void pageSwitcher() { 
     timer = new Timer(); // At this line a new Thread will be created 
     timer.scheduleAtFixedRate(new RemindTask(), 0, 3 * 1000); 
     // Delay in milliseconds 

    } 


    // this is an inner class... 
    class RemindTask extends TimerTask { 
     //Still to be executed, on manual change page 
     // Thought!! on pagechangelistener() set the pager.setCurrentItem to current position 
     //Find a way to determine the current position 
     //and when you find the current position update page and page1 items accordingly. 


      public void run() { 

      // As the TimerTask run on a seprate thread from UI thread we have 
      // to call runOnUiThread to do work on UI thread. 



      getActivity().runOnUiThread(new Runnable() { 
       public void run() { 

        if(page>8) 
        { 

        //This code will execute right to left 
        //Here page1 is decrement with the starting value of 8 equal to the number of pages 
        //On Reaching zero it should take the control to the else statement and execute 
        //left to right 

         //Managing manual view pager changes 
         y = pager.getCurrentItem(); 
         y--; 
         page1 = y; 
         //managed 

         pager.setCurrentItem(page1--); 
         if(page1==-1) 
         { 
          page=-1; 
          flag=0; 
         } 
        } 

        else 
        { 
         //This code will execute from left to right. 
         //where page is the page number (total images - here 8) 
         //On reaching the end where page = 8, page 1 will set to 8 and then move 
         //right to left 

          //Managing manual view pager changes 
          if(flag==0) 
          { 
          int x = pager.getCurrentItem(); 
          page = x; 
          flag = 1; 
          } 
          else 
          { 
           int x = pager.getCurrentItem(); 
           x++; 
           page = x; 
          } 
          //managed 

          pager.setCurrentItem(page++); 

          if(page==8) 
          { 
           page1=8; 
          } 
        } 

       } 
      }); 


     } 
    } 


    //This adapter is for the images on the top of home screen, the sliding images 
    private class ImagePagerAdapter extends PagerAdapter { 


     private String[] images; 


     ImagePagerAdapter(String[] images) { 
      this.images = images; 

     } 

     @Override 
     public void destroyItem(ViewGroup container, int position, Object object) { 
      container.removeView((View) object); 
     } 

     @Override 
     public int getCount() { 
      return images.length; 
     } 


     @Override 
     public Object instantiateItem(ViewGroup view, int position) { 

      View imageLayout = getLayoutInflater(getArguments()).inflate(R.layout.item_pager_image, view, false); 
      assert imageLayout != null; 
      ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image); 
      final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading); 




      imageLoader.displayImage(images[position], imageView, options, new SimpleImageLoadingListener() { 
       @Override 
       public void onLoadingStarted(String imageUri, View view) { 
        spinner.setVisibility(View.VISIBLE); 
       } 



       @Override 
       public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { 
        spinner.setVisibility(View.GONE); 
       } 
      }); 

      view.addView(imageLayout, 0); 
      return imageLayout; 
     } 

     @Override 
     public boolean isViewFromObject(View view, Object object) { 
      return view.equals(object); 
     } 

     @Override 
     public void restoreState(Parcelable state, ClassLoader loader) { 
     } 

     @Override 
     public Parcelable saveState() { 
      return null; 
     } 
    } 
     //End of adapter 


} 

내 로그 캣이

Logcat

어떻게이 문제를 해결하는 데있어 여기? 내가 한 것은 타이머 변수라는 MainActivity에 있었고 작업이 완료되기 전에 취소되었습니다. 이게 내가 한 일이야.

@Override 
public void onBackPressed() { 
    if (doubleBackToExitPressedOnce) { 
    Timer timer = Home.getTimerValue(); 
    timer.cancel(); 
    super.onBackPressed(); 
    return; 
    } 
    this.doubleBackToExitPressedOnce = true; 
    Toast.makeText(this, "Press Again to Exit", Toast.LENGTH_SHORT).show(); 


    } 

MainActivity를 사용 중이고 두 번 뒤로 누르면 NPE가 표시되지 않습니다. 하지만 다른 액티비티로 이동하여 MainActivity로 돌아 가면이 예외가 다시 발생합니다.

+1

실제로 logcat을 텍스트 편집기에 복사 할 수 있습니다. 스크린 샷을 찍을 때의 고통을 감수하지 마십시오. –

+0

은 119 @ 012에있는 null을 가리키는 객체를 사용하려고 시도하는 것 같습니다. – donfuxx

+0

@mishra. 그것은 색깔이 좋아 보인다. – user1377504

답변

2

조각이 활성화되어있을 때만 타이머를 실행하고 싶습니다. 앱을 종료하면 getActivity()null을 반환 할 수 있습니다. 만들고 onStart()Timer 시작하고 조각의 onStop()에서 취소하십시오. 그게 효과가있다.

+0

나는 그것을 시험해 볼 것이다. 감사합니다 – user1377504

+0

나는 onStop()을 시도했지만 여전히 예외가 발생했습니다 – user1377504

+0

질문에있는 코드를 업데이트하고 NPE를받는 라인을 알려주십시오. – SimonSays