Android Studio replace a relative layout insade a framgent with another fragment - java

I have a fragment that contains a PercentRelativeLayout that I want to replace with another fragment on a button click. Here is the outer fragment xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.percent.PercentRelativeLayout
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:layout_widthPercent="92%"
app:layout_heightPercent="80%"
app:layout_marginTopPercent="15%">
<android.support.percent.PercentRelativeLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Vecka 49"
android:id="#+id/weekOneTextView"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekOneTextView"
android:id="#+id/displayWeekOne">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_below="#+id/displayWeekOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 50"
android:id="#+id/weekTwoTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekTwoTextView"
android:id="#+id/displayWeekTwo">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_below="#+id/displayWeekTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 51"
android:id="#+id/weekThreeTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekThreeTextView"
android:id="#+id/displayWeekThree">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
android:layout_below="#+id/displayWeekThree"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 52"
android:id="#+id/weekFourTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekFourTextView"
android:id="#+id/displayWeekFour">
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
Here is the onClick method in the fragments Java file
private void setOnClickListeners(){
mWeekOneTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DropDownWeekFragment dropDownWeekFragment = new DropDownWeekFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().add(R.id.displayWeekOne, dropDownWeekFragment).commit();
}
});
I want to replace the PercentRelativeLayout with ID displayWeekOne with a fragment, here is the for the fragment I wish to replace with
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="layout.DropDownWeekFragment">
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="80%"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Måndag"
android:id="#+id/monday"
app:layout_marginTopPercent="2%"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tisdag"
android:id="#+id/tuesday"
android:layout_below="#id/monday"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/wednessday"
android:layout_below="#id/tuesday"
android:text="Onsdag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/thursday"
android:layout_below="#id/wednessday"
android:text="Torsdag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friday"
android:layout_below="#id/thursday"
android:text="Fredag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/saturday"
android:layout_below="#id/friday"
android:text="Lördag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sunday"
android:layout_below="#id/saturday"
android:text="Söndag"/>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
And here is the Java for that fragment
package layout;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.studentconsulting.mypages.R;
import static android.content.ContentValues.TAG;
public class DropDownWeekFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public DropDownWeekFragment() {
// Required empty public constructor
}
public static DropDownWeekFragment newInstance(String param1, String param2) {
DropDownWeekFragment fragment = new DropDownWeekFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
Log.d("hej", "oncreate");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_drop_down_week, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
I read in the documentation that I can use replace() to replace another fragment, but I want to replace the PercentRelativeLayout if that is possible, or add the fragment to the outer fragments xml

FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.displayWeekOne, dropDownWeekFragment).commit();
You can use replace() to replace one Fragment with another Fragment, as well as a Layout with a Fragment.
Not tested. Hope it works.

Related

Fragment Layout color changing issues

I have created three swiping splash screen layout fragments over an splash screen activity, and I want to change the color of the status bar for each fragment which matches the color of the fragment body.
My Code is
Fragment_a.xml
<?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=".FragmentA">
<ImageView
android:id="#+id/circle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_filled"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<ImageView
android:id="#+id/circle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_blank"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/circle1"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"/>
<ImageView
android:id="#+id/circle3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_blank"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/circle2"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:text="Skip"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginTop="120dp"
android:src="#drawable/ic_browsing"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="68dp"
android:text="Move"
android:textSize="20dp"
app:layout_constraintStart_toStartOf="#+id/imageView2"
app:layout_constraintTop_toBottomOf="#+id/imageView2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Step by Step"
app:layout_constraintTop_toBottomOf="#id/textView2"
app:layout_constraintStart_toStartOf="#id/textView2"
android:layout_marginTop="6dp"
android:textSize="35sp"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a dummy text.\nMade for testing purpose!"
android:textSize="20sp"
android:layout_marginTop="10dp"
app:layout_constraintStart_toStartOf="#+id/textView3"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
</androidx.constraintlayout.widget.ConstraintLayout>
FragmentA.java
package in.pratikchakraborty.liquidswipe;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
public class FragmentA extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FragmentA() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentA.
*/
// TODO: Rename and change types and number of parameters
public static FragmentA newInstance(String param1, String param2) {
FragmentA fragment = new FragmentA();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.white));
}
}
}
I am getting this error while building the project.
AndroidStudioProjects\LiquidSwipe\app\src\main\java\in\pratikchakraborty\liquidswipe\FragmentA.java:65: error: unreachable statement
if (Build.VERSION.SDK_INT >= 21) {
^
You are writing the code for change status color after the return statement so it is not reachable please try below
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_a, container, false);
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.white));
}
return view;
}

