Search code examples
javaandroidandroid-fragmentsonclicklistenerandroid-button

Submit Button from another layout


I'm trying to insert a data into database(firebase) by using a simple submit button. My problem is I created my submission form(including button) in another layout and the java code for the database insertion is in MainActivity.

How can I call that submit button to my MainAcitvity(java)? Ive included my Layout XML code and java code and MainActivity java code.

package com.example.mainmenu;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.google.android.material.navigation.NavigationView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;

    EditText datefill;
    EditText roomanamefill;
    Button submitbutton;

    DatabaseReference bookingdb;

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

//        // Write a message to the database
//        FirebaseDatabase database = FirebaseDatabase.getInstance();
//        DatabaseReference myRef = database.getReference("message");
//        myRef.setValue("Hello, World!");

        datefill = findViewById(R.id.datefill);
        roomanamefill = findViewById(R.id.roomnamefill);
        submitbutton = findViewById(R.id.submitbutton);

        bookingdb = FirebaseDatabase.getInstance().getReference().child("Booking");

        submitbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            insertbookingdata();
            }

        });

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        if(savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new DashboardFragment()).commit();
            navigationView.setCheckedItem(R.id.dashboard);
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
                case R.id.dashboard:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new DashboardFragment()).commit();
                break;
                case R.id.newbooking:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new NewBookingFragment()).commit();
                break;

                case R.id.logout:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new LogOutFragment()).commit();
                break;

        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

private void insertbookingdata(){
        String date = datefill.getText().toString();
        String roomname = roomanamefill.getText().toString();

        Booking booking = new Booking(date,roomname);

        bookingdb.push().setValue(booking);
    Toast.makeText(MainActivity.this,"Booking Success",Toast.LENGTH_SHORT).show();


}

}
package com.example.mainmenu;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


public class NewBookingFragment extends Fragment{



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_newbooking,container,false);

    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/backg">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="99dp"
        android:layout_marginBottom="625dp"
        android:text="BOOKING FORM"
        android:textColor="@color/black"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="27dp"
        android:layout_marginBottom="558dp"
        android:fontFamily="sans-serif-black"
        android:text="Date                  :"
        android:textColor="@color/black"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/roomname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="27dp"
        android:layout_marginBottom="505dp"
        android:fontFamily="sans-serif-black"
        android:text="Room Number :"
        android:textColor="@color/black"
        android:textSize="18sp" />

    <EditText
        android:id="@+id/datefill"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="48dp"
        android:layout_marginBottom="545dp"
        android:ems="10"
        android:hint="(Day/Month/Year)"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/roomnamefill"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="48dp"
        android:layout_marginBottom="494dp"
        android:ems="10"
        android:hint="(BK or DK only)"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/submitbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="158dp"
        android:layout_marginBottom="421dp"
        android:text="SUBMIT"
        app:iconTint="@color/purple_500" />


</RelativeLayout>


Solution

  • You should inflate & add the clickListener in the fragment itself, and if you want to run some code from the activity , you can use requireActivity().

    Fragment:

    public class NewBookingFragment extends Fragment{
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_newbooking,container,false);
            
            Button submitButton = view.findViewById(R.id.submitbutton);
            
            submitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((MainActivity) requireActivity()).insertbookingdata();
                }
    
            });
            
            return view;
    
        }
    }
    

    And you should remove the relevant code from the activity.