Home > Mobile >  Why is second floating action button not working?
Why is second floating action button not working?

Time:10-30

I'm a beginner in android app making and I'm trying to do an app for a project. I found this tutorial and I'm currently trying to put to apps together in android studio. Both are reminders apps, however the second one (the food one), the FAB is not working it register the touch but when it does it says APP keeps stopping. If anybody can help me I'll appreciated.

First Reminder .java

public class MedicineActivity extends AppCompatActivity {

    @BindView(R.id.compactcalendar_view)
    CompactCalendarView mCompactCalendarView;

    @BindView(R.id.date_picker_text_view)
    TextView datePickerTextView;

    @BindView(R.id.date_picker_button)
    RelativeLayout datePickerButton;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.collapsingToolbarLayout)
    CollapsingToolbarLayout collapsingToolbarLayout;

    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;

    @BindView(R.id.contentFrame)
    FrameLayout contentFrame;

    @BindView(R.id.fab_add_task)
    FloatingActionButton fabAddTask;

   @BindView(R.id.coordinatorLayout)
    CoordinatorLayout coordinatorLayout;

    @BindView(R.id.date_picker_arrow)
    ImageView arrow;

    private MedicinePresenter presenter;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd", /*Locale.getDefault()*/Locale.ENGLISH);

    private boolean isExpanded = false;

    public ImageButton imageButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medicine);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);

        imageButton = (ImageButton) findViewById(R.id.image2button);

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent= new Intent(MedicineActivity.this,dashboard_screen.class);
                startActivity(intent);
            }
        });



        mCompactCalendarView.setLocale(TimeZone.getDefault(), /*Locale.getDefault()*/Locale.ENGLISH);

        mCompactCalendarView.setShouldDrawDaysHeader(true);

        mCompactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() {
            @Override
            public void onDayClick(Date dateClicked) {
                setSubtitle(dateFormat.format(dateClicked));
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dateClicked);

                int day = calendar.get(Calendar.DAY_OF_WEEK);

                if (isExpanded) {
                    ViewCompat.animate(arrow).rotation(0).start();
                } else {
                    ViewCompat.animate(arrow).rotation(180).start();
                }
                isExpanded = !isExpanded;
                appBarLayout.setExpanded(isExpanded, true);
                presenter.reload(day);
            }

            @Override
            public void onMonthScroll(Date firstDayOfNewMonth) {
                setSubtitle(dateFormat.format(firstDayOfNewMonth));
            }
        });
        setCurrentDate(new Date());
        MedicineFragment medicineFragment = (MedicineFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
        if (medicineFragment == null) {
            medicineFragment = MedicineFragment.newInstance();
            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), medicineFragment, R.id.contentFrame);
        }

        //Create MedicinePresenter
        presenter = new MedicinePresenter(Injection.provideMedicineRepository(MedicineActivity.this), medicineFragment);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.medicine_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_stats) {
            Intent intent = new Intent(this, MonthlyReportActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    public void setCurrentDate(Date date) {
        setSubtitle(dateFormat.format(date));
        mCompactCalendarView.setCurrentDate(date);
    }

    public void setSubtitle(String subtitle) {
        datePickerTextView.setText(subtitle);
    }

    @OnClick(R.id.date_picker_button)
    void onDatePickerButtonClicked() {
        if (isExpanded) {
            ViewCompat.animate(arrow).rotation(0).start();
        } else {
            ViewCompat.animate(arrow).rotation(180).start();
        }

        isExpanded = !isExpanded;
        appBarLayout.setExpanded(isExpanded, true);
    }
}

First Reminder XML File

   <?xml version="1.0" encoding="utf-8"?>
   <androidx.coordinatorlayout.widget.CoordinatorLayout  xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:id="@ id/coordinatorLayout"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@ id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:expanded="false"
        app:layout_behavior="com.gautam.medicinetime.utils.ScrollingCalendarBehavior">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@ id/collapsingToolbarLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:minHeight="?attr/actionBarSize"
            app:contentScrim="?attr/colorPrimary"
            app:titleEnabled="false"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:statusBarScrim="?attr/colorPrimaryDark">

            <LinearLayout
                android:id="@ id/compactcalendar_view_container"
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:paddingTop="?attr/actionBarSize"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="1.0">

                <com.github.sundeepk.compactcalendarview.CompactCalendarView
                    android:id="@ id/compactcalendar_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingLeft="10dp"
                    android:paddingRight="10dp"
                    app:compactCalendarBackgroundColor="?attr/colorPrimary"
                    app:compactCalendarCurrentDayBackgroundColor="#FFC107"
                    app:compactCalendarCurrentSelectedDayBackgroundColor="#BBDEFB"
                    app:compactCalendarTextColor="#fff"
                    app:compactCalendarTextSize="12sp" />
            </LinearLayout>

            <androidx.appcompat.widget.Toolbar
                android:id="@ id/toolbar"
                style="@style/ToolbarStyle"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay">

                <RelativeLayout
                    android:id="@ id/date_picker_button"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="?android:selectableItemBackground"
                    android:gravity="center_vertical"
                    android:clickable="true"
                    android:focusable="true"
                    android:orientation="vertical">

                    <TextView
                        android:id="@ id/date_picker_text_view"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:ellipsize="end"
                        android:maxLines="1"
                        android:textStyle="bold"
                        android:textSize="18sp"
                        android:textColor="@android:color/white" />

                    <ImageView
                        android:id="@ id/date_picker_arrow"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@id/date_picker_text_view"
                        android:layout_toRightOf="@id/date_picker_text_view"
                        app:srcCompat="@drawable/ic_arrow_drop_down"
                        tools:ignore="ContentDescription,RtlHardcoded" />

                </RelativeLayout>
            </androidx.appcompat.widget.Toolbar>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <RelativeLayout
        android:id="@ id/relativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/design_default_color_background">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageButton
                android:id="@ id/image2button"
                android:layout_width="48dp"
                android:layout_height="50dp"
                android:background="@drawable/roundbutton"
                android:src="@drawable/menu_icon"
                android:text="Button"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.046"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.976" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </RelativeLayout>


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@ id/fab_add_task"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/sixteen_dp"
        app:fabSize="normal"
        app:layout_anchor="@ id/relativeLayout2"
        app:layout_anchorGravity="end|bottom"
        app:srcCompat="@drawable/ic_add" />

    <FrameLayout
        android:id="@ id/contentFrame"
        android:layout_width="match_parent"
        android:layout_height="674dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Second Remider .java

public class FoodActivity extends AppCompatActivity {

    FloatingActionButton mCreateRem;
    RecyclerView mRecyclerview;
    ArrayList<Model> dataholder = new ArrayList<Model>();
    //Array list to add reminders and display in recyclerview
    myAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food);

        mRecyclerview = (RecyclerView) findViewById(R.id.recyclerView_food);
        mRecyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        mCreateRem = (FloatingActionButton) findViewById(R.id.create_reminder);
        //Floating action button to change activity
        mCreateRem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), FoodAddReminder.class);
                startActivity(intent);
                //Starts the new activity to add Reminders
            }
        });

        Cursor cursor = new dbManager(getApplicationContext()).readallreminders();
        //Cursor To Load data From the database
        while (cursor.moveToNext()) {
            Model model = new Model (cursor.getString(1), cursor.getString(2), cursor.getString(3));
            dataholder.add(model);
        }

        adapter = new myAdapter(dataholder);
        mRecyclerview.setAdapter(adapter);
        //Binds the adapter with recyclerview

    }

    @Override
    public void onBackPressed() {
        finish();
        //Makes the user to exit from the app
        super.onBackPressed();

    }
}

