Button doesn't work when adding to fragment - java

I have a button in an fragment that when I clicked on it nothing happens at all
this is the java code of the fragment:
public class HomeFragment 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;
EditText etAddPost;
Button addPostImage;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef;
public HomeFragment() {
// 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 HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
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);
}
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
etAddPost =rootView.findViewById(R.id.etAddPost);
addPostImage = rootView.findViewById(R.id.addPostBtn);
addPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
String postText = etAddPost.getText().toString();
if(TextUtils.isEmpty(postText)){
etAddPost.setError("لا يمكنك ترك هذا الحقل فارغا");
}
else {
Map<String, String> map = new HashMap<>();
map.put("postContent", postText);
myRef.push().setValue(map);
etAddPost.setText("");
}
}
}); return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
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;
}
"http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
and this is my XML code :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/color3"
tools:context="com.mk.playAndLearn.fragment.HomeFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal">
<Button
android:id="#+id/addPostBtn"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:background="#drawable/send"
android:layout_marginRight="5dp"/>
<EditText
android:layout_margin="5dp"
android:id="#+id/etAddPost"
android:layout_width="0dp"
android:gravity="right"
android:layout_height="wrap_content"
android:layout_weight="7"
android:hint="ماذا يخطر في بالك؟"
android:paddingRight="10dp"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</FrameLayout>
I have tried a lot to solve this problem but I couldn't but I am feeling that solving the problem is easy so I hope that any one helps me to solve this problem I tried to change the button type and use ImageButton instead but that doesn't solve the problem

I think you've problems with xml layout. Your recyclerview laying over linear layout. Change the layout as below
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/color3"
tools:context="com.mk.playAndLearn.fragment.HomeFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal">
<Button
android:id="#+id/addPostBtn"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:background="#drawable/send"
android:layout_marginRight="5dp"/>
<EditText
android:layout_margin="5dp"
android:id="#+id/etAddPost"
android:layout_width="0dp"
android:gravity="right"
android:layout_height="wrap_content"
android:layout_weight="7"
android:hint="ماذا يخطر في بالك؟"
android:paddingRight="10dp"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</FrameLayout>

Related

I get an error in the button click listener (Android Studio)

I made an app to send mail separately and I am trying to implement it within another app, well it gives me this error Attempt to invoke virtual method
'void android.widget.Button.setOnClickListener (android.view.View $ OnClickListener)' on a null object reference
I have the id well that I know and the way to put the button and the click listener are well located. What can the error give?
this is my code
public class ContactFragment extends Fragment {
//public EditText mEmail;
public EditText mSubject;
public EditText mMessage;
private Button buttonSend_contact;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public ContactFragment() {
}
public static ContactFragment newInstance(String param1, String param2) {
ContactFragment fragment = new ContactFragment();
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) {
View view = inflater.inflate(R.layout.fragment_videos, container, false);
mMessage = view.findViewById(R.id.messageID);
mSubject = view.findViewById(R.id.subjectID);
buttonSend_contact = view.findViewById(R.id.buttonSendMail);
buttonSend_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMail();
}
});
return view;
}
private void sendMail() {
String mail = "turespawnofficial#gmail.com";
String message = mMessage.getText().toString();
String subject = mSubject.getText().toString().trim();
//Send Mail
JavaMailAPI javaMailAPI = new JavaMailAPI(getActivity(),mail,subject,message);
javaMailAPI.execute();
}
this is my xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ContactFragment">
<!-- <EditText
android:id="#+id/mailID"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"/> -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/subjectID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Subject" />
<EditText
android:id="#+id/messageID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Message" />
<Button
android:id="#+id/buttonSendMail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
</FrameLayout>

Change fragment from spinner in a top fragment