How do I create a fragment template(class with variables and methods, layout) for multiple fragments with the same content?

On the main screen I have 7 buttons (days) and a fragment.
For every day of the week I wanted to generate a fragment with some EditTexts and a ListView, but creating 7 fragments with the same layout and almost the same class content seems too repetitive.
I only did it for Monday and Tuesday.
The only difference between MondayFragment and TuesdayFragment is that in TuesdayFragment I renamed the variable mondayTV to tuesdayTV and in layout I changed the ids of the submit button and the ListView. Also the key for Bundle is different. I don't think it's worth posting it since it's so similar to MondayFragment.
I want to know if it's possible to create a fragment template and use it to generate a fragment for every button of the activity given this code I wrote. There is still a lot to work on when it comes to functionality but I can't get this idea out of my head.
MainActivity.java
package com.example.dietmanagement;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button monday, tuesday, wednesday, thursday, friday, saturday, sunday;
final MondayFragment mondayFragment = new MondayFragment();
final TuesdayFragment tuesdayFragment = new TuesdayFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Intent i = getIntent();
String current_user = i.getStringExtra("current_user");
TextView current_user_txtview = findViewById(R.id.current_user);
current_user_txtview.setText("Welcome, " + current_user);*/
monday = (Button)findViewById(R.id.monday_btn);
tuesday = (Button)findViewById(R.id.tuesday_btn);
wednesday = (Button)findViewById(R.id.wednesday_btn);
thursday = (Button)findViewById(R.id.thursday_btn);
friday = (Button)findViewById(R.id.friday_btn);
saturday = (Button)findViewById(R.id.saturday_btn);
sunday = (Button)findViewById(R.id.sunday_btn);
monday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragment(mondayFragment);
getDay(mondayFragment, "monday", (String) monday.getContentDescription());
}
});
tuesday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragment(tuesdayFragment);
getDay(tuesdayFragment, "tuesday", (String) tuesday.getContentDescription());
}
});
}
private void openFragment(final Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.daysfragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void getDay(final Fragment fragment, String key, String value)
{
Bundle bnd = new Bundle();
bnd.putString(key, value);
fragment.setArguments(bnd);
}
}
Activity_main.xml
<?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"
android:background="#color/background_green"
tools:context=".MainActivity">
<Button
android:id="#+id/tuesday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:contentDescription="#string/tuesday_context"
android:text="#string/tuesday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.194"
app:layout_constraintStart_toEndOf="#+id/monday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<TextView
android:id="#+id/main_title"
android:layout_width="147dp"
android:layout_height="93dp"
android:fontFamily="sans-serif-medium"
android:text="#string/welcome_label"
android:textColor="#FFFFFF"
android:textSize="70sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.414"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.049" />
<Button
android:id="#+id/monday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:contentDescription="#string/monday_context"
android:text="#string/monday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<Button
android:id="#+id/thursday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/thursday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.018"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/sunday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/sunday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.786"
app:layout_constraintStart_toEndOf="#+id/saturday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/saturday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/saturday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.225"
app:layout_constraintStart_toEndOf="#+id/friday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/friday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/friday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.137"
app:layout_constraintStart_toEndOf="#+id/thursday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/wednesday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/wednesday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.369"
app:layout_constraintStart_toEndOf="#+id/tuesday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<ImageView
android:id="#+id/logo"
android:layout_width="52dp"
android:layout_height="58dp"
android:layout_marginStart="8dp"
android:layout_marginTop="52dp"
android:contentDescription="#string/app_name"
app:layout_constraintStart_toEndOf="#+id/main_title"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_logo" />
<TextView
android:id="#+id/current_user"
android:layout_width="362dp"
android:layout_height="27dp"
android:text="#string/current_user"
android:textAlignment="viewEnd"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/main_title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.938"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.318" />
<FrameLayout
android:id="#+id/daysfragment"
android:layout_width="match_parent"
android:layout_height="460dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MondayFragment.java
package com.example.dietmanagement;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MondayFragment extends Fragment {
public TextView mondayTV;
public ArrayList<String> hour_food;
public ArrayAdapter<String> listViewAdapter;
public ListView listView;
public EditText input_meal;
public EditText input_time;
public Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_monday, container, false);
mondayTV = (TextView) v.findViewById(R.id.day);
Bundle bndMon = getArguments();
String day = bndMon.getString("monday");
mondayTV.setText(day);
hour_food = new ArrayList<String>();
listViewAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, hour_food);
listView = (ListView)v.findViewById(R.id.monday_list_item);
listView.setAdapter(listViewAdapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
hour_food.remove(position);
Toast.makeText(getActivity(), "Meal Removed", Toast.LENGTH_SHORT).show();
listViewAdapter.notifyDataSetChanged();
return true;
}
});
input_meal = v.findViewById(R.id.input_meal);
input_time = v.findViewById(R.id.input_time);
submit = (Button) v.findViewById(R.id.submit_food_btn);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(input_time.getText())) {
Toast.makeText(getActivity(), "Empty time input", Toast.LENGTH_SHORT).show();
} else if(TextUtils.isEmpty(input_meal.getText())){
Toast.makeText(getActivity(), "Empty meal input", Toast.LENGTH_SHORT).show();
}
else
{
hour_food.add(String.format("%s - %s", input_meal.getText().toString(), input_time.getText().toString()));
listViewAdapter.notifyDataSetChanged();
input_meal.setText("");
input_time.setText("");
}
}
});
return v;
}
}
fragment_monday.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_green"
tools:context=".MondayFragment">
<TextView
android:id="#+id/day"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/input_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints="#string/time"
android:hint="#string/time"
android:inputType="time" />
<EditText
android:id="#+id/input_meal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="#string/meal"
android:hint="#string/meal"
android:inputType="textAutoCorrect|textCapSentences" />
</LinearLayout>
<Button
android:id="#+id/submit_food_btn_monday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:background="#color/white"
android:textColor="#color/background_green"
android:layout_gravity="end"
android:layout_marginTop="10dp"/>
<ListView
android:id="#+id/monday_list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
strings.xml
Create DayFragment and layout only for one day. Pass extra information for Fragment and handle situations for different days with that extra information (in your case it looks like only String from bundle is different).
fragment_day.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_green">
<TextView
android:id="#+id/day"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/input_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints="#string/time"
android:hint="#string/time"
android:inputType="time" />
<EditText
android:id="#+id/input_meal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="#string/meal"
android:hint="#string/meal"
android:inputType="textAutoCorrect|textCapSentences" />
</LinearLayout>
<Button
android:id="#+id/submit_food_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:background="#color/white"
android:textColor="#color/background_green"
android:layout_gravity="end"
android:layout_marginTop="10dp"/>
<ListView
android:id="#+id/list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
DayFragment.java
public class DayFragment extends Fragment {
private TextView dayTV;
private ArrayList<String> hour_food;
private ArrayAdapter<String> listViewAdapter;
private ListView listView;
private EditText input_meal;
private EditText input_time;
private Button submit;
private String text;
public DayFragment(String text) {
this.text = text;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_day, container, false);
dayTV = v.findViewById(R.id.day);
dayTV.setText(text);
hour_food = new ArrayList<>();
listViewAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, hour_food);
listView = v.findViewById(R.id.list_item);
listView.setAdapter(listViewAdapter);
listView.setOnItemLongClickListener((parent, view, position, id) -> {
hour_food.remove(position);
Toast.makeText(getActivity(), "Meal Removed", Toast.LENGTH_SHORT).show();
listViewAdapter.notifyDataSetChanged();
return true;
});
input_meal = v.findViewById(R.id.input_meal);
input_time = v.findViewById(R.id.input_time);
submit = v.findViewById(R.id.submit_food_btn);
submit.setOnClickListener(v1 -> {
if (TextUtils.isEmpty(input_time.getText())) {
Toast.makeText(getActivity(), "Empty time input", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(input_meal.getText())) {
Toast.makeText(getActivity(), "Empty meal input", Toast.LENGTH_SHORT).show();
} else {
hour_food.add(String.format("%s - %s", input_meal.getText().toString(), input_time.getText().toString()));
listViewAdapter.notifyDataSetChanged();
input_meal.setText("");
input_time.setText("");
}
});
return v;
}
}
Use constructor for passing information.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button monday = findViewById(R.id.monday_btn),
tuesday = findViewById(R.id.tuesday_btn),
wednesday = findViewById(R.id.wednesday_btn),
thursday = findViewById(R.id.thursday_btn),
friday = findViewById(R.id.friday_btn),
saturday = findViewById(R.id.saturday_btn),
sunday = findViewById(R.id.sunday_btn);
openFragment(monday);
openFragment(tuesday);
openFragment(wednesday);
openFragment(thursday);
openFragment(friday);
openFragment(saturday);
openFragment(sunday);
}
private void openFragment(Button btn) {
btn.setOnClickListener(v -> {
String contentDescription = btn.getContentDescription().toString();
getSupportFragmentManager().beginTransaction()
.replace(R.id.daysfragment, new DayFragment(contentDescription))
.addToBackStack(null)
.commit();
});
}
}
In MainActivity openFragment() method takes a Button parameter and with that Button and sets onClickListener to that Button. When you click any Button it gets content description from that Button and passing it to Fragment and opens that Fragment with that content description.

