I am trying to add a fragment to an existing layout from within the onClick method of a button in another Fragment class..
In my MainActivity I add two fragments to the layout..
public class MainActivity extends AppCompatActivity {
private Collapsebutton_Fragment cbut_frag;
private ColourView_Fragment cvw_frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbut_frag = new Collapsebutton_Fragment();
cvw_frag = new ColourView_Fragment();
//ColourView Fragment ready
//CollapseButton Fragment ready
getSupportFragmentManager().beginTransaction()
.add(R.id.container_mainactivity, cbut_frag)
.add(R.id.container_mainactivity, cvw_frag)
.commit();
}
}
One of the added fragments contains a button. When clicking that button - accessing the onClick method of the button - I want to add another fragment..
My code is the following:
public class ColourView_Fragment extends Fragment {
FragmentManager fragmentManager;
ThreeButton_Fragment tbt_fragment;
public ColourView_Fragment(){}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.colourview_fragment, container, false);
FrameLayout frameLayout = (FrameLayout)rootView.findViewById(R.id.ColourView);
frameLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.add(R.id.container_mainactivity, tbt_fragment)
.commit();
}
});
return rootView;
}
I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
There is an error in line
.add(R.id.container_mainactivity, tbt_fragment)
How can I correct?
You haven't initialized tbt_fragment in ColourView_Fragment
Related
i use tab layout matching this tutorial:
tab layout tutorial androidhive
It works fine, but when I add a button to fragment_one.xml , i cant use setOnClickListener for this button Because findViewById not work in MainActivity.java
the MainActivity bellow code:
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
the app stopped with this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener' on a null object reference
Where should the button be defined and setOnClickListener?
Even though a fragment is hosted by an activity, it has its own layout (which is contained in the activity's layout) and therefore you'll have to define the fragment's view in its java class.
In most cases, a fragment would have its own Java class for you to manage and manipulate it, so in your case, it should look like this:
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_one, container, false);
Button button=view.findViewById(R.id.myButtonInFragment);
return view;
}
}
If you'd like to access this button from its parent activity, you can achieve it by making the button public:
public class OneFragment extends Fragment{
public Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_one, container, false);
button=view.findViewById(R.id.myButtonInFragment);
return view;
}
}
and then, access it using the fragment's instance in your activity:
OneFragment myFragment=new OneFragment();
After you have attached the fragment to the activity, you can use:
myFragment.button.setClickEnabled(false);
However, accessing fragment's children outside of the fragment is not recommended, and you should avoid it if you can.
public class MainActivity extends AppCompatActivity {
Button button;
Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new Fragment();
View view = fragment.getView();
if (view !=null) {
view.findViewById(R.id.button);
}
}
}
I am developing an Android application. I have a requirement like there is a button in fragment 1, when a user clicks that button result should be displayed in fragment 2. While loading the activity both fragments is attached. Here is my try:
In main activity:
public void dsp(String str) {
secondfragment f2=new secondfragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
f2.setArguments(bundle);
}
In first fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragone, container,false);
Button btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
m.dsp("clicked");
}
});
return v;
}
In second fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragtwo, container,false);
tv= (TextView) v.findViewById(R.id.textView1);
tv.setText(this.getArguments().getString("name"));
return v;
}
When communicating from Fragment to Fragment you use an interface to pass data to the Activity which in turn updates the fragment you want to change.
For Example:
In Fragment 1:
public class FragmentOne extends Fragment{
public Callback mCallback;
public interface Callback{
void onUpdateFragmentTwo(String message);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
mCallback = (Callback) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragone, container,false);
Button btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onUpdateFragmentTwo("clicked");
}
});
return v;
}
}
then in main Activity implement the interface:
public class MainActivity extends AppCompatActivity implements Callback{
FragmentTwo fragmentTwo;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ... Load views or perform logic
// ... Load Fragment Two into your container
if(savedInstanceState == null){
fragmentTwo = FragmentTwo.newInstance(new Bundle()); // use real bundle here
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_holder, fragmentTwo, "Frag2").commit();
}
}
// Interface method
#Override
public void onUpdateFragmentTwo(String message){
// Call activity method with the argument
if(fragmentTwo != null){
fragmentTwo.updateFragmentTwo(message);
}
}
}
Update
In your second fragment I typically use a static newInstance(Bundle args) method to initialize and then would use a public method to communicate from the Activity to the Fragment for example:
public class FragmentTwo extends Fragment{
public static FragmentTwo newInstance(Bundle args){
FragmentTwo fragment = new FragmentTwo();
fragment.setArguments(args);
return fragment;
}
//... Class overrides here onCreateView etc..
// declare this method
public void updateFragmentTwo(String updateText){
// .. do something with update text
}
}
Thats it, happy coding!
Here you have what the Android Documentation says about Communicating Between Fragments. Here you'll have all the necessary steps to make two or more fragments communicate securely :)
i have an activity with 4 fragments from fragment number 1 I want to enable an existing button (that is disable) on fragment 3, when i click in my button in fragment1. this is my attempt:
fragment 1:
public class FragmentEvolucion extends Fragment {
//btnGuardar is in fragment1, the others are in fragment 3 and 4
Button btnGuardar, btnHabilitarMed, btnHabilitarImc;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_evolucion, container, false);
btnGuardar=(Button)rootView.findViewById(R.id.btnGuardarEvolucion);
btnHabilitarMed=(Button)rootView.findViewById(R.id.btnGuardarMedicacion);
btnHabilitarImc=(Button)rootView.findViewById(R.id.btnGuardarDiagnostico);
btnGuardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnHabilitarMed.setEnabled(true);
btnHabilitarImc.setEnabled(true);
}
});
this give me an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
How can i access the button and change it status enabled correctly?
First of all, create a interface.
UpdateButtonListener.java
public interface UpdateButtonListener {
void onUpdate(boolean status);
}
Now in fragment 3, implement interface to class
public class Fragment3 extends Fragment implements UpdateButtonListener{
public static UpdateButtonListener updateButton;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment3, container, false);
updateButton = this;
return view;
}
#Override
public void onUpdate(boolean status) {
// here set the functionality of button whether to disable or not .
if(status){
btnHabilitarMed.setEnabled(true);
btnHabilitarImc.setEnabled(true);
}
}
}
Now in first fragment.
btnGuardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment3.updateButton.onUpdate(true);
}
Like-wise do for other's.
i have two fragments, i want use callback using interface to change imageview
in first fragment from the second fragment but when callback is fired its get imageview null and i get the below error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ImageView.setImageResource(int)' on a null object
reference
first fragment:
public class firstfragment extends Fragment implements MyProfileCallback
{
Imageview myprofile_image;
public firstfragment()
{
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootview = inflater.inflate(R.layout.fisrt, container, false);
myprofile_image=(ImageView) rootview.(find.id.myprofile_image);
/
...
/
}
#Override
public void callbackCall()
{
myprofile_image.setImageResource(R.drawable.profile_friends);
}
}
second fragment:
public class secondfragment extends Fragment
{
MyProfileCallback mcallback;
public secondfragment()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootview = inflater.inflate(R.layout.second, container, false);
mcallback.callbackCall();
return rootview;
}
interface
public interface MyProfileCallback
{
void callbackCall();
}
Your question is kind of hard to understand so is your code, BUT, I think you should load the resource file in this case R.drawable.profile_friends
when the fragment view has being created
You can:
EDIT:
You are calling your callback from the onCreateView method meaning your mypfile_image view does not have a reference to your element yet
and you get a null pointer exception
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mcallback.callbackCall();
}
calling fragment method from activity returns null object reference, why ?
Fragment:
private RelativeLayout waitingForTerminal;
private RelativeLayout blackContent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.waiting_for_terminal, container, false);
setViews(rootView);
return rootView;
}
private void setViews(View view){
waitingForTerminal = (RelativeLayout) view.findViewById(R.id.waiting_for_terminal);
blackContent = (RelativeLayout) view.findViewById(R.id.blank_content);
}
public void hideWaitingForTerminal(){
waitingForTerminal.setVisibility(View.INVISIBLE);
blackContent.setVisibility(View.VISIBLE);
}
MainActivity:
public void run() {
WaitingForTerminalFragment fragment = new WaitingForTerminalFragment();
fragment.hideWaitingForTerminal();
showToast(terminalConnectionEvent.getTerminalInformation().getSerialNumber());
}
Here is how I solved it.
Fragment:
public void hideWaitingForTerminal(View view) {
RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.waiting_for_terminal);
relativeLayout.setVisibility(RelativeLayout.GONE);
}
MainActivity:
private void changeWaitingForTerminalLayout(WaitingForTerminalFragment waitingForTerminalFragment){
waitingForTerminalFragment.hideWaitingForTerminal(this.findViewById(R.id.terminal).getRootView());
}
try by giving the refrence :
WaitingForTerminalFragment fragment = (WaitingForTerminalFragment)getFragmentManager().findFragmentById(R.id.youfragmentid);
fragment.<specific_function_name>();
By only creating object of that fragment will not call the oncreateview of that fragment class where your view is initialized. This is reason the view inside your fragment method returns null.
Call your fragment method from Activity in this way, it worked for me
YourFragment yourFragment = (YourFragment)getSupportFragmentManager().getFragments().get(0);
yourFragment .yourmethod();
Here 0 is your fragment position.