Is it possible to add On Click Button method in a Fragment? - button

i have added a button in a xml file ..now i want to open it in fragment ..
i am trying to show share option on button click but not findViewbyid working nor anything happen when click on button after RUN..
May be this is the code for sharing.. I am Confused..Please Help
I have Tried My Best..Any Help Will be Appreciated..Thanks to All Experts
(XML Files)
activity_main :
<?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=".MainActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation"
/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemIconTint="#color/selector_item_gray_color"
app:itemTextColor="#color/selector_item_gray_color"
android:background="#302E2D"
app:menu="#menu/bottom_navigation_android" />
</RelativeLayout>
fragment_more :
<?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:layout_centerInParent="true"
android:background="#fff"
android:gravity="center_horizontal">
<LinearLayout
android:id="#+id/linear1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<androidx.appcompat.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Night Mode"
android:textColor="#color/textcolour"></androidx.appcompat.widget.SwitchCompat>
<Button
android:id="#+id/btn_share"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_marginTop="85dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Share"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<Button
android:id="#+id/btn_option2"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="#+id/btn_share"
android:layout_marginTop="10dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Recommend to friends"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<Button
android:id="#+id/btn_option3"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="#+id/btn_option2"
android:layout_marginTop="10dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Get Free Islamic Apps"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<Button
android:id="#+id/btn_option4"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="#+id/btn_option3"
android:layout_marginTop="10dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Rate and Feedback"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<Button
android:id="#+id/btn_option5"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="#+id/btn_option4"
android:layout_marginTop="10dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Help"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<TextView
android:id="#+id/textview6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Example Text"
android:textSize="12sp"
android:textColor="#000000"/>
</LinearLayout>
</RelativeLayout>
(Java Files)
Main_Activity :
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomnav = findViewById(R.id.bottom_navigation);
bottomnav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home_Fragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem MenuItem) {
Fragment selectedFragment = null;
switch (MenuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new Home_Fragment();
break;
case R.id.nav_settings:
selectedFragment = new More_Fragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
Fragment_More :
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class More_Fragment extends Fragment {
Button btn;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_more, container,false);}
}
Even Tried This Code in Fragment_More But Failed
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class More_Fragment extends Fragment {
private String a = "";
private String b = "";
private LinearLayout linear1;
private Button btn_share;
private TextView textview6;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_more, container,false);}
private void initialize(Bundle _savedInstanceState) {
linear1 = (LinearLayout) getActivity().findViewById(R.id.linear1);
btn_share = (Button) getActivity().findViewById(R.id.btn_share);
textview6 = (TextView) getActivity().findViewById(R.id.textview6);
btn_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _view) {
a = textview6.getText().toString();
b = textview6.getText().toString();
Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
}
});
}
private void initializeLogic() { textview6.setVisibility(View.GONE);
}
}

To reference your Button within your fragment you want to do it in onCreateView:
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_more, container,false);
btn_share = (Button) rootView.findViewById(R.id.btn_share);
btn_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _view) {
a = textview6.getText().toString();
b = textview6.getText().toString();
Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
}
});
return rootView;
}

This Is How Its Done..Thanks A Million All Experts..
Fragment_More.java
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class More_Fragment extends Fragment{
private String a = "";
private String b = "";
private LinearLayout linear1;
private Button btn_sharethis;
private TextView text;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_more, container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btn_sharethis = (Button)view.findViewById(R.id.btn_shareme);
text = (TextView)view.findViewById(R.id.textview61);
btn_sharethis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = text.getText().toString();
b = text.getText().toString();
Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
}
});
}
}

Related

Android Android registration and login with firebase

