Sveiny Sveiny - 25 days ago 12
Java Question

How can I navigate from fragment to fragment on button click

I have a few diffrent fragments in my app. In my

HelpFragment
I have a
Button
. What I'm trying to do is that when user press that
Button
then I want them to be navigated to the
ContactFragment
instead.

This is the code I've tried. This code here is crashing my application so clearly it is something wrong here. This code is located in my
MainActivity.java


Button GoToContact=(Button)findViewById(R.id.btnGoToContact);
GoToContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
HelpFragment HelpFragment = new HelpFragment();
FragmentManager manager1 = getSupportFragmentManager();
manager1.beginTransaction().replace(R.id.relativelayout_for_fragment,
HelpFragment,
HelpFragment.getTag()
).commit();
}
});


So I have one layout for each and every
Fragment
. So on my
fragment_help
layout is where the button is located. So I want to move them from
fragment_help
over to
fragment_contact


My code from the fragment_help.xml (Layout)

<Button
android:text="Go to contact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnGoToContact"
style="@android:style/Widget.Button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="GoToContact"/>


This is my code on the HelpFragment

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class HelpFragment extends Fragment {


public HelpFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_help, container, false);
}


This is also how my
ContactFragment
look like. This is the automatic generated code when I created the
Fragment
.

Here is the error when I load the app up!

--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sveinung.clock, PID: 2304
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sveinung.clock/com.sveinung.clock.MainActivity}: java.lang.NullPointerException:
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.sveinung.clock.MainActivity.onCreate(MainActivity.java:50)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)


This is my whole
MainActivity.java


public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

final View rootView = inflater.inflate(R.layout.fragment_help, container, false);
final Button goToContact = (Button) rootView.findViewById(R.id.btnGoToContact);

goToContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
HelpFragment HelpFragment = new HelpFragment();
FragmentManager manager1 = getSupportFragmentManager();
manager1.beginTransaction().replace(R.id.relativelayout_for_fragment,
HelpFragment,
HelpFragment.getTag()
).commit();
}
});

return rootView;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

ClockFragment clockFragment = new ClockFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.relativelayout_for_fragment,
clockFragment,
clockFragment.getTag()
).commit();


}

@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();

if (id == R.id.nav_clock) {
ClockFragment clockFragment = new ClockFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.setCustomAnimations(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_from_left)
.replace(R.id.relativelayout_for_fragment,
clockFragment,
clockFragment.getTag()
).commit();

} else if (id == R.id.nav_world_clock) {
Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();

/*WorldClockFragment worldClockFragment = new WorldClockFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.setCustomAnimations(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_from_left)
.replace(R.id.relativelayout_for_fragment,
worldClockFragment,
worldClockFragment.getTag()
).commit();*/

} else if (id == R.id.nav_timer) {
Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_stopwatch) {
Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_alarm) {
Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_help) {
//Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();

HelpFragment HelpFragment = new HelpFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.setCustomAnimations(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_from_left)
.replace(R.id.relativelayout_for_fragment,
HelpFragment,
HelpFragment.getTag()
).commit();

} else if (id == R.id.nav_contact) {
//Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();

ContactFragment contactFragment = new ContactFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.setCustomAnimations(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_from_left)
.replace(R.id.relativelayout_for_fragment,
contactFragment,
contactFragment.getTag()
).commit();

} else if (id == R.id.nav_about) {
Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();
}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}


}

 

Answer

This block of code:

    Button GoToContact=(Button)findViewById(R.id.btnGoToContact);
        GoToContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HelpFragment HelpFragment = new HelpFragment();
                FragmentManager manager1 = getSupportFragmentManager();
                manager1.beginTransaction().replace(R.id.relativelayout_for_fragment,
                        HelpFragment,
                        HelpFragment.getTag()
                ).commit();
            }
        });

Needs to be inside of onCreateView(). You inflate your layout in onCreateView(), find any child Views and return your inflated layout. I.e.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.fragment_help, container, false);
    final Button goToContact = (Button) rootView.findViewById(R.id.btnGoToContact);

    goToContact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HelpFragment HelpFragment = new HelpFragment();
            FragmentManager manager1 = getSupportFragmentManager();
            manager1.beginTransaction().replace(R.id.relativelayout_for_fragment,
                    HelpFragment,
                    HelpFragment.getTag()
            ).commit();
        }
    });

    return rootView;
}

Give that a try.