bundle in fragment is null [duplicate]

给你一囗甜甜゛ 提交于 2019-12-24 19:26:08

问题


I am trying to send data from MainActivity to SunFragment (the main fragment) as:

MainActivity public class MainActivity extends AppCompatActivity { private FusedLocationProviderClient mFusedLocationClient; private static FragmentManager fragmentManager;

//  protected Location mLastLocation;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mLastLocation;

private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fragmentManager = getSupportFragmentManager();//Get Fragment Manager

    //FloatingActionButton fab = findViewById(R.id.fab);
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    Bundle bundle = new Bundle();
    bundle.putDouble("loclat", 25.4358);
    bundle.putDouble("loclang",81.8463);
    Fragment SunFragment = new SunFragment();
    SunFragment.setArguments(bundle);
    fragmentManager.beginTransaction().replace(R.id.view_pager, new SunFragment()).commit();

SunFragment

public class SunFragment extends Fragment {

    List<SunSession> sunsList;
    Typeface sunfont;
    Double Dlat;
    Double Dlang;

    //to be called by the MainActivity
    public SunFragment() {
        // Required empty public constructor
    }


    private static final String KEY_LOCATION_NAME = "location_name";
    public String TAG ="Sunfragment";
    public String location;//="No location name found";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve location and camera position from saved instance state.
        if (savedInstanceState != null) {
            location = savedInstanceState.getCharSequence(KEY_LOCATION_NAME).toString();
            System.out.println("OnCreate location  "+location);
           // Dlat = getArguments().getDouble("loclat");
            //Dlang = getArguments().getDouble("loclang");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_sun, container, false);
        onSaveInstanceState(new Bundle());
        if (getArguments() != null){
            Dlat = getArguments().getDouble("loclat");
            Dlang = getArguments().getDouble("loclang");
        }
    Log.e("Lat", Double.toString(Dlat));

SectionPagerAdapter

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
    private final Context mContext;

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        //return PlaceholderFragment.newInstance(position + 1);
        switch (position) {
            case 0:
                return new SunFragment();
            //return PlaceholderFragment.newInstance(pos + 5);
            case 1:
                return PlaceholderFragment.newInstance(1);
            //return SecondFragment.newInstance();
            //return PlaceholderFragment.newInstance(pos + 1);
            default:
                return PlaceholderFragment.newInstance(2);
        }
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 3;
    }
}

which is giving error:

java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
        at com.example.phocast.ui.main.SunFragment.onCreateView(SunFragment.java:71)

I have checked this and this, which seems close, but unable to solve my problem. What I am doing wrong here?


回答1:


 mainActivity.java
 ============

  SquardFragment   
          squardFragment=SquardFragment.newInstance(matchId2,page,matchStatus);
       FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(R.id.container, squardFragment, mTag);
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    if (canAddtoBackStack) transaction.addToBackStack(mTag);
    transaction.commit();


  SquardFragment.java
  =================== 

   public static SquardFragment newInstance(String matchId,
        int page,String matchStatus)    {
    SquardFragment frag = new SquardFragment();
    Bundle argsBundle = new Bundle();
    argsBundle.putString("matchId", matchId);
    argsBundle.putInt("page", page);
    argsBundle.putString("matchStatus", matchStatus);
    frag.setArguments(argsBundle);
    return frag;
  }

  if (getArguments() != null) {
        matchId = getArguments().getString("matchId");
        page = getArguments().getInt("page", 0);
        matchStatus=getArguments().getString("matchStatus");
    }



回答2:


The problem is you pass a new instance of your SunFragment to fragmentManager.beginTransaction().replace() instead of using the instance you created with the arguments set.

Fragment SunFragment = new SunFragment();
SunFragment.setArguments(bundle);

//this line is the problem
fragmentManager.beginTransaction().replace(R.id.view_pager, new SunFragment()).commit(); 

//change it to this
fragmentManager.beginTransaction().replace(R.id.view_pager, SunFragment).commit(); 



回答3:


The problem is in this line,

fragmentManager.beginTransaction().replace(R.id.view_pager, new SunFragment()).commit();

you are giving a new object of Sunfragment each time

simply put sunFragment instead of new sunFragment.



来源:https://stackoverflow.com/questions/59188813/bundle-in-fragment-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!