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)
Related
I have multiple buttons in my app and I would like to have a single click listener for all buttons in R.layout.fragment_general. This is what I have tried:
View view = inflater.inflate(R.layout.fragment_general, container, false);
#SuppressLint("ResourceType") ViewGroup group = (ViewGroup) view.findViewById(R.layout.fragment_general);
View v;
for(int i = 0; i < group.getChildCount(); i++) {
v = group.getChildAt(i);
if(v instanceof Button) {
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("A button has been clicked");
}
});
}
}
My app will crash and I get the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
android.view.ViewGroup.getChildCount()' on a null object reference
How should it be done correctly?
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.ViewGroup.getChildCount()' on a null object reference
It means, that your group is null. That happened brcause of this
#SuppressLint("ResourceType") ViewGroup group = (ViewGroup) view.findViewById(R.layout.fragment_general);
You should write yours ViewGroups id in findViewbyId(), but not the fragments layout name.
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 need to call a method in which I parse the JSON objects and set the values I sets values in TextFields and button values, I created fragments but after creating the fragments how will I change the text field values
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
//Switch to different layout accordingly
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1: {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
break;
}
case 2: {
rootView = inflater.inflate(R.layout.fragment_receipt, container, false);
break;
}
case 3: {
rootView = inflater.inflate(R.layout.fragment_totals, container, false);
break;
}
case 4: {
rootView = inflater.inflate(R.layout.fragment_keyboard, container, false);
break;
}
case 5: {
rootView = inflater.inflate(R.layout.fragment_keylock, container, false);
break;
}
}
return rootView;
}
}
I tried to call the method in onStart but onStart method is been called first before the onCreateView and hence I get null pointer exception when I am assigning the value :
#Override
public void onStart() {
super.onStart();
parseJsonResponse(response_message);
}
In the parseJsonResponse() method, I sets the value
String UIFooter = ResponseHeaderObject.getString("FOOTER");
//Set Header Display
headerTextView =(TextView) findViewById(R.id.headerTextView);
headerTextView.setText(UIHeader);
here is the error from logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.mpos.kits.smartpos.PosMainActivity.parseJsonResponse(PosMainActivity.java:366)
Fragments have a function named: onViewCreated which called after your view was created
Yes, that method exists: onViewCreated. however, if you want to assign a text to the TextView outside the method on which it has been created, you have to declare the TextView as a member property (outside any method), to allow its use by all class methods. Otherwise, within a fragment, it will be difficult to manipulate it.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.mpos.kits.smartpos.PosMainActivity.parseJsonResponse(PosMainActivity.java:366)
You are getting this error because this headerTextView =(TextView) findViewById(R.id.headerTextView); returns null in your fragment unless it's referred to a root view like in the onCreateView method. this way (TextView) rootView.findViewById(R.id.section_label);
If you want to override onViewCreated method, do it this way:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//your code
}
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
saveInstanceState() doesn't work as expected.
I'm trying to read the data so I don't have to do the query again when a user reselects the tab. The fragment is a tab in a actionbar. Everything works properly, I just can't get savedInstanceState to be anything else then NULL, anyone has any idea?
This is my code:
public class SpecsFragment extends Fragment {
private String mText;
private ArrayList<HashMap> result;
private Converter c;
private View fragView;
public SpecsFragment() {
mText = "specs";
c = new Converter();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragView = inflater.inflate(R.layout.product_info_fragment, container, false);
return fragView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState == null) {
Bundle args = getArguments();
int id = Integer.parseInt(args.getString("id"));
String query = "SELECT * FROM products WHERE id = " + id;
try {
ZoekQueryTask zoekQueryTask = new ZoekQueryTask(query);
result = zoekQueryTask.getResults();
}
catch (Exception e) {
Log.e("Afgevangen error", e.getMessage());
}
}
else {
result = new ArrayList();
result.add((c.BundleToHashMap(savedInstanceState)));
}
TextView text = (TextView) fragView.findViewById(R.id.textView1);
text.setText(mText);
text.append("\n\n");
text.append(result.get(0).get("ean").toString());
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState = c.HashmapToBundle(result.get(0));
}
}
Using
savedInstance.putAll(c.HashmapToBundle(result.get(0)));
Still does not work.
savedInstance.putBundle("results", c.HashmapToBundle(result.get(0)));
Doesn't work either, anyone have any idea?
I solved the problem by working around it, instead of trying to store savedInstanceState. I wrote functions to get and set a Bundle from the fragments parent activity, and then get the activity by using:
YourActivity parent = (YourActivity) this.getactivity();
And just call the function for getting and setting a bundle which you write yourself.
I solved the problem by working around it, instead of trying to store savedInstanceState. I wrote functions to get and set a Bundle from the fragments parent activity, and then get the activity by using:
YourActivity parent = (YourActivity) this.getactivity();
And just call the function for getting and setting a bundle which you write yourself
If your Fragment is defined in an XML layout, ensure that you have specified an android:id!