Search code examples
javaandroidandroid-fragmentsandroid-tablayout

How to manage java file with tablayout and fragments


I was developing a simple app with firestore. in this case, for better functionality and customer friendly, I input the tablayout concept with fragments to my app. when I using, some errors were coming up. I tried but I cannot fix it. So what I want to is, what is case which affect to that kind of error?? If you are familiar which I was saying, please help me.

this is the java file that i want to code in one fragment. 
package com.example.work_home;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;

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

import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import static android.content.ContentValues.TAG;
import static com.example.work_home.R.id.txt_select_leave;

public class Apply extends Fragment {
    private AutoCompleteTextView SelectLeave, LeaveType;
    TextInputEditText FromDate, ToDate;
    EditText Reason;
    private DatePickerDialog dataPickerDialog_from;
    private DatePickerDialog dataPickerDialog_to;
    Button BtnSubmit;
    BottomNavigationView BtnBottom;
    View v;
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseUser FUser = auth.getCurrentUser();
    public String UserId = FUser.getUid();

    private FirebaseFirestore db = FirebaseFirestore.getInstance();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        v = inflater.inflate(R.layout.fragment_apply, container, false);
        return v;
        SelectLeave = v.findViewById(txt_select_leave);
        LeaveType = v.findViewById(R.id.txt_leave_type);
        FromDate = v.findViewById(R.id.txt_from_user);
        ToDate = v.findViewById(R.id.txt_to_user);
        Reason = v.findViewById(R.id.txt_reason_user);
        BtnSubmit = v.findViewById(R.id.btn_submit);
        BtnBottom = v.findViewById(R.id.btn_bottom_navigation_leave);


        BtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String selectLeave = SelectLeave.getText().toString();
                String leaveType = LeaveType.getText().toString();
                String fromDate = FromDate.getText().toString();
                String toDate = ToDate.getText().toString();
                String reason = Reason.getText().toString();

                DocumentReference documentReference = db.collection("users").document(UserId);
                DocumentReference documentReference_two = documentReference.collection("ApplyLeave").document();

                Map<String, Object> LeaveData = new HashMap<>();
                LeaveData.put("u_select_leave", selectLeave);
                LeaveData.put("u_leave-type", leaveType);
                LeaveData.put("u_from_date", fromDate);
                LeaveData.put("u_to_date", toDate);
                LeaveData.put("u_reason", reason);

                documentReference_two.set(LeaveData);

            }
        });


        FromDate.setText(getTodayDate());
        ToDate.setText(getTodayDate());

        initDatePicker_from();
        initDatePicker_to();

        String[] Select_Leave = new String[]{
                "Casual Leave", "Sick Leave", "Annual Leave ", "Maternity Leave", "Paternity Leave"
                , "Compensatory Off", "Other"};

        ArrayAdapter adapter = new ArrayAdapter<>(
                Apply.this, R.layout.dropdown_item, Select_Leave
        );
        SelectLeave.setAdapter(adapter);

        String[] Leave_Type = new String[]{
                "Full Day", "Half Day", "Other"};

        ArrayAdapter<String> adapter_one = new ArrayAdapter<>(
                Apply.this, R.layout.dropdown_item, Leave_Type
        );
        LeaveType.setAdapter(adapter_one);

        /*BtnBottom.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.logout:
                        Intent logout = new Intent(Apply.this, Login.class);
                        startActivity(logout);
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.home:
                        Intent home = new Intent(Apply_leave.this, Home.class);
                        startActivity(home);
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.user:
                        Intent user = new Intent(Apply_leave.this, UserProfile.class);
                        startActivity(user);
                        overridePendingTransition(0, 0);
                        return true;
                    /*case R.id.alerts:
                        Intent alerts = new Intent(Apply_leave.this, Notifications.class);
                        startActivity(alerts);
                        overridePendingTransition(0, 0);
                        return true;

                }
                return false;
            }
        });*/


    }

    private String getTodayDate() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        month = month + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        return makeDataString(day, month, year);


    }


    private void initDatePicker_from() {
        DatePickerDialog.OnDateSetListener dataSetListener_from = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                month = month + 1;
                String date_from = makeDataString(dayOfMonth, month, year);
                FromDate.setText(date_from);
            }
        };
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        int style = AlertDialog.THEME_HOLO_LIGHT;
        dataPickerDialog_from = new DatePickerDialog(this, style, dataSetListener_from, year, month, day);
        dataPickerDialog_from.getDatePicker().setMaxDate(System.currentTimeMillis());
    }

    private void initDatePicker_to() {
        DatePickerDialog.OnDateSetListener dataSetListener_to = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                month = month + 1;
                String date_to = makeDataString(dayOfMonth, month, year);
                ToDate.setText(date_to);
            }
        };
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        int style = AlertDialog.THEME_HOLO_LIGHT;
        dataPickerDialog_to = new DatePickerDialog(this, style, dataSetListener_to, year, month, day);
        dataPickerDialog_to.getDatePicker().setMaxDate(System.currentTimeMillis());
    }

    private String makeDataString(int dayOfMonth, int month, int year) {
        return getMonthFormat(month) + " " + dayOfMonth + " " + year;
    }

    private String getMonthFormat(int month) {
        if (month == 1)
            return "JAN";
        if (month == 2)
            return "FEB";
        if (month == 3)
            return "MAR";
        if (month == 4)
            return "APR";
        if (month == 5)
            return "MAY";
        if (month == 6)
            return "JUN";
        if (month == 7)
            return "JUL";
        if (month == 8)
            return "AUG";
        if (month == 9)
            return "SEP";
        if (month == 10)
            return "OCT";
        if (month == 11)
            return "NOV";
        if (month == 12)
            return "DEC";

        return "JAN";

    }

    public void openDatePicker_from(View view) {
        dataPickerDialog_from.show();

    }

    public void openDatePicker_to(View view) {
        dataPickerDialog_to.show();


    }
}

