HomeBaseFragment中运行时的空指针异常

时间:2014-02-27 12:47:48

标签: android android-fragments stack-trace android-logcat

在运行时发生堆栈跟踪错误,同时在Fragments的帮助下开发Gems应用程序。这是我的代码..

AppData.java

public class AppData {

    private static Context mContext;
    private static Typeface typefaceTamil;
    private static Typeface typefaceEnglish;
    private static Typeface typefaceHindi;
    private static Typeface typefaceTitle;
    private List<Gallery> galleries;
    private List<String> languages;
    private String language;
    private Map<String, List<Blog>> mapBlog;
    private Map<String, List<Audio>> mapAudio;
    private Map<String, List<Video>> mapVideo;
    private List<Announcement> announcements;
    private Map<String,List<Product>> products;
    private List<Category> categories;
    private boolean isPlaying;
    private static int screenWidth;
    public static boolean isVideoPlaying=false;
    private int screenHeight;
    private String magzfiles;
    private List<Magzine> magzines;
    private static Video liveStreamVideo;
    private String blogLang;
    private String videoLang;

    public AppData(Context context) {
        mContext = context;
        languages = new ArrayList<String>();
        addLanguages();
        WindowManager windowManager = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();
        mapAudio = new HashMap<String, List<Audio>>();
        mapBlog = new HashMap<String, List<Blog>>();
        mapVideo = new HashMap<String, List<Video>>();
        this.products=new HashMap<String, List<Product>>();
    }

    private void addLanguages() {
        languages.add("English");
        languages.add("Tamil");
        languages.add("Hindi");

    }

    private static void initFontStyles() {
        typefaceTamil = Typeface.createFromAsset(mContext.getAssets(),
                "fonts/tamil_nambi.ttf");
    /*  typefaceEnglish = Typeface.createFromAsset(mContext.getAssets(),
                "fonts/warnock_regular.otf");*/
        typefaceEnglish = Typeface.DEFAULT;
        typefaceHindi = Typeface.createFromAsset(mContext.getAssets(),
                "fonts/vigyapti.ttf");
    /*  typefaceTitle = Typeface.createFromAsset(mContext.getAssets(),
                "fonts/menu_title.ttf");*/
        typefaceTitle=Typeface.DEFAULT_BOLD;
    }

    public static Typeface getTamilFont() {
        if (typefaceTamil == null) {
            initFontStyles();
        }
        return typefaceTamil;
    }

    public static Typeface getTitleFont() {
        if (typefaceTitle == null) {
            initFontStyles();
        }
        return typefaceTitle;
    }

    public static Typeface getEnglishFont() {
        if (typefaceEnglish == null) {
            initFontStyles();
        }
        return typefaceEnglish;
    }

    public static Typeface getHindiFont() {
        if (typefaceHindi == null) {
            initFontStyles();
        }
        return typefaceHindi;
    }

    public List<String> getlanguages() {
        return languages;
    }

    public void setBlogs(String lnag, List<Blog> blogs) {
        if (mapBlog == null) {
            mapBlog = new HashMap<String, List<Blog>>();
        }
        mapBlog.put(lnag, blogs);
    }

    public List<Gallery> getGalleries() {
        return galleries;
    }