I've an app with a tab view, which has 2 tab. Tab 2 contains a spinner that has a drop-down function. The spinner includes Prova 1, 2, etc. Clicking on each item will open a fragment below. Clicking on the Prova 1, will take me to a page that show some information, but it doesn't work.
Picture 1
Picture 2
Picture 3
FragmentTop.java
public class FragmentTop extends Fragment { //implements AdapterView.OnItemClickListener{
// 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";
private Spinner spinner;
private String[] items;
private FragmentProva1 fragmentProva1;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FragmentTop() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static FragmentTop newInstance(String param1, String param2) {
FragmentTop fragment = new FragmentTop();
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) {
View view = inflater.inflate(R.layout.fragment_Top, container, false);
items = getResources().getStringArray(R.array.Top);
fragmentProva1 = new FragmentProva1();
spinner = view.findViewById(R.id.spinnerTop);
initSpinner();
// Inflate the layout for this fragment
return view;
}
private void initSpinner() {
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String text = adapterView.getItemAtPosition(i).toString();
switch (text){
case "Prova1":
setFragment(fragmentProva1);
break;
case "Prova2":
break;
}
Toast.makeText(adapterView.getContext(),text,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
public void setFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentTop_id, fragment);
fragmentTransaction.commit();
}
}
fragment_top.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentTop">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Spinner
android:id="#+id/spinnerTop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16sp"
android:textSize="16sp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentTop_id" />
</ScrollView>
</LinearLayout>
</FrameLayout>
FragmentProva1.java
public class FragmentProva1 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";
private TextInputLayout textInputSideA;
private TextInputLayout textInputSideB;
private TextInputLayout textInputSideC;
private TextView result;
private Button btnCalculate;
private LinearLayout Prova1LinearLayout;
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FragmentProva1() {
// Required empty public constructor
}
public static FragmentProva1 newInstance(String param1, String param2) {
FragmentProva1 fragment = new FragmentProva1();
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
View view = inflater.inflate(R.layout.fragment_prova1, container, false);
textInputSideA = view.findViewById(R.id.textInputSideA);
textInputSideB = view.findViewById(R.id.textInputSideB);
textInputSideC = view.findViewById(R.id.textInputSideC);
result = view.findViewById(R.id.result);
Prova1LinearLayout = view.findViewById(R.id.Prova1LinearLayout);
btnCalculate = view.findViewById(R.id.btnCalculate);
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double info1;
double info2;
double info3;
if(!validateLatoA() | !validateLatoB() | !validateLatoC()){
return;
}
info1 = calculate();
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
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 {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private boolean validateLatoA(){
String latoA_Input = textInputSideA.getEditText().getText().toString().trim();
if(latoA_Input.isEmpty()){
textInputSideA.setError("Field can't be empty");
return false;
} else {
textInputSideA.setError(null);
return true;
}
}
private boolean validateLatoB(){
String latoB_Input = textInputSideB.getEditText().getText().toString().trim();
if(latoB_Input.isEmpty()){
textInputSideB.setError("Field can't be empty");
return false;
} else {
textInputSideB.setError(null);
return true;
}
}
private boolean validateLatoC(){
String latoC_Input = textInputSideC.getEditText().getText().toString().trim();
if(latoC_Input.isEmpty()){
textInputSideC.setError("Field can't be empty");
return false;
} else {
textInputSideC.setError(null);
return true;
}
}
}
fragment_prova1.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentProva1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="UselessParent"
android:padding="16sp"
android:layout_marginTop="16sp"
android:id="#+id/Prova1LinearLayout">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputSideA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="info1"
android:textSize="16sp"
android:inputType="numberDecimal"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputSideB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="info2"
android:textSize="16sp"
android:inputType="numberDecimal"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputSideC"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="info3"
android:textSize="16sp"
android:inputType="numberDecimal"/>
</com.google.android.material.textfield.TextInputLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calculate"
android:textSize="16sp"
android:id="#+id/btnCalculate"/>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="16sp"
android:padding="16dp"/>
</LinearLayout>
</FrameLayout>

Widget layout from Activity still appear after fragment add transaction

I have a problem with fragments. I add fragments dynamically without removing old fragments so they can be recalled when I return. But when I applied the following snippet I found that some of the views that came from the activity did not disappear, such as the Button, TextView, and so on. The results I get are overlapping views
MainActivity.Java
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {
private static final String TAG = "MainActivity";
private Unbinder unbinder;
private FragmentManager fragmentManager;
#BindView(R.id.dynamic_fragment_frame)
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
unbinder = ButterKnife.bind(this);
fragmentManager = this.getSupportFragmentManager();
}
public void openFragment(View view) {
BlankFragment fragment = BlankFragment.newInstance("Test 1");
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right);
transaction.addToBackStack(null);
transaction.add(R.id.dynamic_fragment_frame, fragment, "BLACK_FRAGMENT");
transaction.commit();
}
#Override
protected void onDestroy() {
unbinder.unbind();
super.onDestroy();
}
#Override
public void onFragmentInteraction(String text) {
Log.d(TAG, "onFragmentInteraction: " + text);
onBackPressed();
}
}
activity_reading.xml
<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"
android:background="#00d9ff"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
</RelativeLayout>
BlankFragment.java
public class BlankFragment extends Fragment {
private static final String ARG_TEXT = "TEXT";
private Unbinder unbinder;
private String mParam1;
private OnFragmentInteractionListener mListener;
#BindView(R.id.tv_blank_fragment)
TextView tvTitle;
#BindView(R.id.back_btn)
Button backBtn;
#BindView(R.id.next_btn)
Button nextBtn;
private FragmentManager fragmentManager;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance(String param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_TEXT);
}
fragmentManager = getFragmentManager();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
tvTitle.setText(mParam1);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "test dari fragment";
sendBack(test);
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void sendBack(String sendback) {
if (mListener != null) {
mListener.onFragmentInteraction(sendback);
}
}
#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(String text);
}
}
fragment_blank.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"
android:background="#cfcf1d"
tools:context=".BlankFragment">
<TextView
android:id="#+id/tv_blank_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<Button
android:id="#+id/next_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_btn"
android:layout_alignParentStart="true"
android:text="Create new Fragment" />
<Button
android:id="#+id/back_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:text="back" />
</RelativeLayout>
Everything went smoothly but the result of my Mainactivity layout still appeared on fragment. Please help me
Result as shows as below:
here 1
here 2
In activity_reading, the fragment container view (dynamic_fragment_frame) is declared first, so the button and the text view will be displayed on top of it. If you move the fragment container to the bottom, the fragments will be displayed correctly, so the layout should look something like this:
<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"
android:background="#00d9ff"
tools:context=".MainActivity">
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<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"
android:background="#00d9ff"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
</RelativeLayout>
With the above layout, Imagine that the TextView and Button are over the FragmeLayout. So when you add a Fragment to the FrameLayout, the TextView and Button are still over the FragmeLayout. To hide these views, you should use TextView.setVisibility(View.GONE) and Button.setVisibility(View.GONE) when adding a Fragment