I have a view (activity_SingIn) and its Presenter now in the onCreate method gives me the following error related to "singInPresenter.singInUser(v);"
2022-09-18 17:30:51.785 3811-3811/com.example.Natour21 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.Natour21, PID: 3811
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.NaTour21.Presenter.Activity.SingInPresenter.singInUser(android.view.View)' on a null object reference
at com.example.NaTour21.View.Activity.activity_singIn$2.onClick(activity_singIn.java:61)
package com.example.NaTour21.Presenter.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.NaTour21.View.Activity.activity_Home;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import android.widget.ProgressBar;
public class SingInPresenter extends AppCompatActivity {
private EditText EmailLgn,PasswordLgn;
String[] messaggio = {"Campi vuoti inserili"};
private ProgressBar progressBar;
public void singInUser(View view) {
String email = EmailLgn.getText().toString();
String password = PasswordLgn.getText().toString();
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
home();
}
}, 3000);
} else {
String error;
try{
throw task.getException();
}catch(Exception e){
error ="Errore di accesso utente";
}
Snackbar snackbar = Snackbar.make(view,error,Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}
}
});
}
public void home() {
Intent intent = new Intent(this, activity_Home.class);
startActivity(intent);
finish();
}
#Override
public void onStart() {
super.onStart();
FirebaseUser UtenteCorrente = FirebaseAuth.getInstance().getCurrentUser();
if(UtenteCorrente != null){
home();
}
}
}
package com.example.NaTour21.View.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import com.example.NaTour21.Presenter.Activity.SingInPresenter;
import com.example.NaTour21.R;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.widget.ProgressBar;
public class activity_singIn extends AppCompatActivity{
private EditText EmailLgn,PasswordLgn;
private Button loginLgn;
private Button registratiLgn;
private SingInPresenter singInPresenter;
private ProgressBar progressbar;
String[] messaggio = {"Campi vuoti inserirli",
"Accesso effettuato con successo",
"Formato email non valido",
"La password deve avere minimo 6 caratteri"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singin);
getSupportActionBar().hide();
initializeComponent();
registratiLgn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity_singIn.this, activity_singUp.class);
startActivity(intent);
}
});
loginLgn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = EmailLgn.getText().toString();
String password = PasswordLgn.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Snackbar snackbar = Snackbar.make(v, messaggio[0], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
} else if (!isValidEmail(email)) {
Snackbar snackbar = Snackbar.make(v, messaggio[2], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}else if (!(password.length() < 6)) {
Snackbar snackbar = Snackbar.make(v, messaggio[3], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}else{
Snackbar snackbar = Snackbar.make(v, messaggio[1], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
singInPresenter.singInUser(v); //??????
}
}
});
}
private boolean isValidEmail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void initializeComponent() {
registratiLgn = findViewById(R.id.btRegistratiLgn);
EmailLgn = findViewById(R.id.tilEmailLgn);
PasswordLgn = findViewById(R.id.tilPasswordLgn);
loginLgn = findViewById(R.id.btLoginLgn);
progressbar = findViewById(R.id.progressbarLgn);
}
}
<?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="match_parent"
android:background="#drawable/sfondo"
android:id="#+id/activity_singin"
android:clickable="true"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="336dp"
android:layout_height="196dp"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/txtNomeApp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:clickable="true"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:text="NaTour21"
android:textColor="#color/white"
android:textSize="60sp" />
</LinearLayout>
<LinearLayout
android:layout_width="361dp"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<EditText
android:id="#+id/tilEmailLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="25dp"
android:drawableLeft="#drawable/ic_email"
android:ems="10"
android:hint="Email"
android:textColor="#color/white"
android:inputType="textEmailAddress"
app:backgroundTint="#color/white"/>
<EditText
android:id="#+id/tilPasswordLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:drawableLeft="#drawable/ic_password"
android:drawableRight="#drawable/ic_occhio"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:textColor="#color/white"
app:backgroundTint="#color/white"/>
<ProgressBar
android:id="#+id/progressbarLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
app:layout_constraintTop_toBottomOf="#id/containerComponents" />
<Button
android:id="#+id/btLoginLgn"
android:layout_width="232dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:background="#drawable/button_login"
android:text="Login"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold"/>
<Button
android:id="#+id/btRegistratiLgn"
android:layout_width="232dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:background="#drawable/button_registrati"
android:text="Registrati"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Dear #Fabiola Salomone if you are trying to use MVP because you said you have a presenter then i am afraid you are not doing it correctly at least according to what i know about MVP please study about it that will be better instead of me or anyone else telling you the code directly because you will not know how it works that way , for a head start you need to make an interface and presenter and inside that presenter you will make three more interfaces View Model and Presenter again and then you will initialize that presenter inside you main activity , here you are extending you presenter with appcompactActivty that itself is wrong a lot about your code is wrong its not MVP by any means so i don't how can i help you exactly with this apart from what i just said, Once you know how MVP work then me or other users can surely help you with this, Still if you need any clearance you can ask :)