    public void setGalleries(List<Gallery> galleries) {
        this.galleries = galleries;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public List<Blog> getBlogs(String lang) {
        return mapBlog.get(lang);
    }

    public List<Audio> getAudios(String lang) {

        return mapAudio.get(lang);
    }

    public void setAudios(String lang, List<Audio> audios) {
        if (mapAudio == null) {
            mapAudio = new HashMap<String, List<Audio>>();
        }
        mapAudio.put(lang, audios);
    }

    public void setVideos(String lang, List<Video> videos) {
        if (mapVideo == null) {
            mapVideo = new HashMap<String, List<Video>>();
        }
        mapVideo.put(lang, videos);
    }

    public List<Video> getVideos(String lang) {

        return mapVideo.get(lang);
    }

    public static Typeface getTypeFace(String language) {
        if (language.equalsIgnoreCase("English")) {
            return getEnglishFont();
        } else if (language.equalsIgnoreCase("Hindi")) {
            return getHindiFont();
        } else if (language.equalsIgnoreCase("Tamil")) {
            return getTamilFont();
        }

        return getEnglishFont();
    }

    public void clearData() {
        if (mapAudio != null)
            mapAudio.clear();
        if (mapBlog != null)
            mapBlog.clear();
        if (mapVideo != null)
            mapVideo.clear();
        if(galleries!=null)
            galleries.clear();
        if(announcements!=null)
            announcements.clear();
        if(products!=null)
            products.clear();
        if(magzines!=null)
            magzines.clear();

        setBlogLang(null);
        setVideoLang(null);


    }

    public boolean isPlaying() {
        return isPlaying;
    }

    public void setPlaying(boolean isPlaying) {
        this.isPlaying = isPlaying;
    }

    public List<Announcement> getAnnouncements() {
        return announcements;
    }

    public void setAnnouncements(List<Announcement> announcements) {
        this.announcements = announcements;
    }

    public List<Product> getProducts(String cat) {
        return products.get(cat);
    }

    public void setProducts(String cat,List<Product> products) {
        if(this.products==null)
            this.products=new HashMap<String, List<Product>>();
        this.products.put(cat, products);
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    public static int getScreenWidth() {
        return screenWidth;
    }

    public List<Magzine> getMagzines() {
        return magzines;
    }

    public void setMagzines(List<Magzine> magzines) {
        this.magzines = magzines;
    }

    public void setLiveStreamVideo(Video video) {
        liveStreamVideo=video;

    }
    public Video getLiveStreamVideo() {
        return liveStreamVideo;

    }

    public void setBlogLang(String lang) {
        blogLang=lang;
    }
    public String getBlogLang() {
        return blogLang;
    }

    public static boolean isAudioAvalableinSD(String title) {
        String path ="";
        try {
            path = getPath(title);
            if(path==null)
                return false;   
        } catch (Exception e) {
            return false;
        }

        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static String getPath(String title)  throws Exception{


        final String cachePath =
                Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                        !isExternalStorageRemovable() ? getExternalCacheDir(mContext).getPath() :
                                mContext.getCacheDir().getPath();

        return cachePath+ File.separator +title.trim() + ".mp3";
    }
     public static File getExternalCacheDir(Context context) {
            if (Utils.hasFroyo()) {
                return context.getExternalCacheDir();
            }

            // Before Froyo we need to construct the external cache dir ourselves
            final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
            return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
        }
    public static boolean isExternalStorageRemovable() {
        if (Utils.hasGingerbread()) {
            return Environment.isExternalStorageRemovable();
        }
        return true;
    }

    public String getVideoLang() {
        return videoLang;
    }

    public void setVideoLang(String videoLang) {
        this.videoLang = videoLang;
    }
}

HomeBaseFragment.java

public class HomeBaseFragment extends BaseFragment implements OnTabChangeListener {

    private View mRoot;
    private TabHost mTabHost;
    private int mCurrentTab;
    private AudioFragment mAudioFragment;
    private LiveStreamFragment liveStreamFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new GetLiveStreamVideoTask(getActivity()).execute();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mRoot = inflater.inflate(R.layout.layout_home, null);
        mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);

        mAudioFragment = new AudioFragment();
        liveStreamFragment = new LiveStreamFragment();
        setupTabs();



        return mRoot;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        updateTab("Home", R.id.tab_home);
    }

    public class GetLiveStreamVideoTask extends CustomAsyncTask {

        private String responseString;

        public GetLiveStreamVideoTask(Activity activity) {
            super(activity);
            enableLoadingDialog(false);
        }

        @Override
        public void doTask() throws Exception {

            responseString = APIServiceHandler
                    .getData("http://splendor.pro/gemapp/api/livestream.php");

        }

        @Override
        public void doFinish() {

            if (responseString != null) {

                try {
                    JSONObject resposeJsonObject = new JSONObject(
                            responseString);
                    int statusCode = resposeJsonObject.optInt("statusCode", 0);
                    if (statusCode == 200) {
                        JSONArray jsonArray = resposeJsonObject
                                .getJSONArray("videos");
                        List<Video> videos = new ArrayList<Video>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            Video video = new Video(jsonArray.getJSONObject(i));
                            videos.add(video);
                        }
                        if(videos.size()>0){
                            Video video=videos.get(0);
                            appData.setLiveStreamVideo(video);
                        }


                    } 
                } catch (Exception e) {
                }

            }

        }

    }