Can't change container ID of fragment Android

I am working on the development of an Android App. In an Activity there will be two tab. Each of the tabs are individual fragments. I am retrieving some JSON data from the server in Async task and setting those data into the TextView of the Fragment Layout.
So far I understand I have to replace the fragment in the main activity to achieve this. I am getting following error while running the app.
java.lang.IllegalStateException: Can't change container ID of fragment MutualFunds{ed3a1c0 #0 id=0x7f080096}: was 2131230870 now 2131230812
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:422)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:444)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:434)
at com.testappl.ivest.ICLProducts.changefrag(ICLProducts.java:234)
at com.testappl.ivest.ICLProducts$JsonTask.onPostExecute(ICLProducts.java:207)
at com.testappl.ivest.ICLProducts$JsonTask.onPostExecute(ICLProducts.java:101)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
Here is my Fragment Activity class:
package com.testappl.ivest;
import android.app.FragmentManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.testappl.ivest.model.FundMaster;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MutualFunds.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MutualFunds#newInstance} factory method to
* create an instance of this fragment.
*/
public class MutualFunds 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";
private static final String ARG_PARAM3 = "param3";
private static final String ARG_PARAM4 = "param4";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String mParam3;
private String mParam4;
private static View view;
private OnFragmentInteractionListener mListener;
TextView mBFLabel;
TextView mBFDefintion;
TextView mBFCurrentNAV;
TextView mBFCurrentReturn;
TextView mGFLabel;
TextView mGFDefinition;
TextView mGFCurrentNAV;
TextView mGFCurrentReturn;
public MutualFunds() {
// 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 MutualFunds.
*/
// TODO: Rename and change types and number of parameters
public static MutualFunds newInstance(String param1, String param2,String param3,String param4) {
MutualFunds fragment = new MutualFunds();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
args.putString(ARG_PARAM3, param3);
args.putString(ARG_PARAM4, param4);
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);
mParam3=getArguments().getString(ARG_PARAM3);
mParam4=getArguments().getString(ARG_PARAM4);
}
if(savedInstanceState==null){
Fragment MutualFundFragment=new Fragment();
getFragmentManager().beginTransaction().
add(R.id.fragment_mutual_funds,MutualFundFragment,
"mutual_fund_tag").commit();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_mutual_funds, container, false);
mBFLabel=view.findViewById(R.id.fund_name_bf);
mBFDefintion=view.findViewById(R.id.fund_definition_bf);
mBFCurrentNAV=view.findViewById(R.id.current_nav_bf);
mBFCurrentReturn=view.findViewById(R.id.current_return_bf);
mBFLabel.setText(mParam1);
mBFDefintion.setText(mParam2);
mGFLabel=view.findViewById(R.id.fund_name_gf);
mGFDefinition=view.findViewById(R.id.fund_definition_gf);
mGFCurrentNAV=view.findViewById(R.id.current_nav_gf);
mGFCurrentReturn=view.findViewById(R.id.current_return_gf);
mGFLabel.setText(mParam3);
mGFDefinition.setText(mParam4);
return inflater.inflate(R.layout.fragment_mutual_funds, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
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;
}
//Change the texts of Balanced Fund
public void changeBFTexts(FundMaster fm){
mBFLabel.setText(fm.getFundName());
mBFDefintion.setText(fm.getFundDefinition());
}
//Change the texts of Growth Fund
public void changeGFTexts(FundMaster fm){
mGFLabel.setText(fm.getFundName());
mGFDefinition.setText(fm.getFundDefinition());
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Here is my Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".MutualFunds"
android:id="#+id/fragment_mutual_funds">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/fund_name_bf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="28dp"
android:text="#string/mutualfundfrag_iclbf_title"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/fund_definition_bf"
android:layout_width="319dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:text="#string/mutualfundfrag_iclbf_definition"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/fund_name_bf" />
<TextView
android:id="#+id/current_nav_bf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="#string/mutualfundfrag_iclbf_current_nav"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/fund_definition_bf" />
<TextView
android:id="#+id/current_return_bf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="#string/mutualfundfrag_iclbf_current_return"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/current_nav_bf" />
<TextView
android:id="#+id/fund_performance_bf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="#string/mutualfundfrag_iclbf_fund_performance"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/current_return_bf" />
<TextView
android:id="#+id/fund_name_gf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="28dp"
android:text="#string/mutualfundfrag_bcbiclgf_title"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/fund_performance_bf" />
<TextView
android:id="#+id/fund_definition_gf"
android:layout_width="315dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="#string/mutualfundfrag_bcbiclgf_definition"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/fund_name_gf" />
<TextView
android:id="#+id/current_nav_gf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="#string/mutualfundfrag_iclbf_current_nav"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/fund_definition_gf" />
<TextView
android:id="#+id/current_return_gf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="#string/mutualfundfrag_iclbf_current_return"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/current_nav_gf" />
<TextView
android:id="#+id/fund_performance_gf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="#string/mutualfundfrag_iclbf_fund_performance"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/current_return_gf" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
Here is the parent activity where the async task is there and the fragment is going to replaced:
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
try {
JSONArray resultJsonArray = new JSONArray(result);
ArrayList<FundMaster> fundsData=new ArrayList<FundMaster>();
for(int i=0;i<resultJsonArray.length();i++){
JSONObject jsonObject= (JSONObject) resultJsonArray.get(i);
fundsData.add(new FundMaster(Integer.valueOf(jsonObject.get("f_id").toString()),
Integer.valueOf(jsonObject.get("fund_id").toString()),
jsonObject.get("fund_name").toString(),
jsonObject.get("fund_definition").toString(),
jsonObject.get("fund_date").toString()));
}
for(FundMaster fm:fundsData){
Log.d("Fund Name",fm.getFundName());
Log.d("Fund Launch Date",fm.getFundLaunchDate());
//MutualFunds mf=new MutualFunds();
//View view=fragment.getView();
if(mutualFundFragment!=null) {
if (fm.getFundId() == 1) {
mutualFundFragment.changeBFTexts(fm);
} else if (fm.getFundId() == 2) {
mutualFundFragment.changeGFTexts(fm);
}
} else{
Log.e("Message Error","Error");
}
changefrag(mutualFundFragment);
}
} catch (JSONException e){
Log.e("JSON Error","JSON problem");
}
}
}
public void changefrag(android.support.v4.app.Fragment frag) {
FragmentManager manager = getSupportFragmentManager();
if (!manager.beginTransaction().isEmpty()) {
manager.beginTransaction().detach(frag);
}
manager.beginTransaction()
.replace(R.id.fragment_mutual_funds, frag).commit();
}
As far I understand, Static Fragment cannot be replaced. Can anyone suggest me what should I do in this case? Thanks in advance.