Android-Firebase- java.lang.NullPointerException in recyclerView

I am making a tabbed activity with multiple fragments which populate themselves with RecyclerView and the data for this is being retrieved from Firebase Realtime database and Storage as backend.
The error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.visan.peds, PID: 1522
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
at com.example.visan.peds.Landing_mother.getData(Landing_mother.java:76)
at com.example.visan.peds.Landing_mother.onCreateView(Landing_mother.java:43)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1643)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1272)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1646)
at android.view.View.measure(View.java:18991)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2645)
at android.view.View.measure(View.java:18991)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2403)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1342)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1591)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1233)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6552)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:919)
at android.view.Choreographer.doCallbacks(Choreographer.java:710)
at android.view.Choreographer.doFrame(Choreographer.java:645)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:905)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5582)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My Main Activity, Landing.java
package com.example.visan.peds;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class Landing extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout=(TabLayout)findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("CHILD"));
tabLayout.addTab(tabLayout.newTab().setText("MOTHER"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager=(ViewPager) findViewById(R.id.pager);
final Landing_frag_manager frag_manager=new Landing_frag_manager(getSupportFragmentManager(),tabLayout.getTabCount(),Landing.this);
viewPager.setAdapter(frag_manager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
});
}
}
Its layout file, activity_landing.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/main_layout"
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=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
The fragment adapter, Landing_frag_manager.java
package com.example.visan.peds;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class Landing_frag_manager extends FragmentPagerAdapter {
private int num_of_tabs;
Context context;
public Landing_frag_manager(FragmentManager fm, int numOfTabs, Context context){
super(fm);
this.num_of_tabs=numOfTabs;
this.context=context;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Landing_child child=new Landing_child();
return child;
case 1:
Landing_mother mother=new Landing_mother();
return mother;
default:
return null;
}
}
#Override
public int getCount() {
return num_of_tabs;
}
}
Code for Fragment, Landing_mother.java
package com.example.visan.peds;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class Landing_mother extends Fragment {
private List<Ailment> ailments;
private RecyclerView recyclerView;
LinearLayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public Landing_mother(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragment_landing_mother,container,false);
ailments=new ArrayList<>();
getData();
recyclerView =(RecyclerView)view.findViewById(R.id.recyclerView1);
recyclerView.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
return view;
}
private void getData(){
FirebaseDatabase db=FirebaseDatabase.getInstance();
DatabaseReference ref=db.getReference().child("Mother").child("0");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Log.v("SNAPSHOT::",dataSnapshot.toString());
for (DataSnapshot snapshot:dataSnapshot.getChildren()){
Ailment ailment=snapshot.getValue(Ailment.class);
ailments.add(ailment);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
adapter=new LandingAdapter(ailments,getActivity());
recyclerView.setAdapter(adapter);
}
}
Its layout file, fragment_landing_mother.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
The Ailment object class, Ailment.java
package com.example.visan.peds;
public class Ailment {
private String name, image_url;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setImage_url(String image_url){
this.image_url=image_url;
}
public String getImage_url(){
return image_url;
}
}
Adapterfor RecyclerView, LandingAdapter.java
package com.example.visan.peds;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.List;
public class LandingAdapter extends RecyclerView.Adapter<LandingAdapter.ViewHolder>{
private List<Ailment> list;
private Context context;
FirebaseStorage storage;
LayoutInflater inflater;
public LandingAdapter(List<Ailment> list, Context context){
super();
this.list=list;
this.context=context;
inflater=LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.landing_list_row,parent,false);
ViewHolder viewHolder=new ViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Ailment ailment=list.get(position);
StorageReference storageReference=storage.getReferenceFromUrl(ailment.getImage_url());
Glide.with(context).using(new FirebaseImageLoader()).load(storageReference).into(holder.imageView);
holder.textView.setText(ailment.getName());
}
#Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public TextView textView;
public ViewHolder(View view){
super(view);
imageView=(ImageView)view.findViewById(R.id.row_image);
textView=(TextView)view.findViewById(R.id.row_name);
}
}
}
Layout file for Single Row of recyclerView, landing_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/row_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/row_name"
android:layout_below="#+id/row_image"/>
</RelativeLayout>
Your are calling getData(); which is trying to access RecyclerView before it has been initialised. Call it after you finish recycler view initialisation. For example after recyclerView.setLayoutManager(layoutManager);

