Click listener for ALL buttons - java

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.

Related

I have added button to Fragment, now i am trying to register that button to Javafile of fragment, but its giving me error in java file

public class SlideshowFragment extends Fragment {
private FragmentSlideshowBinding binding;
public Button btn1,btn2;
#Override
public View onCreateView( LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
btn1=(Button) findViewById (R.id.button); // find view by id is giving error
(Cannot resolve method 'findViewById' in 'SlideshowFragment)
btn2=(Button) findViewById (R.id.button2);
SlideshowViewModel slideshowViewModel =
new ViewModelProvider(this).get(SlideshowViewModel.class);
binding = FragmentSlideshowBinding.inflate(inflater, container, false);
View root = binding.getRoot();
// final TextView textView = binding.button;
//slideshowViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
If you're using view binding you don't need to access your components with findViewById method. While using view binding, pressing dot (.) after calling your view binding reference will show you all available components in your layout. You can simply use:
btn1 = binding.button;
btn2 = binding.button2;
But if you still want to access your components with findViewById method you should use it with your root view reference:
btn1 = binding.getRoot().findViewById(R.id.button);
btn2 = binding.getRoot().findViewById(R.id.button2);

NullPointerException problem, can't add event

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)

Is there any method after creating the view of fragments?How to change Layout of tabs after creating fragments

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
}

Android view is null object reference inside fragment

i'm having a hard time with some code. I am using sliding tabs with 2 fragment. Inside one of my fragment i'm trying to get a LinearLayout and add some stuff in it but everytime i try to do getView().findViewByID() I got null object reference
I'm calling the function after the onCreateView() I tried making a variable of type View and putting the View that i inflate in the onCreateView in it but i keeps getting the same error. I also tried putting a if() before to check if view isnt null , but even with this , I get null object reference. Can someone help me ?
public class listAlarmFragment extends Fragment{
public View view = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle){
View v = inflater.inflate(R.layout.list_alarm,vg,false);
view = v;
return v;
}
public void showAlarm(Cursor c){
if(view != null) { //even with that check, I got a null pointer exception
LinearLayout baseList = (LinearLayout) view.findViewById(R.id.baseList); // NullPointerException: Attempt to invoke virtual method on a null object reference
}
}
}
Replacing view with getView() doesnt change anything.
This is how I'm calling the function from the Main Activity
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment c = adapter.getItem(0);
((listAlarmFragment)(c)).showAlarm(dbHelper.getAlarm()); // where I call the function
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I'm opening this fragment at the beggining when my app open. It crashs when im trying to switch to another fragment.
here is the stack trace :
04-02 18:41:54.615 31584-31584/al.demo.alarmmanagerdemo E/AndroidRuntime: FATAL EXCEPTION: main
Process: al.demo.alarmmanagerdemo, PID: 31584
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at al.demo.alarmmanagerdemo.fragment.listAlarmFragment.showAlarm(listAlarmFragment.java:83)
at al.demo.alarmmanagerdemo.MainActivity$1.onPageSelected(MainActivity.java:54)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1971)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:689)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:673)
at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2288)
at android.view.View.dispatchTouchEvent(View.java:10779)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2858)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2534)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:605)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1895)
at android.app.Activity.dispatchTouchEvent(Activity.java:3241)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:567)
at android.view.View.dispatchPointerEvent(View.java:11008)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5155)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5007)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4585)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4551)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4684)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4559)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4741)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4585)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4551)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4559)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7092)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7024)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6985)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7202)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:323)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:6776)
04-02 18:41:54.615 31584-31584/al.demo.alarmmanagerdemo E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1510)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1400)
I would do something like this,
public class listAlarmFragment extends Fragment{
//public View view = null; // no need
private LinearLayout baseList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle){
View v = inflater.inflate(R.layout.list_alarm,vg,false);
baseList = (LinearLayout) v.findViewById(R.id.baseList);
//view = v; no need
return v;
}
public void showAlarm(Cursor c){
if(baseList!=null){
//do something with your baseList
}
}
}
Also check R.id.baseList exists in the layout xml R.layout.list_alarm.
and it should be LinearLayout with
id=#+id/baseList

Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager

I am trying to implement RecyclerView in one of my custom alert dialogue. Its crashing with error called
Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
on this line
hsv_font_bartextview.setLayoutManager(layoutManager);
My function code of custom dialogue is like below
private void showGotoPageDialog() {
final Dialog mDialog = new Dialog(SettingsActivity.this);
mDialog.setContentView(R.layout.font_dialogue);
mDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayoutManager layoutManager
= new LinearLayoutManager(SettingsActivity.this, LinearLayoutManager.HORIZONTAL, false);
hsv_font_bartextview=(RecyclerView)findViewById(R.id.hsv_font_bartextview);
hsv_font_bartextview.setLayoutManager(layoutManager);
TextAdapterTextview textAdaptertextview = new TextAdapterTextview(SettingsActivity.this, Globle.getFontArray());
hsv_font_bartextview.setAdapter(textAdaptertextview);
textAdaptertextview.setOnClickLIstner(new OnTClickLIstner() {
#Override
public void onClick(View v, String image, int position) {
Toast.makeText(SettingsActivity.this,image,Toast.LENGTH_SHORT).show();
}
});
mDialog.show();
TextView dismiss = (TextView) mDialog.findViewById(R.id.dialog_dismiss);
dismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDialog.dismiss();
}
});
}
Let me know if someone can help me for solve my issue. Thanks
hsv_font_bartextview=(RecyclerView)findViewById(R.id.hsv_font_bartextview);
findViewById() returns null, because your activity does not have a widget with that ID. Your dialog might, but the dialog is not the activity. Call findViewById() on the dialog if that is where the hsv_font_bartextview is.

Categories