在Fragments的帮助下开发Gems应用程序时,运行时发生了logcat错误。
logcat的:
E/AndroidRuntime(667): FATAL EXCEPTION: main
E/AndroidRuntime(667): java.lang.NullPointerException
E/AndroidRuntime(667): at com.sit.gems.frgment.HomeBaseFragment.onMoreFragmentOptionSelected(HomeBaseFragment.java:345)
E/AndroidRuntime(667): at com.sit.gems.activity.HomeActivity.onMoreFragmentOptionSelected(HomeActivity.java:80)
E/AndroidRuntime(667): at com.sit.gems.frgment.MoreFragment$1.onItemClick(MoreFragment.java:44)
E/AndroidRuntime(667): at android.widget.AdapterView.performItemClick(AdapterView.java:292)
E/AndroidRuntime(667): at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
E/AndroidRuntime(667): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
E/AndroidRuntime(667): at android.widget.AbsListView$1.run(AbsListView.java:3168)
E/AndroidRuntime(667): at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime(667): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(667): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(667): at android.app.ActivityThread.main(ActivityThread.java:4340)
E/AndroidRuntime(667): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(667): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(667): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime(667): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime(667): at dalvik.system.NativeStart.main(Native Method)
HomeBaseFragment.java:
package com.sit.gems.frgment;
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) {
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());
((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;
}
} 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) {
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();
transaction = getActivity().getSupportFragmentManager()
.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("live","LIVE STREAMING");
bundle.putString("url", appData.getLiveStreamVideo().getVideoUrl()); //345th Line
liveStreamFragment.setArguments(bundle);
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;
}
}
}
AppData.java:
package com.sit.gems.app;
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 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.DEFAULT;
typefaceHindi = Typeface.createFromAsset(mContext.getAssets(),
"fonts/vigyapti.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();
}
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;
}
}
BaseFragment.java:
package com.sit.gems.app;
public class BaseFragment extends Fragment {
private Activity activity;
protected AppData appData;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appData = ((GemsApplication) activity.getApplication()).getAppData();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
HomeActivity.java:
package com.sit.gems.activity;
public class HomeActivity extends BaseActivity implements
VideoFragment.OnVideoSelectedListener,
AudioFragment.OnAudioSelectedListener,
BlogFragment.OnBlogSelectedListener,
MoreFragment.OnMoreFragmentOptionSelectedListener,
AnnouncenentFragment.OnAnnouncementSelectedListener,
ProductFragment.OnProductSelectedListener,
GalleryFragment.OnGalItemSelectedListener,
ProductDetailFragment.OnInquiryListener,
CategoryFragment.OnCategorySelectedListener,
MagzineFragment.OnMagzineSelectedListener{
private HomeBaseFragment fragment;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.base_fragment);
AppPreferences.setAppPreferences(getApplicationContext());
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
fragment = new HomeBaseFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment).commit();
}
@Override
public void OnAudioSelected(Audio audio) {
fragment.OnAudioSelected(audio);
}
@Override
public void OnBlogSelected(Blog blog,String lang) {
fragment.OnBlogSelected(blog,lang);
}
@Override
protected void onDestroy() {
super.onDestroy();
appData.clearData();
}
@Override
public void OnVideoSelected(Video video) {
fragment.OnVideoSelected(video);
}
@Override
public void onMoreFragmentOptionSelected(int option) {
fragment.onMoreFragmentOptionSelected(option); //80th Line
}
@Override
public void OnAnnouncementSelected(Announcement announcement) {
fragment.onAnnouncementSelected(announcement);
}
@Override
public void OnProductSelected(Product product) {
fragment.onProductSelected(product);
}
@Override
public void OnGalItemSelected(String pos,String name) {
fragment.onGalItemSelected(pos,name);
}
@Override
public void OnInquirytSelected(Product product) {
fragment.onInquirytSelected(product);
}
@Override
public void OncategorySelected(String id,String name) {
fragment.oncategorySelected(id,name);
}
@Override
public void OnMagzineSelected(Magzine magzine) {
fragment.onMagzineSelected(magzine);
}
}
BaseActivity.java:
package com.sit.gems.app;
public class BaseActivity extends FragmentActivity {
protected AppData appData;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
appData=((GemsApplication) getApplication()).getAppData();
}
public void onDestroyView() {
}
}
MoreFragment.java:
package com.sit.gems.frgment;
public class MoreFragment extends BaseFragment {
OnMoreFragmentOptionSelectedListener mCallBack;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.quickaction, null);
List<String> options=new ArrayList<String>();
options.add("Announcements");
options.add("Magazines");
options.add("Products");
options.add("Live Streaming");
options.add("Prayer Request");
options.add("Settings");
ListView listView =(ListView) view.findViewById(R.id.tracks);
listView.setAdapter(new MoreAdapter(getActivity(), 0, options));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
mCallBack.onMoreFragmentOptionSelected(arg2+1); //44th Line
}
});
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallBack = (OnMoreFragmentOptionSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
public interface OnMoreFragmentOptionSelectedListener{
public void onMoreFragmentOptionSelected(int option);
}
}
输出:
答案 0 :(得分:0)
检查appData
对象并确保其已初始化。这似乎是null
或返回null
网址字符串。
答案 1 :(得分:0)
查看导致问题的代码行,看起来你没有在任何地方初始化appData实例,这可能是为什么?
如果这不是问题,您可以通过替换此问题来缩小问题范围或暂时修补问题:
bundle.putString("url", appData.getLiveStreamVideo().getVideoUrl());
有了这个:
try {
Log.d("LiveStreamVideo", "Screen Width: " + appData.getScreenWidth());
Log.d("LiveStreamVideo", "Video URL: " + getLiveStreamVideo().getVideoUrl());
bundle.putString("url", appData.getLiveStreamVideo().getVideoUrl());
} catch (Exception e) {
e.printStackTrace();
}
如果在期望看到第一个Log输出之前输出堆栈跟踪,则知道appData为null。如果它在第二个日志请求中失败,那么getVideoUrl()就是问题。
可能是getVideoUrl()返回null,因为我无法确定它是否存在。也许为这个变量设置一个默认值是为了确保:
private videoUrl = "";