Second Reminder XML file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FoodActivity"
    android:id="@ id/Food_Container">

    <androidx.appcompat.widget.Toolbar
        android:id="@ id/FoodToolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/yellow_light"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:title="What's on you firdge?" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@ id/recyclerView_food"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        android:visibility="invisible"
        app:layout_constraintBaseline_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/FoodToolbar"
        tools:layout_editor_absoluteX="-4dp" />

         <TextView
            android:id="@ id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="No food reminder added\n   Add now"
            android:textAlignment="center"
            android:textSize="18dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@ id/recyclerView_food"
            app:layout_constraintStart_toStartOf="@ id/recyclerView_food"
            app:layout_constraintTop_toBottomOf="@ id/FoodToolbar"
            app:layout_constraintVertical_bias="0.523"
            android:visibility="gone"
            />

        <ImageView
            android:layout_width="379dp"
            android:layout_height="46dp"
            android:src="@drawable/food_icon"
            app:layout_constraintBottom_toTopOf="@ id/textView4"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@ id/FoodToolbar"
            app:layout_constraintVertical_bias="0.966"
            android:visibility="gone"
            />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@ id/create_reminder"
        android:layout_width="65dp"
        android:layout_height="56dp"
        android:src="@drawable/ic_baseline_add_24"
        app:backgroundTint="@color/yellow_light"
        app:layout_anchorGravity="right|bottom"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.928"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.961" />

</androidx.constraintlayout.widget.ConstraintLayout>

CodePudding user response:

You can not use applicationcontext in here, but if you want you need to add flags to the intent. So easier method for you to use "this" instead:

        mCreateRem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(this, FoodAddReminder.class);
                startActivity(intent);
                //Starts the new activity to add Reminders
            }
        });

CodePudding user response:

We can only "guess" why, but "not working" and "app keeps stopping" could mean a lot of things and you didn't provide any Log information or an Exception stacktrace. Its also hard to guess what FoodAddReminder.class is, if its an activity, make sure its declared in your AndroidManifest.xml

mCreateRem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(this, FoodAddReminder.class); // <-- is this an activity?
                startActivity(intent);
                //Starts the new activity to add Reminders
            }
        });

Check your AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.me.my.project">
    <application >
        <activity
            android:name=".FoodAddReminder"/>  <!-- here -->
    </application>
</manifest>

If that is not the issue, I suspect that using getApplicationContext(), you're having this crashlog

AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

You should then tell the system you want to start a new task,

public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), FoodAddReminder.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
 }

But I would suggest not doing it, instead use your FoodActivity as your calling activity to FoodReminder in this case, and pay attention to this, it should be prefixed with FoodActivity otherwise you will refer to your enclosing anonymous OnClickListener scope.

@Override
public void onClick(View v) {
       Intent intent = new Intent(FoodActivity.this, FoodAddReminder.class);
       startActivity(intent);
}

If none of these solved your "not working" issue, please provide a more specific Log information and reduce your code to something that is copy-and-paste-able.

  • Related