当我尝试在viewpager中进行反向滑动或反复滑动片段时,我得到空指针异常我没有得到这背后的真正问题。我的代码如下
public class Actionbar extends FragmentActivity{
private AuthDb authDb;
SampleFragmentPagerAdapter adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_bar);
authDb = new AuthDb(getApplicationContext());
ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
adapter=new SampleFragmentPagerAdapter();
viewPager.setAdapter(adapter);
if(Reference.SEARCH_COLOR.equalsIgnoreCase("true"))
{
setTitle("Search");
}
if(Reference.ACTIONBARTITLE){
Reference.ACTIONBARTITLE=false;
showIcon();
}
System.out.println("inside actionbarrrrr");
}
public void showIcon(){
try{
}
catch (NullPointerException e) {
e.printStackTrace();
}
catch(例外e){
e.printStackTrace();
}
}
public void setTitle(String title){
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
private String tabtitles[] = new String[] { "Feed", "Profile", "Search","Followers","Settings" };
final int PAGE_COUNT = 5;
public SampleFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public Fragment getItem(int position) {
Fragment frm = null;
System.out.println("scrolling position"+position+":count: "+PAGE_COUNT);
if(position==0){
frm=FeedFragment.create(position);
}
else if(position==1){
frm=ProfileFragment.create(position);
}
else if(position==2){
frm=SearchFragment.create(position);
}
else if(position==3){
frm=FollowersFragment.create(position,"me");
}
else if(position==4){
frm=SettingFragment.create(position);
}
else{
frm=FeedFragment.create(position);
}
return frm;
}
@Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return tabtitles[position];
}
}
}
我的片段之一
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("foloCount") && (mFolloCount != null)) {
mFolloCount.setText(intent.getStringExtra("foloCount"));
}
if (intent.hasExtra("msgCount") && (mMsgCount != null)) {
String User_Message_Count = intent.getStringExtra("msgCount");
if (User_Message_Count.equalsIgnoreCase("0")) {
mMsgCount.setVisibility(View.GONE);
} else {
mMsgCount.setVisibility(View.VISIBLE);
mMsgCount.setText(User_Message_Count);
}
}
if (intent.hasExtra("notiCount") && (mMsgCount != null)) {
String User_Notification_Count = intent
.getStringExtra("notiCount");
if (User_Notification_Count.equalsIgnoreCase("0")) {
mNotifyCount.setVisibility(View.GONE);
} else {
mNotifyCount.setVisibility(View.VISIBLE);
mNotifyCount.setText(User_Notification_Count);
}
}
}
};
private AlarmManager alarm;
private PendingIntent pIntent;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
if (!(activity instanceof FragmentActivity)) {
throw new IllegalStateException(((Object) this).getClass()
.getSimpleName()
+ " must be attached to a FragmentActivity.");
}
mHomeActivity = (FragmentActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnNavigateProfileListener ");
}
System.out.println("step 215");
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
if(Constants.DIALOGOPEN){
Constants.DIALOGOPEN=false;
Constants.dialog.dismiss();
}
}
else { }
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("inside profile fragment");
mViewUtils = new ViewUtils(getActivity().getApplicationContext());
dbHelper = new QsDatabaseHelper(getActivity().getApplicationContext());
context = getActivity();
mSportDb = new SportDb(getActivity().getApplicationContext());
mOptions = new DisplayImageOptions.Builder().cacheOnDisc(true)
.cacheInMemory(true)
.showImageForEmptyUri(R.drawable.noimagesmall)
.showImageOnFail(R.drawable.noimagesmall)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.considerExifParams(true).build();
mImageLoader = ImageLoader.getInstance();
ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(
getActivity()).defaultDisplayImageOptions(mOptions)
.threadPoolSize(3).build();
mImageLoader.init(imageLoaderConfiguration);
System.out.println("inside profile fragment");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container,
false);
mSavedInstanceState = savedInstanceState;
round_Image = null;
if (mSavedInstanceState == null) {
taken_image = null;
round_Image = null;
upload_image_hd = null;
}
mViewUtils = new ViewUtils(getActivity().getApplicationContext());
boolean checker=getActivity().getResources().getBoolean(R.bool.isTablet);
System.out.println("bbool"+checker);
if(checker)
Reference.DEVICEHEIGHT=600;
else
Reference.DEVICEHEIGHT=400;
// dummy call//
allSportsFromServer();
// updateCustomerSportsToServer();
mMessage = (LinearLayout) view.findViewById(R.id.tab2_wrapper);
mfollow = (LinearLayout) view.findViewById(R.id.tab1_wrapper);
mNotify = (LinearLayout) view.findViewById(R.id.tab3_wrapper);
mPhoto = (LinearLayout) view.findViewById(R.id.tab4_wrapper);
// mMenuIcon = (LinearLayout) view.findViewById(R.id.one_wrapper);
// mMenuSave = (LinearLayout) view.findViewById(R.id.two_wrapper);
// mMenuSaveButton = (ImageView) view.findViewById(R.id.my_image_save);
mUsername = mViewUtils.createTextView(view.findViewById(R.id.Username),
false);
tag = mViewUtils.createTextView(view.findViewById(R.id.usertag), false);
mAge = mViewUtils.createTextView(view.findViewById(R.id.age), false);
mPlace = mViewUtils
.createTextView(view.findViewById(R.id.place), false);
mLikeCount = mViewUtils.createTextView(
view.findViewById(R.id.like_count), false);
mFolloCount = mViewUtils.createTextView(
view.findViewById(R.id.follw_count), false);
mProgressBar = (ImageView) view.findViewById(R.id.progress_image);
dummyimage = (ImageView) view.findViewById(R.id.cover_image_dummy);
mViewUtils.createTextView(view.findViewById(R.id.photo_text), false);
mViewUtils.createTextView(view.findViewById(R.id.follw_text), false);
mUserProfile = (ImageView) view.findViewById(R.id.cover_image);
System.out.println("new user" + Reference.newuser);
if (!Reference.newuser) {
dummyimage.setVisibility(View.GONE);
mUserProfile.setVisibility(View.VISIBLE);
}
mEdit = (ImageView) view.findViewById(R.id.edit);
mGender = (ImageView) view.findViewById(R.id.gender);
grid = (GridView) view.findViewById(R.id.gridviewsports);
mlike = mViewUtils.createIconTextView(view.findViewById(R.id.like));
mMessage_icon = (ImageView) view.findViewById(R.id.tab_msg);
mNotify_icon = (ImageView) view.findViewById(R.id.tab_notify);
mMsgCount = mViewUtils.createTextView(
view.findViewById(R.id.msg_count), false);
mNotifyCount = mViewUtils.createTextView(
view.findViewById(R.id.notify_count), false);
mPhoto_icon = (ImageView) view.findViewById(R.id.tab_photo);
// mListview = (ListView) view.findViewById(R.id.list_all);
// mRecive = (ListView) view.findViewById(R.id.list_my);
firstload = true;
grid.setAdapter(new GridViewAdapter(getActivity()));
// Animation anim = AnimationUtils.loadAnimation(getActivity(),
// R.anim.grid_animation);
// grid.setAnimation(anim);
// anim.start();
mNotify_icon.setTag(R.string.type, "notifyicon");
mMessage_icon.setTag(R.string.type, "messageicon");
mPhoto_icon.setTag(R.string.type, "photoicon");
mMessage.setTag(R.string.type, "messageicon");
mNotify.setTag(R.string.type, "notifyicon");
mPhoto.setTag(R.string.type, "photoicon");
// mMenuSaveButton.setTag(R.string.type, "sportsSave");
mfollow.setTag(R.string.type, "followicon");
mMessage.setOnClickListener(this);
mNotify.setOnClickListener(this);
mPhoto.setOnClickListener(this);
mfollow.setOnClickListener(this);
mMessage_icon.setOnClickListener(this);
mNotify_icon.setOnClickListener(this);
mPhoto_icon.setOnClickListener(this);
// mMenuSaveButton.setOnClickListener(this);
System.out.println("step 336");
return view;
}
public static Context getinstance() {
return context;
}
@Override
public void onStart() {
super.onStart();
System.out.println("step 348");
try {
if (round_Image != null) {
mUserProfile.setImageBitmap(round_Image);
}
String User_Name = PreferencesUtils.getData(
Reference.USER_FIRSTNAME, getActivity()
.getApplicationContext());
String User_Age = PreferencesUtils.getData(Reference.USER_AGE,
getActivity().getApplicationContext());
String User_Country = PreferencesUtils.getData(
Reference.USER_LOCATION, getActivity()
.getApplicationContext());
String User_Gender = PreferencesUtils.getData(
Reference.USER_GENDER_G, getActivity()
.getApplicationContext());
String User_Follow = PreferencesUtils.getData(
Reference.SERVER_USER_FOLLOWER_COUNT, getActivity()
.getApplicationContext());
String User_Profile = PreferencesUtils.getData(
Reference.SERVER_USER_CROPPED_PHOTO_URL, getActivity()
.getApplicationContext());
String User_Message_Count = PreferencesUtils.getData(
Reference.SERVER_USER_MESSAGE_COUNT, getActivity()
.getApplicationContext());
String User_Notification_Count = PreferencesUtils.getData(
Reference.SERVER_USER_NOTIFICATION_COUNT, getActivity()
.getApplicationContext());
String User_Like_Count = PreferencesUtils.getData(
Reference.SERVER_USER_LIKE_COUNT, getActivity()
.getApplicationContext());
String User_Sports = PreferencesUtils.getData(
Reference.SERVER_USER_SELECT_SPORTS, getActivity()
.getApplicationContext());
String All_Sports = PreferencesUtils.getData(
Reference.SERVER_ALL_SPORTS, getActivity()
.getApplicationContext());
String tagline = PreferencesUtils.getData(Reference.TAGuser,
getActivity().getApplicationContext());
if (!User_Name.equals("") && !User_Age.equals("")
&& !User_Age.equals("") && !User_Country.equals("")
&& !User_Gender.equals("") && !User_Follow.equals("")
&& !User_Message_Count.equals("")
&& !User_Notification_Count.equals("")
&& !User_Like_Count.equals("") && !All_Sports.equals("")
&& !User_Sports.equals("") && !tagline.equals("")) {
String[] strArr = User_Name.split(" ");
StringBuffer res = new StringBuffer();
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
mUsername.setText((res.toString().trim()));
}
if (tagline.trim().length() > 0)
tag.setText(tagline);
else
tag.setText(R.string.DEFAULT_TAG);
mAge.setText(User_Age);
mPlace.setText(User_Country);
mFolloCount.setText(User_Follow);
if (User_Gender.equals("male")) {
mAge.setTextColor(getResources().getColor(
R.color.blue_light));
mGender.setImageDrawable(getResources().getDrawable(
R.drawable.ic_me_male));
} else {
mAge.setTextColor(getResources().getColor(R.color.pink));
mGender.setImageDrawable(getResources().getDrawable(
R.drawable.ic_switch_female));
}
// PROFILE PICTURE
System.out.println("user picc" + User_Profile);
if (User_Profile.equalsIgnoreCase("0")
|| User_Profile.trim().length() == 0) {
// mUserProfile.setImageDrawable(getResources().getDrawable(R.drawable.noimagesmall));
dummyimage.setVisibility(View.VISIBLE);
mUserProfile.setVisibility(View.GONE);
} else {
try {
String imageURL = User_Profile;
// Log.d("ENTERED_IN_THE_IMAGE_URL", "" + imageURL);
System.out.println("setting cropped line 413"
+ imageURL);
mImageLoader.displayImage(imageURL, mUserProfile,
mOptions);
mUserProfile.setVisibility(View.VISIBLE);
} catch (Exception e) {
// mUserProfile.setImageDrawable(getResources().getDrawable(R.drawable.noimagesmall));
dummyimage.setVisibility(View.VISIBLE);
mUserProfile.setVisibility(View.GONE);
}
}
// DisplayMetrics displaymetrics = new DisplayMetrics();
// getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
// final int windowheight = displaymetrics.heightPixels;
// final int windowwidth = displaymetrics.widthPixels;
//
// mUserProfile.setOnTouchListener(new View.OnTouchListener() {
//
// @Override
// public boolean onTouch(View v, MotionEvent event) {
// layoutParams = (RelativeLayout.LayoutParams)
// mUserProfile.getLayoutParams();
// switch(event.getAction())
// {
// case MotionEvent.ACTION_DOWN:
// break;
// case MotionEvent.ACTION_MOVE:
// int x_cord = (int)event.getRawX();
// int y_cord = (int)event.getRawY();
//
// if(x_cord>windowwidth){x_cord=windowwidth;}
// if(y_cord>windowheight){y_cord=windowheight;}
//
// layoutParams.leftMargin = x_cord -55;
// layoutParams.topMargin = y_cord - 75;
//
// mUserProfile.setLayoutParams(layoutParams);
// break;
// default:
// break;
// }
// return true;
// }
// });
// MESSAGE COUNT
if (User_Message_Count.equalsIgnoreCase("0")) {
mMsgCount.setVisibility(View.GONE);
} else {
mMsgCount.setVisibility(View.VISIBLE);
mMsgCount.setText(User_Message_Count);
}
// NOTIFICATION COUNT
if (User_Notification_Count.equalsIgnoreCase("0")) {
mNotifyCount.setVisibility(View.GONE);
} else {
mNotifyCount.setVisibility(View.VISIBLE);
mNotifyCount.setText(User_Notification_Count);
}
// LIKE COUNT
if (User_Like_Count.equalsIgnoreCase("0")) {
mLikeCount.setVisibility(View.GONE);
} else {
mLikeCount.setText(User_Like_Count);
}
// ALL SPORTS
try {
JSONArray jsonArray = new JSONArray(All_Sports);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String SportsName = obj
.getString(Reference.SPORTS_NAME);
// mListview_all.add(SportsName);
}
// mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
// USER SELECTED SPORTS
if (mSportDb.sportsExists()) {
mSportDb.emptyAuth();
}
try {
JSONArray jsonArray = new JSONArray(User_Sports);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
int SportsId = Integer.parseInt(obj
.getString(Reference.SPORTS_ID_RE));
String SportsName = obj
.getString(Reference.SPORTS_NAME);
mSportDb.createAuth(SportsId, SportsName, "1");
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
getProfileDetailServer();
}
} catch (Exception e) {
System.out.println("exxxceptionn");
}
if(Constants.DIALOGOPEN){
Constants.DIALOGOPEN=false;
Constants.dialog.dismiss();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("step 574");
mEdit.setTag(R.string.type, "edit");
mEdit.setOnClickListener(this);
taken_image = null;
round_Image = null;
upload_image_hd = null;
// String listCount = String.valueOf(mListview_all.size());
// mListview_all.clear();
// mListview_new.clear();
// mListview_my.clear();
initializeUIElements(); // ADD TO SPORTS FUNCTION
// setupDragDropStuff();
// setupDropStuff();
//
getProfileDetailServer();
}
@Override
public void onResume() {
super.onResume();
System.out.println("step 599");
try {
if (((PreferencesUtils.getData(Reference.USER_ID, getActivity()))
.length() > 0)
&& (PreferencesUtils.getData(Reference.USER_ID,
getActivity()) != null)) {
getActivity().registerReceiver(broadcastReceiver,
new IntentFilter(Reference.REFREASH_PROFILE));
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 3);
profileServiceIntent = new Intent(getActivity(),
ProfileService.class);
pIntent = PendingIntent
.getService(getActivity(), 0, profileServiceIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarm = (AlarmManager) getActivity().getSystemService(
Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), 7000, pIntent);
}
} catch (Exception e) {
System.out.println(e);
}
// mListview_all.clear();
// mListview_new.clear();
// mListview_my.clear();
Log.e("", "---> onResume");
initializeUIElements(); // ADD TO SPORTS FUNCTION
}
@Override
public void onPause() {
super.onPause();
try{
alarm.cancel(pIntent);
getActivity().stopService(profileServiceIntent);
getActivity().unregisterReceiver(broadcastReceiver);
}
catch(Exception e){
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
try{
getActivity().unregisterReceiver(broadcastReceiver);
alarm.cancel(pIntent);
getActivity().stopService(profileServiceIntent);
}
catch(Exception e){
System.out.println(e);
}
super.onDestroy();
}
@Override
public void onStop() {
// TODO Auto-generated method stub
try{
getActivity().unregisterReceiver(broadcastReceiver);
alarm.cancel(pIntent);
getActivity().stopService(profileServiceIntent);
}
catch(Exception e){
System.out.println(e);
}
super.onStop();
}
@Override
public void onClick(View v) {
String type = v.getTag(R.string.type).toString().trim();
try {
if (type.equalsIgnoreCase("edit")) {
mEdit.setVisibility(View.INVISIBLE);
onClickEdit();
}
if (type.equalsIgnoreCase("messageicon")) {
((FeedActivity) mHomeActivity).navigateToMessagePage();
}
if (type.equalsIgnoreCase("notifyicon")) {
((FeedActivity) mHomeActivity).navigateToNotificationPage();
}
if (type.equalsIgnoreCase("photoicon")) {
((FeedActivity) mHomeActivity).navigateToPhotoPage();
}
if (type.equalsIgnoreCase("sportsSave")) {
createUserSportsServer();
}
if (type.equalsIgnoreCase("followicon")) {
if (!mFolloCount.getText().toString().equals("0"))
((FeedActivity) mHomeActivity).navigateToFollowersPage(
"following", true);
}
} catch (NullPointerException ignored) {
}
catch (Exception e) {
}
}
}
我的xml
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:id="@+id/pager_headerr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/markerboxcolor"
android:layout_gravity="top"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#ffffff" />
我的错误日志如下
06-08 12:09:08.667: E/AndroidRuntime(17491): FATAL EXCEPTION: main
06-08 12:09:08.667: E/AndroidRuntime(17491): Process: com.sports.sportspartners, PID: 17491
06-08 12:09:08.667: E/AndroidRuntime(17491): java.lang.NullPointerException
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:708)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.support.v4.view.ViewPager$3.run(ViewPager.java:249)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.view.Choreographer.doCallbacks(Choreographer.java:591)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.view.Choreographer.doFrame(Choreographer.java:559)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.os.Handler.handleCallback(Handler.java:808)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.os.Handler.dispatchMessage(Handler.java:103)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.os.Looper.loop(Looper.java:193)
06-08 12:09:08.667: E/AndroidRuntime(17491): at android.app.ActivityThread.main(ActivityThread.java:5292)
06-08 12:09:08.667: E/AndroidRuntime(17491): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 12:09:08.667: E/AndroidRuntime(17491): at java.lang.reflect.Method.invoke(Method.java:515)
06-08 12:09:08.667: E/AndroidRuntime(17491): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
06-08 12:09:08.667: E/AndroidRuntime(17491): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
06-08 12:09:08.667: E/AndroidRuntime(17491): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
最后,我通过添加viewPager.setOffscreenPageLimit(3);