Android Fragment not showing up in my application

I have a strange issue with my Fragment, I get no errors at runtime (I'm using Android Studio v8.7 and the Gradle compiles just fine) but when my app runs on my phone it's now showing up, it looks like an empty Activity.
Activity.class
package android.bignerdranch.com.criminalintent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.MenuItem;
public class CrimeActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
// These are Fragments from the app.v4 package, it's needed to make the app compatible with API < 11
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if(fragment == null) {
fragment = new Fragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Fragment.class
package android.bignerdranch.com.criminalintent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckbox;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mCrime.setTitle(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
mDateButton.setText(mCrime.getDate().toString());
mDateButton.setEnabled(false);
mSolvedCheckbox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
}
}
Activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"
style="?android:listSeparatorTextViewStyle" />
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_hint" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"
style="?android:listSeparatorTextViewStyle" />
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp" />
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="#string/crime_solved_label" />
</LinearLayout>
Can somebody point me in the right direction and tell me what could solve my issue?
Ok i found the errors, I was instantiating the wrong Fragment.
Instead of
if(fragment == null) {
fragment = new Fragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
It should be
if(fragment == null) {
fragment = new CrimeFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();

Android App Crashes on FragmentTransaction.replace

I'm attempting to create a dynamic UI using the support.v4 library to insert fragments into a framelayout I have defined for my main activity.
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android:id="#+id/button_report"
android:text="#string/button_report"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="#+id/button_pay"
android:text="#string/button_pay"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="#+id/button_contact"
android:text="#string/button_contact"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2" />
</LinearLayout>
And here is the MainActivity.java:
package com.example.Test;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity
{
// Declare button variables
protected Button btnReport;
protected Button btnPay;
protected Button btnContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign buttons
btnReport = (Button)findViewById(R.id.button_report);
btnPay = (Button)findViewById(R.id.button_pay);
btnContact = (Button)findViewById(R.id.button_contact);
// Import fragments
final Fragment fragmentPhone = new FragmentPhone();
final Fragment fragmentReport = new FragmentReport();
final Fragment fragmentPay = new FragmentPay();
final android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
// Check for existing fragment, if none then add FragmentPhone.class
if (savedInstanceState != null) return;
else {
ft.add(R.id.container, fragmentPhone);
ft.commit();
}
// "Report" button
btnReport.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentReport); //Replace the details_container
ft.addToBackStack(null); // Add transaction to back stack
ft.commit(); // Commit the transaction
}
});
// "Pay" button
btnPay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentPay);
ft.addToBackStack(null);
ft.commit();
}
});
// "Contact" button
btnContact.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentPhone);
ft.addToBackStack(null);
ft.commit();
}
});
}
}
And here is my FragmentPhone class:
package com.example.Test;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentPhone extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone, container, false);
}
}
When I launch the app, the xml loads correctly and the framelayout gets filled with fragmentPhone, but pressing any of the buttons creates an "app has stopped unexpectedly" dialogue and prompts me to force close.
Any ideas or suggestions will be greatly appreciated. Thanks!
I ended up re-getting and re-declaring FragmentManager and FragmentTransaction within each onClickListener. I also removed "addToBackStack" as I decided it was unneeded. Here is my current, working code:
// "Report" button
btnReport.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
android.support.v4.app.FragmentManager fragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmentTransaction1.replace(R.id.container, fragmentReport);
fragmentTransaction1.commit();
}
});
(untested)
make ft a global field so it's available in the click handler.

