This question already has answers here:
How to pass values between Fragments
(18 answers)
Closed 5 years ago.
I know there are so many qustions regarding this , but none of them are solving my problem
I want to pass a string variable from one fragment to other, here is the code I did. but I am getting error (I will show the error)
from first fragment I did
Desc_1 ldf = new Desc_1 ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.frame, ldf).commit();
and incoming second fragment I did like
public class Desc_1 extends Fragment {
public Desc_1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_desc_1,container,false);
String value = getArguments().getString("YourKey");
Toast.makeText(getActivity(), value,
Toast.LENGTH_LONG).show();
return rootview;
}
}
I am getting error like
07-27 20:31:06.386 26816-26816/com.example.jaison.newsclient E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jaison.newsclient, PID: 26816
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at layout.Desc_1.onCreateView(Desc_1.java:34)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:725)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5769)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:861)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
try this :
Bundle bundle = getArguments();
if(bundle != null)
String value = bundle.getString("YourKey");
Just check if getArguments() is not null inside your fragment, and then inside the curly braces add your code
Example:
Bundle bundle_arguments = getArguments();
if(bundle_arguments != null) {
// your code
}
Please check this answer for passing values between fragments
https://stackoverflow.com/a/27626004/5065318
Related
I am trying to send two strings via a bundle to the next fragment but the app crashes even before I get to the first fragment.
I get this error in the second fragment:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.guessit, PID: 22360
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.example.android.guessit.GameFlow.FragmentAnswer1.onCreateView(FragmentAnswer1.java:125)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1696)
at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:299)
at androidx.fragment.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:259)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
at androidx.viewpager.widget.ViewPager.setCurrentItemInternal(ViewPager.java:669)
at androidx.viewpager.widget.ViewPager.setCurrentItemInternal(ViewPager.java:631)
at androidx.viewpager.widget.ViewPager.setCurrentItem(ViewPager.java:612)
at com.example.android.guessit.GameFlow.GameActivity.setViewPager(GameActivity.java:152)
at com.example.android.guessit.GameFlow.FragmentOneCategory$6.onClick(FragmentOneCategory.java:190)
at android.view.View.performClick(View.java:7352)
at android.view.View.performClickInternal(View.java:7318)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27800)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
I know that this means that the string value that I am trying to receive in the second fragment means that there is no value for that string but I don't know where the problem here is because the strings I am trying to send are not null.
This is the code I am using for the bundle in the first fragment (using this in onCreatView):
FragmentAnswer1 frag1 = new FragmentAnswer1();
Bundle args = new Bundle();
args.putString("question_1", question);
args.putString("answer_1", answer);
frag1.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.container, frag1).commit(); // there is a message that says that "beginTransaction" may produce a nullPointer
Here is the code to receive the strings in the second fragment (currently also in onCreateView)
question = getArguments().getString("question_1"); // error is in this line
answer = getArguments().getString("answer_1");
question1.setText(question);
rightAnswer.setText(answer);
I already tried to move the above code into the onStartmethod but I still get the same error. I also tried using this solution but its not working for me. I did not find any other solution or method on how to resolve the problem.
Please let me know if you need more informations. Any help is much appreciated!
I have now found the correct way to send data from one Fragment to another while having a ViewPager. We have to use a ViewModel.
First we have to create a ViewModel, in this case our goal is to send a String from Fragment 1 to Fragment 2. Here is the code for the ViewModel with Getter and Setter method for the String:
public class ViewModelString extends ViewModel {
private MutableLiveData<String> mString = new MutableLiveData<>();
public MutableLiveData<String> getmString() {
return mString;
}
public void setmString(MutableLiveData<String> mString) {
this.mString = mString;
}
}
Then in Fragment 1 from where we want to sent the string we need to first initialize the ViewModel in onCreate.
public class Fragment1 extends Fragment {
private ViewModelString viewModel;
public Fragment1() {
// Required empty public constructor
}
public static Fragment1 newInstance() {
return new Fragment1();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize ViewModel here
viewModel = ViewModelProviders.of(requireActivity()).get(ViewModelString.class);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
String hello = "hello";
viewModel.setmString(hello);
}
}
Then in the second Fragment we also have to first initialize the viewModel and then create an observer. Here we then take the String that is stored in the ViewModel and set a TextView to its value:
public class Fragment2 extends Fragment {
private ViewModelString viewModel;
public Fragment2() {
// Required empty public constructor
}
public static Fragment2 newInstance() {
return new Fragment2();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize ViewModel here
viewModel = ViewModelProviders.of(requireActivity()).get(ViewModelString.class);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
TextView textView = findViewById(R.id.yourTextViewId);
// Gets the string
viewModel.getmString().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
}
...
}
I hope this helps anyone! Please feel free to edit my post.
Use Bundle to send String:
//Put the value
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
YourFragmentName ldf = new YourFragmentName ();
ldf.setArguments(args);
//Inflate the fragment
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
In onCreateView of the new Fragment:
//Retrieve the value
Bundle bundle = this.getArguments();
if (bundle != null) {
String value = bundle.getString("YourKey");
}
Use a Bundle. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("Key", "value");
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, frag1).commit()
Bundle has put methods for lots of data types. See this
Then in your Fragment, retrieve the data in onCreate() method like:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getString(Key);
}
try this.
var fragment: MainFragment =MainFragment()
val args = Bundle()
args.putString("question_1", "My question")
args.putString("answer_1", "My answer")
fragment.setArguments(args)
fragmentManager.beginTransaction().add(R.id.fragment_content, fragment).commit()
I'm making a project where I added a calendar (compact calendar --> https://github.com/SundeepK/CompactCalendarView). I have two Fragments that are sending some data with bundle method between them. One has the calendar, the second one has the form to create an object.
The second one is just sending the new object to the First one and I want the first one adding the event in the calendar.
Before all, I checked and the object sent by the Second Fragment isn't null, and I can add an Event with the first Fragment in the OnCreateView method.
But when I try to call the addEvent method after I received the object, it says there is a problem and the object is null, but as I said, I checked and it isn't null.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
if (bundle != null) {
Cours c = bundle.getParcelable("CoursNew");
if (c != null) {
ajouterCours(c);
}
}
public Cours ajouterCours(Cours c) {
for (int i = 0; i < c.listeDate.size(); i++) {
Event e = new Event(c.getColor(), c.getDateLong(i),c.getNom());
System.out.println(e);
c.listeEvent.add(e);
compactCalendar.addEvent(e);
}
listeCours.add(c);
return c;
}
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.sundeepk.compactcalendarview.CompactCalendarView.addEvent(com.github.sundeepk.compactcalendarview.domain.Event, boolean)' on a null object reference
at com.example.wllh.Menu1.ajouterCours(Menu1.java:181)
at com.example.wllh.Menu1.onCreateView(Menu1.java:62)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
i have been creating an App that uses Fragments Mostly
here is how it is supposed to work, on the Home Fragment i click a button that takes me to another Fragment for filling information
on this fragment when I click a button a Dialog Fragment opens and I select a City Name then Submit, it dismisses the Dialog and is supposed to SetText on a TextView.
I use an interface that calls a method on the City Selection fragment in order to set the Text. here is some Code
Declaration for the EditText
EditText editText_From;
Setting finding the View
OnCreate
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_trip_date, container, false);
editText_From = view.findViewById(R.id.editText_From);
return view;
}
public void setSelectedCity(String city)
{
Log.i("<<269>>", "Setting Text on Edit Text <<269>>:" + city);
editText_From.setText(city);
}
This Method below is supposed to set text for the my EditText or TextView
public void setSelectedCity(String city)
{
Log.i("<<269>>", "Setting Text on Edit Text <<269>>:" + city);
selectedCityConfirmed = city;
editText_From.setText(city);
}
the App Crashes on EditText with the Following Error Message,
02-16 19:37:43.928 26582-26582/com.example.bob2609.busticketingapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bob2609.busticketingapp, PID: 26582
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference
at com.example.bob2609.busticketingapp.TripDateFragment.setSelectedCity(TripDateFragment.java:188)
at com.example.bob2609.busticketingapp.MainActivity.selectedCity(MainActivity.java:176)
at com.example.bob2609.busticketingapp.LocationSelector$1.onItemClick(LocationSelector.java:69)
at android.widget.AdapterView.performItemClick(AdapterView.java:313)
at android.widget.AbsListView.performItemClick(AbsListView.java:1201)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3195)
at android.widget.AbsListView$3.run(AbsListView.java:4138)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
The Interface Method on MainActivity
#Override
public void selectedCity(String city)
{
tripDateFragment.setSelectedCity(city);
}
Anyone knows a way around this?
Why are you declaring again Textview again in onCreate Method?
Declare outside the onCreate and Find the View using "findViewByID" inside on create.
I have written an app with OSMdroid using activities, but I am now trying to port it over to fragments instead (I'm new to fragments though). I am getting the error:
"java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setBuiltInZoomControls(boolean)' on a null object reference"
It seems that the MapView has not yet been initialised, am I initialising in the wrong place (OnCreateView)? According to the activity lifecycle, OnCreate is called before OnCreateView, so it would make sense that it is not recognised, but I am confused as to where then to put my code.
Code for my implementation of the fragment:
//inflating fragment layout
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
map = (MapView) view.findViewById(R.id.map);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));
setupMap();
}
//initializing map
private void setupMap() {
//adding zoom and touch controls
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
//getting current location using coarse/fine location so we can set centerpoint
currentLocation = getCurrentLocation();
... code continues ...
Error stack trace:
java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setBuiltInZoomControls(boolean)' on a null object reference
at skicompanion.skicompanion.MapFragment.setupMap(MapFragment.java:101)
at skicompanion.skicompanion.MapFragment.onCreate(MapFragment.java:86)
at android.app.Fragment.performCreate(Fragment.java:2214)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1153)
at android.app.BackStackRecord.run(BackStackRecord.java:800)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:487)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
In your posted code it doesn't look like you need to override onCreate method in your case. just move this code:
context = getActivity();
Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));
setupMap();
into the onCreateView method before the return call and should be ok.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to do a simple operation: click a button and show a custom DialogFragment, but I'm getting a NullPointExpection and I can't figure out why.
mAlertDialog.java:
public class mAlertDialog extends DialogFragment {
TextView title;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_invalid_time, container, false);
title = (TextView)view.findViewById(R.id.titleText);
return view;
}
public void setTheTitle(String title) {
this.title.setText(title);
}
}
Showing mAlertDialog:
mAlertDialog dialog = new mAlertDialog();
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));
dialog.show(fm, "InvalidTime");
Error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at m.inschool8.Objects.mAlertDialog.setTheTitle(mAlertDialog.java:20)
at m.inschool8.bSubjects.Fragment_Subjects$55.onClick(Fragment_Subjects.java:2654)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The title is still null when you are calling
mAlertDialog dialog = new mAlertDialog();
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));
so what you can do is
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_invalid_time, container, false);
title = (TextView)view.findViewById(R.id.titleText);
setTheTitle(getActivity().getString(R.string.invalidTimeTitle));
return view;
}
// call it
mAlertDialog dialog = new mAlertDialog();
dialog.show(fm, "InvalidTime");
Your title is null until the DialogFragment is shown causing onCreateView to kick-in. Hence change the order as below:
mAlertDialog dialog = new mAlertDialog();
dialog.show(fm, "InvalidTime");
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));