0

For some reason, when I click on the Toolbar(toolbar) and Float button(button) in my app, the OnClickListener () method crashes the snippet and app

Although the ImageButton(OnOff) handler runs and does not crash the fragment

Fragment

public class ZnonkiFragment extends Fragment {
    private SharedPreferences settings;
    private ImageButton OnOff;
    private ViewPager viewPager;
    private DrawerLayout drawerLayout;
    private MainActivity.PagerAdapter pagerAdapter;
    private FloatingActionButton button;
    final Context context = getActivity();
    private androidx.appcompat.widget.Toolbar toolbar;
    private TabLayout tabLayout;
    private String ZvonOne, ZvonTwo;
    private List<Fragment> list = new ArrayList<>();
    private String url;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_znonki, container,
       toolbar =  view.findViewById(R.id.toolbar);
       toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.menu));
       toolbar.setNavigationOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Toast.makeText(context,"lel",Toast.LENGTH_LONG).show();
           }
       });
        //...

       addListenerOnButton(view);
        return view;
    }

    public boolean checkString(String string) {
        try {
            Integer.parseInt(string);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public void addListenerOnButton (final View viewOne){
        OnOff = viewOne.findViewById(R.id.onOff);
        button =  viewOne.findViewById(R.id.floatingActionButton);
        OnOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //...
        });
        button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View view) {
                 //...
                });
        button.setOnClickListener(new View.OnClickListener()  {
                    @Override
                    public void onClick(View view) {
                         //...
                      });
    }


}

XML

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".ZnonkiFragment">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:title="Звонки"
        app:titleTextColor="#FFFFFF" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_margin="16dp"
        android:clickable="true"
        android:focusable="true"
        app:backgroundTint="@color/colorAccent"
        app:backgroundTintMode="src_atop"
        app:srcCompat="@drawable/kek" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:isScrollContainer="true"
        app:tabIndicatorColor="@android:color/white"
        app:tabIndicatorHeight="6dp"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@android:color/white"
        app:tabTextColor="#E6E6FA">

    </com.google.android.material.tabs.TabLayout>

    <ImageButton
        android:layout_margin="16dp"
        android:id="@+id/onOff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:background="@null"
        app:srcCompat="@drawable/on" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/rager"
        android:layout_width="match_parent"
        android:layout_height="557dp"
        android:layout_marginTop="105dp"
/>

</FrameLayout>

Although this code worked in the main activiti

I don't know why but there are no errors in debug mode

MSpeed
  • 8,153
  • 7
  • 49
  • 61

3 Answers3

0

I think main cause of this issue is

final Context context = getActivity();

which is used in

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Toast.makeText(context,"lel",Toast.LENGTH_LONG).show();
           }
       });

please note the getActivity() method returns the current activity with which this fragment is attached. and you are calling while the fragment object is creating before it is attached to activity.

you can change the above code to :

Context context;

and override the method as

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

Hope this answers your question.

Danial clarc
  • 724
  • 1
  • 7
  • 25
Kundan Singh
  • 91
  • 1
  • 6
0

What Kundan has suggested is correct but the fix is much easier.

You don't need this:

final Context context = getActivity();

If you need to gain access to the context in a Fragment you can call requireContext() if you need access to the Activity you can call requireActivity()

So your toast message can become:

Toast.makeText(requireContext(),"lel",Toast.LENGTH_LONG).show();
Scott Cooper
  • 2,779
  • 2
  • 23
  • 29
0

The solution is simple

In your fragment class file, dont create custom function for calling click events rather you can use the android's defaul method by simply implementing them in your class file and then override it. Thats makes the code more simpler and reusable in future.

public class ZnonkiFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
    private SharedPreferences settings;
    private ImageButton OnOff;
    private ViewPager viewPager;
    private DrawerLayout drawerLayout;
    private FloatingActionButton button;
    final Context context = getActivity();
    private TabLayout tabLayout;
    private String ZvonOne, ZvonTwo;
    private List<Fragment> list = new ArrayList<>();
    private String url;
    private Toolbar mToolbar;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_znonki, container, false);
        mToolbar = view.findViewById(R.id.toolbar);
        mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_launcher_background));
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "lel", Toast.LENGTH_LONG).show();
            }
        });
        //...

        OnOff = view.findViewById(R.id.onOff);
        OnOff.setOnClickListener(this);
        OnOff.setOnLongClickListener(this);

        button = view.findViewById(R.id.floatingActionButton);

        return view;
    }

    public boolean checkString(String string) {
        try {
            Integer.parseInt(string);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.onOff:
                //call your onclick function here...
                break;
            case R.id.floatingActionButton:
                //call your onclick function here...
                break;
        }
    }

    @Override
    public boolean onLongClick(View view) {
        switch (view.getId()) {
            case R.id.floatingActionButton:
                //call your long click function here...
                break;
        }
        return false;
    }
}

I have left comments on particular Loc where you can add your code and check it. And the toolbar was crashing due to improper importing of the libraries. If you havent used the androidx library into your gradle file then you can go with simple toolbar which is of "import android.support.v7.widget.Toolbar". This will surely stop your onclick crash on toolbar. If there is any issue, just let me know. Thank you.