    private void setupTabs() {
        mTabHost.setup();
        mTabHost.addTab(newTab(getString(R.string.str_home), R.string.str_home,
                R.drawable.home_selector, R.id.tab_home));
        mTabHost.addTab(newTab(getString(R.string.str_video),
                R.string.str_video, R.drawable.video_icon_selector,
                R.id.tab_video));
        mTabHost.addTab(newTab(getString(R.string.str_audio),
                R.string.str_audio, R.drawable.audio_icon_selector,
                R.id.tab_audio));
        mTabHost.addTab(newTab(getString(R.string.str_blog), R.string.str_blog,
                R.drawable.blog_icon_selector, R.id.tab_blog));
        mTabHost.addTab(newTab(getString(R.string.str_gal), R.string.str_gal,
                R.drawable.gal_icon_selector, R.id.tab_gal));
        mTabHost.addTab(newTab(getString(R.string.str_more), R.string.str_more,
                R.drawable.more_icon_selector, R.id.tab_more));

        mTabHost.setOnTabChangedListener(this);

    }

    private TabSpec newTab(String tag, int labelId, int tabImg, int tabContentId) {
        //AppLog.d("TAG", "buildTab(): tag=" + tag);

        View indicator = LayoutInflater.from(getActivity()).inflate(
                R.layout.tab,
                (ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
        TextView textView = ((TextView) indicator.findViewById(R.id.tab_text));
        textView.setText(labelId);
        textView.setTypeface(AppData.getTitleFont());
        // textView.setSelected(true);
        ((ImageView) indicator.findViewById(R.id.tab_img))
                .setImageResource(tabImg);

        TabSpec tabSpec = mTabHost.newTabSpec(tag);
        tabSpec.setIndicator(indicator);
        tabSpec.setContent(tabContentId);
        return tabSpec;
    }

    @Override
    public void onTabChanged(String arg0) {
        if (getString(R.string.str_home).equals(arg0)) {
            updateTab(arg0, R.id.tab_home);
            mCurrentTab = 0;
            return;
        } else if (getString(R.string.str_video).equals(arg0)) {
            updateTab(arg0, R.id.tab_video);
            mCurrentTab = 1;
            return;
        } else if (getString(R.string.str_audio).equals(arg0)) {
            updateTab(arg0, R.id.tab_audio);
            mCurrentTab = 2;
            return;
        } else if (getString(R.string.str_blog).equals(arg0)) {
            updateTab(arg0, R.id.tab_blog);
            mCurrentTab = 3;
            return;
        } else if (getString(R.string.str_gal).equals(arg0)) {
            updateTab(arg0, R.id.tab_gal);
            mCurrentTab = 4;
            return;
        } else if (getString(R.string.str_more).equals(arg0)) {

            updateTab(arg0, R.id.tab_more);
            mCurrentTab = mTabHost.getCurrentTab();
            return;
        }

    }

    private void updateTab(String tabId, int placeholder) {

        FragmentManager fm = getFragmentManager();

        mAudioFragment.stopPlay(tabId);


        if (fm.findFragmentByTag(tabId) == null) {
            if(AppData.isVideoPlaying && fm.findFragmentById(R.id.tab_video) != null){
                fm.popBackStack();
            }
            switch (placeholder) {
            case R.id.tab_home:
                fm.beginTransaction()
                        .replace(placeholder, new HomeFragment(), tabId)
                        .commit();
                break;
            case R.id.tab_video:
                fm.beginTransaction()
                        .replace(placeholder, new VideoFragment(), tabId)
                        .commit();
                break;
            case R.id.tab_audio:
                fm.beginTransaction()
                        .replace(placeholder, mAudioFragment, tabId).commit();
                break;
            case R.id.tab_blog:
                fm.beginTransaction()
                        .replace(placeholder, new BlogFragment(), tabId)
                        .commit();
                break;
            case R.id.tab_gal:
                fm.beginTransaction()
                        .replace(placeholder, new GalleryFragment(), tabId)
                        .commit();
                break;
            case R.id.tab_more:
                fm.beginTransaction()
                        .replace(placeholder, new MoreFragment(), tabId)
                        .commit();
                break;
            default:
                fm.beginTransaction()
                        .replace(placeholder, new HomeFragment(), tabId)
                        .commit();
                break;
            }
            // if(tabId.equalsIgnoreCase(R.s))
        } else if (fm.findFragmentByTag(tabId) != null) {
            if (tabId.equalsIgnoreCase(getString(R.string.str_more))) {
                fm.popBackStack();
            }

            if(AppData.isVideoPlaying && fm.findFragmentById(R.id.tab_video) != null){
                fm.popBackStack();
            }

        }
    }

    public void OnAudioSelected(Audio audio) {
        LiveStreamFragment audioDetailFragment = new LiveStreamFragment();
        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.tab_audio, audioDetailFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    public void OnBlogSelected(Blog blog,String lang) {

        BlogDetailFragment blogDetailFragment = new BlogDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("blog", blog);
        bundle.putString("lang", lang);
        blogDetailFragment.setArguments(bundle);
        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.tab_blog, blogDetailFragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }

    public void OnVideoSelected(Video video) {
        //LiveStreamFragment audioDetailFragment = new LiveStreamFragment();

        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        if(video.getVideoType().equalsIgnoreCase("Youtube")){
            Intent intent=new Intent(getActivity(),YoutubePlayActivity.class);
            intent.putExtra("videoid", video.getVideoUrl());
            intent.putExtra("title", video.getVideoTitle());
            startActivity(intent);
        }else{
            LiveStreamFragment tubePlayFragment=new LiveStreamFragment();

            Bundle bundle=new Bundle();
            bundle.putString("live","VIDEO");
            if(AppData.isAudioAvalableinSD(video.getVideoTitle().trim())){
                try {
                    bundle.putString("url", AppData.getPath(video.getVideoTitle().trim()));
                } catch (Exception e) {
                    bundle.putString("url", video.getVideoUrl());
                }
            }else{
                bundle.putString("url", video.getVideoUrl());
            }
            tubePlayFragment.setArguments(bundle);
            transaction.replace(R.id.tab_video, tubePlayFragment);

        }
        transaction.addToBackStack(null);
        transaction.commit();
    }

    public void onMoreFragmentOptionSelected(final int option) {
        switch (option) {
        case 1:
            AnnouncenentFragment fragment = new AnnouncenentFragment();
            FragmentTransaction transaction = getActivity()
                    .getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.tab_more, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
            break;
        case 2:
            MagzineFragment magzineFragment = new MagzineFragment();
            transaction = getActivity().getSupportFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.tab_more, magzineFragment);
            transaction.addToBackStack(null);
            transaction.commit();
            break;
        case 3:
            CategoryFragment categoryFragment = new CategoryFragment();
            transaction = getActivity().getSupportFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.tab_more, categoryFragment);
            transaction.addToBackStack(null);
            transaction.commit();
            break;
        case 4:
            LiveStreamFragment liveStreamFragment=new LiveStreamFragment();
        Bundle bundle=new Bundle();
        bundle.putString("live","LIVE STREAMING");
        bundle.putString("url", AppData.getLiveStreamVideo().getVideoUrl());//344th Line
        liveStreamFragment.setArguments(bundle);
        transaction = getActivity().getSupportFragmentManager()
                .beginTransaction();
        transaction.replace(R.id.tab_more, liveStreamFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;          
         case 5:
            PrayerRequestFragment prayerRequest = new PrayerRequestFragment();
            transaction = getActivity().getSupportFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.tab_more, prayerRequest);
            transaction.addToBackStack(null);
            transaction.commit();
            break;  
        case 6:
            SettingsFragment settingsFragment = new SettingsFragment();
            transaction = getActivity().getSupportFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.tab_more, settingsFragment);
            transaction.addToBackStack(null);
            transaction.commit();
            break;      


        default:
            break;
        }

    }