*****this is layout of my tablayout(main.xml) file[enter image description here][1]

******* this is the layout of apply.xml file******** [enter image description here][2]

this is my adapter file*****

package com.example.work_home;

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

import java.util.ArrayList;

public class VPAdapter extends FragmentPagerAdapter {

    private final ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
    private final ArrayList<String> fragmentTitle = new ArrayList<>();


    public VPAdapter(@NonNull FragmentManager fm, int behavior) {
        super(fm, behavior);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragmentArrayList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentArrayList.size();
    }
    public void addFragment(Fragment fragment, String title){
        fragmentArrayList.add(fragment);
        fragmentTitle.add(title);

    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {

        return fragmentTitle.get(position);
    }
}

So if You are familiar with these kind of problem please help me..

*errors in the code

error: cannot infer type arguments for ArrayAdapter<>
        ArrayAdapter<String> adapter_one = new ArrayAdapter<>(
                                           ^
error: incompatible types: Apply cannot be converted to Context
        dataPickerDialog_from = new DatePickerDialog(this, style, dataSetListener_from, year, month, day);
                                                     ^
error: unreachable statement
        SelectLeave = v.findViewById(txt_select_leave);
        ^
******************errors****************************
[enter image description here][3] 
[enter image description here][4]


  [1]: https://i.sstatic.net/hDZcQ.png
  [2]: https://i.sstatic.net/sAVCB.png
  [3]: https://i.sstatic.net/vbChu.png
  [4]: https://i.sstatic.net/uuDg3.png

Solution

  • These are Java compilation errors.

    error: cannot infer type arguments for ArrayAdapter<>
            ArrayAdapter<String> adapter_one = new ArrayAdapter<>(
                  Apply.this, R.layout.dropdown_item, Select_Leave
            );
    

    So the problem is that all of the constructors for ArrayAdapter require a Context as the first argument. But you have given it an Apply. And Apply has been declared as a Fragment ... and a Fragment is not a Context.

    error: incompatible types: Apply cannot be converted to Context
            dataPickerDialog_from = new DatePickerDialog(
                 this, style, dataSetListener_from, year, month, day);
    

    This is pretty much the same problem. The DatePickerDialog constructors all require a Context as the first argument, but this is an Apply which is not a Context.

    I'm not 100% sure about this, but I think you should be calling getContext() on your Apply / Fragment instance and passing the result to those two constructors ...


    Note that you can (and should) find and read the javadocs for the Android library classes to understand how to use them. For example, the javadocs for Fragment tell you that a Fragment is not a Context ... but it does have a getContext() method.