调用getActivity()时片段类中的Nullpointer异常.getApplicationContext()

时间:2014-11-05 09:49:31

标签: android sqlite gridview android-fragments views

我在使用光标时得到nullpointer异常。在这一点上感到困惑,因为我相信每个片段都在一个活动中,我在google中提到了一些点,我得到了这个异常,而我的片段实例不是附加到Activity。(我的程序是从gallery中获取所有图像并将其作为网格视图列在我的片段中,我在这里使用SWIPABLE视图)。 提前谢谢...

 public ArrayList<String> getFilePaths()
        {

//       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
//       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            Uri u =MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
            System.out.println("uri is"+u);
            String[] projection =  { MediaStore.Images.Media.DATA }; 

//              {MediaStore.Images.ImageColumns.DATA};
//          { MediaStore.Images.Media.DATA };
            Cursor c = null;

            //treeset in which images are sorted in ascending order
            SortedSet<String> dirList = new TreeSet<String>();
            ArrayList<String> resultIAV = new ArrayList<String>();

             String[] directories = null; 
            if ((u != null) &&(projection!=null)) 
            { 
                System.out.println("projection is"+projection);
                //null pointer exception
//               Cursor cursor = getContentResolver().query(selectedImage,
//                       filePathColumn, null, null, null);
                //getContentResolver().
                Log.e("devicetab","cursor not equalto null");
                Log.e("devicetab",getActivity().getApplicationContext().toString());
                //not executing this line
                //getSupportLoadManager().initLoader(0, null, getActivity());
//              c=getSupportLoaderManager.(u, projection,null,null,null); 
                System.out.println("context "+getActivity().getApplicationContext());

                System.out.println("activity"+getActivity());
                c =getActivity().getApplicationContext().getContentResolver().query(u, projection, null, null, null); 
//              c =getActivity().getContentResolver().query(u, projection,null,null,null); 
                getActivity().startManagingCursor(c);
                c.moveToFirst();
                Log.e("devicetab","cursor");

            } 

            if ((c != null) && (c.moveToFirst())) 
            { 
                do 
                {
                    String tempDir = c.getString(0);
                    tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
                    try{
                        dirList.add(tempDir);
                    }
                    catch(Exception e)
                    {

                    }
                } 
                while (c.moveToNext());
                //string array driectories
                directories = new String[dirList.size()];
                dirList.toArray(directories);

            }
//             c.close();
            for(int i=0;i<dirList.size();i++)
            {
                File imageDir = new File(directories[i]);
                File[] imageList = imageDir.listFiles();

//              File targetDirector = new File(picturePath);
//              Log.e("Devicetab","before files");
//              File[] files = targetDirector.listFiles();



                if(imageList == null)
                    continue;
                for (File imagePath : imageList) { 
                    try {

                            if(imagePath.isDirectory())
                            {
                                imageList = imagePath.listFiles();

                            }
                            if ( imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG")  
                                    || imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")                                    
                                    || imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
                                    || imagePath.getName().contains(".gif") || imagePath.getName().contains(".GIF")
                                    || imagePath.getName().contains(".bmp") || imagePath.getName().contains(".BMP")                         
            )
                            {



                                String path= imagePath.getAbsolutePath();
                            resultIAV.add(path);

                            }
                        }
                //  }
                catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            return resultIAV;


        }

这是我的logcat

11-05 05:19:25.659: W/TabsPagerAdapter(9498): inside class2 fragmentmanager
11-05 05:19:25.689: E/Bqswipeview(9498): inside onTabSelected
11-05 05:19:25.689: E/Bqswipeview(9498): tabs added
11-05 05:19:26.269: W/TabsPagerAdapter(9498): inside class2 tabspageradapter
11-05 05:19:26.269: I/System.out(9498): uri iscontent://media/external/images/media
11-05 05:19:26.269: I/System.out(9498): projection is[Ljava.lang.String;@b1155080
11-05 05:19:26.269: E/devicetab(9498): cursor not equalto null
11-05 05:19:26.269: D/AndroidRuntime(9498): Shutting down VM
11-05 05:19:26.269: W/dalvikvm(9498): threadid=1: thread exiting with uncaught exception (group=0xb0d13b20)
11-05 05:19:26.269: E/AndroidRuntime(9498): FATAL EXCEPTION: main
11-05 05:19:26.269: E/AndroidRuntime(9498): Process: com.bq.bqgdrive, PID: 9498
11-05 05:19:26.269: E/AndroidRuntime(9498): java.lang.NullPointerException
11-05 05:19:26.269: E/AndroidRuntime(9498):     at com.bq.bqgdrive.DeviceTab.getFilePaths(DeviceTab.java:185)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at com.bq.bqgdrive.DeviceTab.<init>(DeviceTab.java:145)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at com.bq.tabsswipe.adapter.TabsPagerAdapter.getItem(TabsPagerAdapter.java:28)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:97)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.support.v4.view.ViewPager.populate(ViewPager.java:987)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.View.measure(View.java:16497)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.View.measure(View.java:16497)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.View.measure(View.java:16497)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.View.measure(View.java:16497)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.Choreographer.doFrame(Choreographer.java:544)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.os.Handler.handleCallback(Handler.java:733)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.os.Looper.loop(Looper.java:136)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at android.app.ActivityThread.main(ActivityThread.java:5017)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at java.lang.reflect.Method.invoke(Method.java:515)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-05 05:19:26.269: E/AndroidRuntime(9498):     at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:0)

我认为你必须初始化游标,然后从游标中获取任何东西,

你可以直接`getActivity()。getContentResolver()。试试这个,

如果它不起作用,则显示Log cat。

答案 1 :(得分:0)

我解决了这个问题...将异常发生部分移动到onAttach使用了上下文对象。更多参考检查下面的代码

 ImageAdapter myImageAdapter;
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    activity.setContentView(R.layout.devicetab);
    Log.e("Devicetab","onCreate ");
    GridView gridview = (GridView) activity.findViewById(R.id.gridView1);
    //myImageAdapter=new ImageAdapter(this);

    ArrayList<String> arrlist=getFilePaths(activity.getApplicationContext());
    Iterator<String> itr=arrlist.iterator();

    myImageAdapter = new ImageAdapter(activity.getApplicationContext());

      do
      {
          String obj=itr.next();
//        setAdapter(obj);
          myImageAdapter.add(obj);
      }
      while(itr.hasNext());

    gridview.setAdapter(myImageAdapter);





}




     public ArrayList<String> getFilePaths(Context cntx)
        {

            Uri u =MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
            System.out.println("uri is"+u);
            String[] projection =  { MediaStore.Images.Media.DATA }; 

            Cursor c = null;

            //treeset in which images are sorted in ascending order
            SortedSet<String> dirList = new TreeSet<String>();
            ArrayList<String> resultIAV = new ArrayList<String>();

             String[] directories = null; 
            if ((u != null) &&(projection!=null)) 
            { 
                System.out.println("projection is"+projection);

                Log.e("devicetab","cursor not equalto null");

                //System.out.println("context "+getActivity().getApplicationContext());
                //here null pointer occurs

                c =cntx.getContentResolver().query(u, projection, null, null, null); 

                getActivity().startManagingCursor(c);
                c.moveToFirst();
                Log.e("devicetab","cursor");

            } 

            if ((c != null) && (c.moveToFirst())) 
            { 
                do 
                {
                    String tempDir = c.getString(0);
                    tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
                    try{
                        dirList.add(tempDir);
                    }
                    catch(Exception e)
                    {

                    }
                } 
                while (c.moveToNext());
                //string array driectories
                directories = new String[dirList.size()];
                dirList.toArray(directories);

            }

            for(int i=0;i<dirList.size();i++)
            {
                File imageDir = new File(directories[i]);
                File[] imageList = imageDir.listFiles();



                if(imageList == null)
                    continue;
                for (File imagePath : imageList) { 
                    try {

                            if(imagePath.isDirectory())
                            {
                                imageList = imagePath.listFiles();

                            }
                            if ( imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG")  
                                    || imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")                                    
                                    || imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
                                    || imagePath.getName().contains(".gif") || imagePath.getName().contains(".GIF")
                                    || imagePath.getName().contains(".bmp") || imagePath.getName().contains(".BMP")                         
            )
                            {



                                String path= imagePath.getAbsolutePath();
                            resultIAV.add(path);

                            }
                        }

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

            return resultIAV;


        }

答案 2 :(得分:0)

尝试在实例化Fragment时从活动传递上下文,并使用此上下文而不是getActivity()函数。

答案 3 :(得分:0)

java.lang.NullPointerException
  at com.bq.bqgdrive.DeviceTab.getFilePaths(DeviceTab.java:185)
  at com.bq.bqgdrive.DeviceTab.<init>(DeviceTab.java:145)

构造函数或成员变量初始化<init>为时过早,无法调用getActivity()。该片段尚未附加到活动中。

将初始化和getFilePaths()电话移至fragment lifecycle中的onAttach()或更晚。