No adapter attached; skipping layout ,while displaying a list using recycler VIew

I know this question was asked before but even after looking for all the answer
I couldn't find anything relevant. I am basically trying to display a list of items inside a fragment using recycler view, but it saysNo adapter attached; skipping layout even though I have attached an adapter.
Note: I am using a Tab Layout where there are three tabs and a fragment inside each Tab. I am trying to display the recycler view list in one of the fragment.
Here is my Adapter class:
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongViewHolder> {
ArrayList<SongData> songList;
public SongAdapter(ArrayList songList) {
this.songList = songList;
}
//Getting hold of each item of the RecyclerView
public static class SongViewHolder extends RecyclerView.ViewHolder {
ImageView albumArt;
TextView Title,Artist;
public SongViewHolder(View itemView) {
super(itemView);
albumArt = (ImageView)itemView.findViewById(R.id.AlbumImage);
Title= (TextView)itemView.findViewById(R.id.Title);
Artist = (TextView)itemView.findViewById(R.id.Artist);
}
}
#Override
public SongViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.music_tiles,parent,false);
SongViewHolder svh= new SongViewHolder(view);
return svh;
}
#Override
public void onBindViewHolder(SongViewHolder holder, int position) {
SongData songData = songList.get(position);
holder.Title.setText(songData.Title);
holder.Artist.setText(songData.Artist);
holder.albumArt.setImageResource(songData.ImageId);
}
#Override
public int getItemCount() {
return songList.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Fragment code:
public class musicFrag 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;
public musicFrag() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static musicFrag newInstance(String param1, String param2) {
musicFrag fragment = new musicFrag();
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) {
View view = inflater.inflate(R.layout.fragment_music, container, false);
//Initializing RecyclerView , SongAdapter, LinerLayoutManager
SongData songData =new SongData();
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager( new LinearLayoutManager(getActivity()));
SongAdapter songAdapter = new SongAdapter(songData.InitializeData());
recyclerView.setAdapter(songAdapter);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
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 {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Fragment layout:
<android.support.constraint.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:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dannproductions.musify.MainActivity$PlaceholderFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
SongData Class :
public class SongData {
String Title,Artist;
int ImageId;
public SongData() {
};
public SongData(String title, String Artist, int ImageId) {
this.Title = Title;
this.Artist = Artist;
this.ImageId = ImageId;
}
ArrayList<SongData> songList;
public ArrayList<SongData> InitializeData(){
songList = new ArrayList<SongData>();
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
return songList;
}
}
Here is the RecyclerView item layout:
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/AlbumImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginEnd="10dp"
android:src="#drawable/round"
app:civ_border_color="#d35400"
app:civ_border_width="4dp" />
<TextView
android:id="#+id/Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="30dp"
android:layout_toEndOf="#id/AlbumImage"
android:text="TextView"
android:textSize="25sp" />
<TextView
android:id="#+id/Artist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Title"
android:layout_centerHorizontal="true"
android:layout_toEndOf="#id/AlbumImage"
android:text="TextView" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I pasted your adapter and recyclerview code in my android studio. and i found no bug in your list filling code. Here is how your list looks.
So double check your tablayout and fragment code if you are having some issue.

Categories

Resources