How to stop fragments from being recreated in fragment transaction

I have an activity with multiple steps, each step being a fragment transaction with an edittext box, with a next/back button to navigate and initiate sending the users input data. I want to be able to move throughout the fragments with the text in each box staying static. I can move back no problem, but as soon as I click next the next fragment is recreated and everything is lost.
I tried:
using a dummy view in onCreateView
refetching the string in onCreate
setRetainInstance(true); in the constructor
Using a viewpager has other complications regarding receiving data which I was not able to solve despite many here attempting to help, so I have no choice but to use fragment transactions in my app.
main/FormActivity.java
package com.loopbreakr.formproject;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class FormActivity extends AppCompatActivity implements PageOne.ExitFormInteractionListener{
//DECLARE COMPONENTS
private FrameLayout fragmentContainer;
private Button backToMain;
private Button startForm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//FIND COMPONENTS IN XML
setContentView(R.layout.activity_form);
fragmentContainer = findViewById(R.id.frame_layout);
backToMain = findViewById(R.id.return_button);
startForm = findViewById(R.id.start_button);
//SET LISTENERS/INTENTS FOR BUTTONS
backToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
startForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragments();
}
});
}
private void openFragments() {
PageOne fragment1 = PageOne.newInstance();
FragmentManager fragmentManager =getSupportFragmentManager();
FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
beginTransaction.addToBackStack(null);
beginTransaction.add(R.id.frame_layout,fragment1,"PageOne_tag");
beginTransaction.commit();
}
#Override
public void onFragmentInteraction(String answerOneText) {
}
}
One of my fragments PageOne.java
package com.loopbreakr.formproject;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class PageOne extends Fragment {
View restored;
private static final String SAVED = "text";
private String savedText;
private String answerOneString;
private EditText answerOne;
private ExitFormInteractionListener mListener;
public PageOne() {
setRetainInstance(true);
}
public static PageOne newInstance() {
PageOne fragment = new PageOne();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
savedText = getArguments().getString(SAVED);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(restored == null){
restored = inflater.inflate(R.layout.fragment_page_one, container, false);
}
answerOne = restored.findViewById(R.id.answer_one);
Button exitForm = restored.findViewById(R.id.exit_form);
Button goNextTwo = restored.findViewById(R.id.gonext_two);
exitForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
returnToDesc();
}
});
goNextTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answerOneString = answerOne.getText().toString();
sendToTwo(answerOneString);
openSecondFragment();
}
});
return restored;
}
private void sendToTwo(String answerOneText) {
if(mListener != null){
mListener.onFragmentInteraction(answerOneText);
}
}
private void openSecondFragment() {
PageTwo fragment2 = PageTwo.newInstance(answerOneString);
FragmentTransaction fragTransition = getFragmentManager().beginTransaction();
fragTransition.replace(R.id.frame_layout, fragment2,"PageTwo_TAG");
fragTransition.addToBackStack(null);
fragTransition.commit();
}
private void returnToDesc(){
FragmentManager fragTransBack = getFragmentManager();
fragTransBack.popBackStack();
}
public interface ExitFormInteractionListener{
void onFragmentInteraction(String answerOneText);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
if (context instanceof ExitFormInteractionListener) {
mListener = (ExitFormInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
activity_form.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FormActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="32dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</LinearLayout>
<TextView
android:id="#+id/activity_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="#string/activity_title"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/return_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="8dp"
android:text="#string/return_text"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="#string/start_text"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintEnd_toEndOf="parent"
android:stateListAnimator="#null"/>
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
activity_page_one.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:clickable="true"
tools:context=".PageOne"
android:focusable="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:id="#+id/activity_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="#string/activity_title"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<Button
android:id="#+id/exit_form"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="8dp"
android:text="#string/back"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:stateListAnimator="#null"/>
<Button
android:id="#+id/gonext_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="#string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:stateListAnimator="#null"/>
<EditText
android:id="#+id/answer_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="start|top"
android:hint="#string/answer_one_hint"
android:inputType="textMultiLine|textAutoCorrect"
android:maxLines="4"
android:minLines="4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/activity_name"
android:stateListAnimator="#null"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
Thanks.

Why when I want to access this fragment my application fails? Android Studio

I am developing an application in which I want to insert data in firebase, but when I want to open the fragment in the application I get an error.
I am using nav_graph for navigation between screens and I am also using movile_navigation. I don't know if that is information that could be important.
This is the java code, I don't know what causes the error:
```
public class Pantalla1Fragment extends Fragment{
TextView editTextName;
TextView editTextEdad;
TextView editTextApellidos;
TextView editTextGenero;
TextView editPadecimientos;
TextView editTextObservaciones;
TextView getEditTextTratamientos;
Button btnRegistar;
FirebaseAuth mAuth;
DatabaseReference mDatabase;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Pantalla1Fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Pantalla1Fragment.
*/
// TODO: Rename and change types and number of parameters
public static Pantalla1Fragment newInstance(String param1, String param2) {
Pantalla1Fragment fragment = new Pantalla1Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/*#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_pantalla1, container, false);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
editTextName = view.findViewById(R.id.editTextName);
editTextEdad = view.findViewById(R.id.editTextEdad);
editTextApellidos = view.findViewById(R.id.editTextApellidos);
editTextGenero = view.findViewById(R.id.editTextGenero);
editPadecimientos = view.findViewById(R.id.editTextPadesimientos);
editTextObservaciones = view.findViewById(R.id.editTextObservaciones);
getEditTextTratamientos = view.findViewById(R.id.editTextTratamientos);
btnRegistar = view.findViewById(R.id.btnRegistar);
btnRegistar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerPerfil();
}
});
}
public void registerPerfil() {
String nombre=editTextName.getText().toString();
String apellidos=editTextApellidos.getText().toString();
String edad=editTextEdad.getText().toString();
String genero=editTextGenero.getText().toString();
String padecimientos=editPadecimientos.getText().toString();
String tratamiento=getEditTextTratamientos.getText().toString();
String observaciones=editTextObservaciones.getText().toString();
if(!TextUtils.isEmpty(nombre)){
String id=mDatabase.push().getKey();
Registro_Perfiles perfil = new Registro_Perfiles(nombre, apellidos, edad, genero, padecimientos, tratamiento, observaciones);
mDatabase.child("Users").child(id).setValue(perfil);
//Toast.makeText(this, "Datos introducidos", Toast.LENGTH_LONG).show();
}
}
}
And this part is the fragment view:
<?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=".Pantalla1Fragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:padding="15dp"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre" />
<EditText
android:id="#+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="#string/editTextNombre" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Apellidos" />
<EditText
android:id="#+id/editTextApellidos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Apellidos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Edad" />
<EditText
android:id="#+id/editTextEdad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Edad" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Genero" />
<EditText
android:id="#+id/editTextGenero"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Genero" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Padesimientos" />
<EditText
android:id="#+id/editTextPadesimientos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Padesimientos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Tratamientos" />
<EditText
android:id="#+id/editTextTratamientos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Tratamientos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Observaciones" />
<EditText
android:id="#+id/editTextObservaciones"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Observaciones" />
<Button
android:id="#+id/btnRegistar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="REGISTRAR NUEVO PERFIL" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Error in the logcat
--------- beginning of crash
2020-08-26 12:13:05.893 17635-17635/com.example.thebestapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.thebestapp, PID: 17635
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.push()' on a null object reference
at com.example.thebestapp.Pantalla1Fragment.registerPerfil(Pantalla1Fragment.java:126)
at com.example.thebestapp.Pantalla1Fragment$1.onClick(Pantalla1Fragment.java:111)
at android.view.View.performClick(View.java:6297)
at android.view.View$PerformClick.run(View.java:24797)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6626)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
You should never be using getActivity().findViewById in a Fragment.
Instead, override onViewCreated() and use view.findViewById() - the view that is passed to that method is the view you inflated in onCreateView():
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
editTextName = view.findViewById(R.id.editTextName);
editTextEdad = view.findViewById(R.id.editTextEdad);
editTextApellidos = view.findViewById(R.id.editTextApellidos);
editTextGenero = view.findViewById(R.id.editTextGenero);
editPadecimientos = view.findViewById(R.id.editTextPadesimientos);
editTextObservaciones = view.findViewById(R.id.editTextObservaciones);
getEditTextTratamientos = view.findViewById(R.id.editTextTratamientos);
btnRegistar = view.findViewById(R.id.btnRegistar);
btnRegistar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerPerfil();
}
});
}

Radio button OnCheckedChangeListener error inside fragment

I am facing some problem when calling onCheckedCahngedListener inside fragment on radio group app crashes.
when clicking on any item inside radio group the app crashed.
fragment_sell.xml
<LinearLayout 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"
tools:context="com.example.syedsaadali.myapplication.SellFragment"
android:orientation="vertical">
<HorizontalScrollView
android:id="#+id/scrollView"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_gravity="center"
android:background="#FFFFFF"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/RadioButton1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:checkedButton="#+id/first"
>
<RadioButton
android:id="#+id/sApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/apartment"
android:padding="15dp"
android:onClick="apartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sBuilder"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/house"
android:padding="15dp"
android:onClick="house"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sPlot"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:button="#drawable/land"
android:padding="15dp"
android:onClick="land"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sHouse"
android:layout_width="100dp"
android:layout_height="match_parent"
android:button="#drawable/builder"
android:padding="15dp"
android:onClick="builder"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sStudioApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/farmhouse"
android:padding="15dp"
android:onClick="farmhouse"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sFarmHouse"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/serviceapartment"
android:padding="15dp"
android:onClick="servicedapartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sServicedApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/studioapartment"
android:padding="15dp"
android:onClick="studioapartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
</RadioGroup>
</LinearLayout>
</HorizontalScrollView>
SellFragment.java
public class SellFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private RadioGroup mRadioGroup1;
private RadioButton mapartment;
private RadioButton mBuilder;
private RadioButton mplot;
private RadioButton mHouse;
private RadioButton mStudioApartment;
private RadioButton mFarmhouse;
private RadioButton mServicedApartment;
private Spinner city;
private View layout;
public static SellFragment newInstance(String param1, String param2) {
SellFragment fragment = new SellFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
layout = inflater.inflate(R.layout.fragment_sell, container, false);
mRadioGroup1=(RadioGroup) layout.findViewById(R.id.RadioButton1);
mapartment=(RadioButton)layout.findViewById(R.id.sApartment);
mBuilder=(RadioButton)layout.findViewById(R.id.sBuilder);
mplot=(RadioButton)layout.findViewById(R.id.sPlot);
mHouse=(RadioButton)layout.findViewById(R.id.sHouse);
mStudioApartment=(RadioButton)layout.findViewById(R.id.sStudioApartment);
mFarmhouse=(RadioButton)layout.findViewById(R.id.sFarmHouse);
mServicedApartment=(RadioButton)layout.findViewById(R.id.sServicedApartment);
mRadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.sApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
} else if (checkedId == R.id.sBuilder) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sPlot) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sHouse) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sStudioApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sFarmHouse) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.cServicedApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
}
});
return layout;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}}
Logcat:
03-23 02:50:57.703 4697-4697/com.example.syedsaadali.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.syedsaadali.myapplication, PID: 4697
java.lang.IllegalStateException: Could not find method apartment(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatRadioButton with id 'cApartment'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4780)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You have defined <RadioButton ... android:onClick="apartment"/> In the XML But any method apartment was not created in Activity.
To resolve this Either remove that onClick attribute (if note needed) OR create a method apartment in java as well like
public void apartment(View view){
}
You can directly click Alt + Enter in onClick attribute of XML to get the hint of resolving this error by creating method.

Categories