    public void onAnnouncementSelected(Announcement announcement) {
        AnnouncenentDetailFragment blogDetailFragment = new AnnouncenentDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString("date", announcement.getDate());
        bundle.putString("announcement", announcement.getAnnouncement());
        bundle.putString("title", announcement.getTitle());
        blogDetailFragment.setArguments(bundle);
        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.tab_more, blogDetailFragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }

    public void onProductSelected(Product product) {
        ProductDetailFragment productDetailFragment = new ProductDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("product", product);
        productDetailFragment.setArguments(bundle);
        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.tab_more, productDetailFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    public void onGalItemSelected(String pos,String name) {
        GalleryDetailFragment productDetailFragment = new GalleryDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id", pos);
        bundle.putString("name", name);
        productDetailFragment.setArguments(bundle);
        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.tab_gal, productDetailFragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }

    public void onInquirytSelected(Product product) {
        InquiryFragment productDetailFragment = new InquiryFragment();

        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        Bundle bundle=new Bundle();
        bundle.putParcelable("product",product);
        productDetailFragment.setArguments(bundle);
        transaction.replace(R.id.tab_more, productDetailFragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }

    public void oncategorySelected(String id,String name) {
        ProductFragment productFragment = new ProductFragment();

        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        Bundle bundle=new Bundle();
        bundle.putString("id",id);
        bundle.putString("name", name);
        productFragment.setArguments(bundle);
        transaction.replace(R.id.tab_more, productFragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }

    public void onMagzineSelected(Magzine magzine) {
        MagazineDetailFragment detailFragment=new MagazineDetailFragment();
        FragmentTransaction transaction = getActivity()
                .getSupportFragmentManager().beginTransaction();
        Bundle bundle=new Bundle();
        bundle.putString("url",magzine.getMagzfiles());
        bundle.putString("title",magzine.getContent());
        detailFragment.setArguments(bundle);
        transaction.replace(R.id.tab_more, detailFragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }

}

Video.java:

public class Video {

    private int videoId;
    private String videoType;
    private String language;
    private String date;
    public String videoUrl;
    private String videoTitle;

    public Video(JSONObject jsonObject) {
        setVideoId(jsonObject.optInt("videoid", 0));
        setVideoType(jsonObject.optString("video_type", null));
        setLanguage(jsonObject.optString("language", null));
        setDate(jsonObject.optString("date", null));
        if(getVideoType().equalsIgnoreCase("Youtube"))
          setVideoUrl(jsonObject.optString("video_url", null));
        else
          setVideoUrl(jsonObject.optString("video_file", null));

        setVideoTitle(jsonObject.optString("video_title", null));
    }

    public int getVideoId() {
        return videoId;
    }

    public void setVideoId(int videoId) {
        this.videoId = videoId;
    }

    public String getVideoType() {
        return videoType;
    }

    public void setVideoType(String videoType) {
        this.videoType = videoType;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getVideoUrl() {
        return videoUrl;
    }

    public void setVideoUrl(String videoUrl) {
        this.videoUrl = videoUrl;
    }

    public String getVideoTitle() {
        return videoTitle;
    }

    public void setVideoTitle(String videoTitle) {
        this.videoTitle = videoTitle;
    }



}

堆栈跟踪:

D/AndroidRuntime(973): Shutting down VM
W/dalvikvm(973): threadid=1: thread exiting with uncaught exception (group=0xb3b0fba8)
E/AndroidRuntime(973): FATAL EXCEPTION: main
E/AndroidRuntime(973): Process: com.gems.android, PID: 973
E/AndroidRuntime(973): java.lang.NullPointerException
E/AndroidRuntime(973):  at com.sit.gems.frgment.HomeBaseFragment.onMoreFragmentOptionSelected(HomeBaseFragment.java:344)
  • 我在 HomeBaseFragment.java 中提到了第344行。我是 花了很多时间来解决这些问题。
  • 但我无法找到它。如果有人知道如何解决这些问题 错误类型。
  • 欢迎您回答。谢谢!

1 个答案:

答案 0 :(得分:1)

HomeBaseFragment.GetLiveStreamVideoTask.doFinish()上,您的appData.setLiveStreamVideo可能未被调用,因此getLiveStreamVideo()可能会返回可能导致NPE的空值

if(videos.size()>0){
    Video video=videos.get(0);
    appData.setLiveStreamVideo(video);
}

如果用户在加载完成之前尝试访问此代码,也可以为null。