getApplicationContext()上的空指针异常

时间:2015-12-24 14:14:32

标签: java android android-fragments

我使用扩展活动尝试了以下代码,但是现在我更改了代码以使用扩展片段。我在网上搜索并找到getActivity()函数来调用query()和其他函数。我尝试了这个,但现在它出错了:

错误

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.admin.funtube_mp4/com.example.admin.funtube_mp4.Main}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.admin.funtube_mp4.HomeFragmant.init_phone_video_grid(HomeFragmant.java:65)
            at com.example.admin.funtube_mp4.HomeFragmant.onCreateView(HomeFragmant.java:49)
            at android.app.Fragment.performCreateView(Fragment.java:1700)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
            at android.app.BackStackRecord.run(BackStackRecord.java:684)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
            at android.app.Activity.performStart(Activity.java:5550)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)

public class HomeFragmant extends Fragment{
    private Cursor videocursor;
    private int video_column_index;
    ListView videolist;

    List<String> listpath = new ArrayList<String>();
    String[] paths=new String[100];
    int count;
    String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA, MediaStore.Video.Thumbnails.VIDEO_ID };
    String path;
    File file;

    public HomeFragmant() {
    }

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

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        videolist = (ListView) getActivity(). findViewById(R.id.PhoneVideoList);
        init_phone_video_grid();

        return rootView;

    }
    private void init_phone_video_grid() {
        System.gc();
        String[] proj = { MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.SIZE };

      //  file = new File(Environment.getExternalStorageDirectory() + File.separator + "Funtube/UserData/Videos/");
       // videocursor =getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, MediaStore.Images.Media.DATA + " LIKE ? ", new String[]{"%" + file.getAbsolutePath().toString() + "%"}, null);
        videocursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,proj, null, null, null);
//        videocursor =getActivity().managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, MediaStore.Images.Media.DATA + " LIKE ? ", new String[]{"%" + file.getAbsolutePath().toString() + "%"}, null);

        count = videocursor.getCount();

        videolist.setAdapter(new VideoAdapter(getActivity().getApplicationContext()));
        videolist.setOnItemClickListener(videogridlistener);
    }

    private AdapterView.OnItemClickListener videogridlistener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position,long id) {
            System.gc();
            video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            videocursor.moveToPosition(position);
            String filename = videocursor.getString(video_column_index);
            Intent intent = new Intent(getActivity(),ViewVideo.class);
            intent.putExtra("videofilename", filename);
            startActivity(intent);
        }
    };

    public class VideoAdapter extends BaseAdapter {
        private Context vContext;

        public VideoAdapter(Context c) {
            vContext = c;
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            System.gc();
            ViewHolder holder;
            String id = null;
            convertView = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
                holder = new ViewHolder();
                holder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
                holder.txtSize = (TextView) convertView.findViewById(R.id.txtSize);
                holder.thumbImage = (ImageView) convertView.findViewById(R.id.imgIcon);

                video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
                videocursor.moveToPosition(position);
                id = videocursor.getString(video_column_index);
                video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
                videocursor.moveToPosition(position);
                // id += " Size(KB):" +
                // videocursor.getString(video_column_index);
                holder.txtTitle.setText(id);
                holder.txtSize.setText(" Size(KB):"+ videocursor.getString(video_column_index));

                String[] proj = { MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA };
                @SuppressWarnings("deprecation")
                Cursor cursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, MediaStore.Video.Media.DISPLAY_NAME + "=?", new String[]{id}, null);
                cursor.moveToFirst();
                long ids = cursor.getLong(cursor
                        .getColumnIndex(MediaStore.Video.Media._ID));

                ContentResolver crThumb = getActivity().getContentResolver();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 1;
                Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
                        crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND,
                        options);
                holder.thumbImage.setImageBitmap(curThumb);
                curThumb = null;

            } /*
             * else holder = (ViewHolder) convertView.getTag();
             */
            return convertView;
        }
    }

    static class ViewHolder {

        TextView txtTitle;
        TextView txtSize;
        ImageView thumbImage;
    }
}

2 个答案:

答案 0 :(得分:1)

请勿在{{1​​}}中致电getActivity(),您无法保证onCreateView在那里完全创建。使用Activity方法获取对onActivityCreated

的引用

除非您害怕泄露Activity,否则您只需使用Activity,无需检索ApplicationContext即可创建适配器恕我直言。

来自docs about Fragments

  

警告:如果在Fragment中需要Context对象,则可以   调用getActivity()。但是,请注意只调用getActivity()   当片段附加到活动时。当片段不是   尚未附着,或在其生命周期结束时被分离,   getActivity()将返回null。

答案 1 :(得分:0)

完全同意@ 2Dee,可能只需要尝试使用 getActivity()

videolist.setAdapter(new VideoAdapter(getActivity()));