Show/Hide Fragments and change the visibility attribute programmatically

This is a 2 part problem. What I'm having is a 3 Fragment layout where the 3'rd Fragment(FragmentC) is added dynamically when the user taps a button found in another fragment. Then, after it's added the 3'rd Fragment has a button to maximize/minimize it.
UPDATE: Scrool at the end for SOLUTION
PROBLEM 1:
I'm trying to change the visibility attribute of a FrameLayout that acts as a container for the 3'rd fragment(R.id.fragment_C).
What the code is supposed to do is to generate another fragment that, originally has an XML containing android:visibility = "gone". Then, the Fragment is added when tapping a button and the visibility is suppose to change to VISIBLE.
I know this has been covered before, but after 4 hours of trying to make it work I decided to ask what I'm doing wrong.
PROBLEM 2:
After the 3'rd fragment is generated I have a minimize/maximize button that's supposed to hide the first 2 Fragments and allow the 3'rd Fragment to fill the screen.
The problem is the Views of the first 2 Fragments are not removed when using .setVisibility(View.GONE). This has been covered before as well, but I can't figure out why it doesn't work in my code.
The code so far(sorry if it's to verbose but I thought it's better to include all details for you folks):
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:orientation="vertical"
>
<FrameLayout
android:id="#+id/fragment_A"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#CCCCCC"
>
</FrameLayout>
<FrameLayout
android:id="#+id/fragment_B"
android:layout_width="fill_parent"
android:layout_height="300dp"
android:layout_below="#id/fragment_A"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:background="#B4B4B4"
>
</FrameLayout>
<FrameLayout
android:id="#+id/fragment_C"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/fragment_B"
android:layout_centerHorizontal="true"
android:layout_marginTop="0dp"
android:background="#A3A3A3"
android:visibility="gone"
>
</FrameLayout>
</RelativeLayout>
land/main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingLeft="0dp"
android:paddingRight="0dp" >
<LinearLayout
android:id="#+id/fragments_container"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:baselineAligned="false" >
<FrameLayout
android:id="#+id/fragment_A"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.5"
android:background="#CCCCCC" >
</FrameLayout>
<FrameLayout
android:id="#id/fragment_B"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.5"
android:background="#B4B4B4"
>
</FrameLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/fragment_C"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/fragment_container"
android:layout_centerHorizontal="true"
android:layout_marginTop="0dp"
android:background="#A3A3A3"
android:visibility="gone" >
</FrameLayout>
</RelativeLayout>
MainActivity.java
package com.example.android.fragments_proto.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import com.example.android.fragments_proto.R;
import com.example.android.fragments_proto.fragment.GMC_DateSelectionFragment;
import com.example.android.fragments_proto.fragment.GMC_ProdUnitSelectionFragment;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
FragmentManager fm = getSupportFragmentManager();
Fragment fragmentA = fm.findFragmentById(R.id.fragment_A);
Fragment fragmentB = fm.findFragmentById(R.id.fragment_B);
if (fragmentA == null) {
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_A, new FragmentA());
ft.commit();
}
if (fragmentB == null) {
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_B, new FragmentB());
ft.commit();
}
}
}
Now the XML and .java files for the first Fragment.
fragment_A.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
>
<DatePicker
android:id="#+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
FragmentA.java
package com.example.android.fragments_proto.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.Toast;
import com.example.android.fragments_proto.R;
public class FragmentA extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_A, container, false);
DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker1);
datePicker.setCalendarViewShown(true);
datePicker.setSpinnersShown(false);
datePicker.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, "You Touched ME!", Toast.LENGTH_SHORT).show();
}
return false;
}
});
return view;
}
}
Now the XML and .java files for the Fragment that contains the button that when tapped adds the content in R.id.fragment_C
fragment_B.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.1"
>
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="wrap_content">
<Button
android:id="#+id/button"
android:text="#string/btn_fragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
FragmentB.java
package com.example.android.fragments_proto.fragment;
import android.app.Activity;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.example.android.fragments_proto.R;
public class FragmentB extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentB, container, false);
ListView listView = (ListView) view.findViewById(R.id.listView1);
Button button = (Button) view.findViewById(R.id.button);
String[] machines = new String[] { "MachineId-001", "MachineId-002", "MachineId-003", "MachineId-004", "MachineId-005", "MachineId-006", "MachineId-007", "MachineId-008"};
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.select_dialog_multichoice, machines));
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.fragment_C);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = getActivity();
if (activity != null) {
getFragmentManager().beginTransaction().replace(R.id.fragment_C, new FragmentC()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).addToBackStack(null).commit();
frameLayout.setVisibility(View.VISIBLE);
}
}
});
return view;
}
}
The XML and .java files for the Fragment that's supposed to be added.
fragment_C.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="wrap_content">
<Button
android:id="#+id/maximize_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Maximize Me!" />
</LinearLayout>
<TextView
android:id="#+id/text_view"
android:textIsSelectable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF33FF"
/>
</LinearLayout>
FragmentC.java
package com.example.android.fragments_proto.fragment;
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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.android.fragments_proto.R;
public class FragmentC extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_C, container, false);
TextView textView = (TextView) view.findViewById(R.id.text_view);
final Fragment fragmentA = getFragmentManager().findFragmentById(R.id.fragment_A);
final Fragment fragmentB = getFragmentManager().findFragmentById(R.id.fragment_B);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (fragmentA.isVisible() && fragmentB.isVisible()) {
ft.hide(fragmentA);
ft.hide(fragmentB);
fragmentA.getView().setVisibility(View.GONE);
fragmentB.getView().setVisibility(View.GONE);
button.setText("Minimize Me!");
ft.addToBackStack(null);
} else {
ft.show(fragmentA);
ft.show(fragmentB);
fragmentA.getView().setVisibility(View.VISIBLE);
fragmentB.getView().setVisibility(View.VISIBLE);
button.setText("Maximize Me!");
ft.addToBackStack(null);
}
ft.commit();
}
});
return view;
}
}
Found the problem and a solution thanks to Moesio
PROBLEM:
My error was that I was trying to find a view (in FragmentB.java) with
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.fragment_C);
This line was returning null so when the code reached the point where it was supposed to do a .setVisibility() then the app. would return a nullPointerException.
The same happened for FragmentC.java (so my 2 problems were related). The Views were not removed because my findViewById was null!
SOLUTION:
Just search for your View with getActivity.findViewById(R.id.your_view);
In FragmentB you're trying get a view which is not on your contentView
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
// this is in fragment_b layout
ListView listView = (ListView) view.findViewById(R.id.listView1);
Button button = (Button) view.findViewById(R.id.button);
/* ... */
// ****************************************
// this is NOT in fragment_b layout, which causes null
// ****************************************
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.fragment_C);
/* ... */
}
Try:
final FrameLayout frameLayout = (FrameLayout) getActivity().getWindow().findViewById(R.id.fragment_C);
Whereas R.id.fragment_C is inflated and setted on MainActivity.
Moreover, I had the same problem until use an extra flag
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
final Fragment fragmentC = new FragmentC();
fragmentTransaction.add(R.id.fragment_C, fragmentC);
fragmentTransaction.commit();
menuIsOn = false;
final View fragmentCView = findViewById(R.id.fragment_C);
final Button btn = (Button) findViewById(R.id.btn);
btnPowers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!menuIsOn) {
fragmentCView.setVisibility(View.VISIBLE);
} else {
fragmentCView.setVisibility(View.INVISIBLE);
}
menuIsOn = !menuIsOn;
}
});
Create the Instances of fragments and add instead of replace
FragA fa= new FragA();
FragB fb= new FragB();
FragC fc= new FragB();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmnt_container, fa);
fragmentTransaction.add(R.id.fragmnt_container, fb);
fragmentTransaction.add(R.id.fragmnt_container, fc);
fragmentTransaction.show(fa);
fragmentTransaction.hide(fb);
fragmentTransaction.hide(fc);
fragmentTransaction.commit();
suppose we want to to hide and show different fragments based on our action
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(fa);
fragmentTransaction.show(fb);
fragmentTransaction.hide(fc);
fragmentTransaction.commit();

Resources