calling a fragment from fragment - android

I want to call another fragment from the current fragment on the click of the button in the current fragment.
Here is my Mainactivity :
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.asd.fragments.RecommendationsFragment;
import com.asd.ibitz4college.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.TrendingFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).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();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
if (id == R.id.search_colleges) {
// Handle the Search Colleges action
fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();
}
else if (id == R.id.search_consultancies) {
fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();
}
else if (id == R.id.search_coaching) {
fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();
}
else if (id == R.id.my_recommendations) {
fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();
}
else if (id == R.id.trending) {
fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();
} else if (id == R.id.profile) {
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is one of my fragment :
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.asd.k4c.R;
public class SearchCoachingFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_search_coaching,container,false);
return rootview;
}
} //Update code formatting
Suppose I want to call resultsfragment from the above fragment on the click
of a button whose id is btn_search, then what should I do?
I tried some already existing answers here, no luck!
P.S: I'm a starter to the world of android dev.

For doing a fragment transaction.Please do the following.
Eg..
A and B are fragments.
Currently A is visible to the User. If you want to do a transaction.
Just create as like below
B b = new B();
((YourActivity)getActivity).setnewFragment(b,true);
public void setNewFragment(Fragment fragment,boolean addbackstack) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_content, fragment);
if (addbackstack)
transaction.addToBackStack(title);
transaction.commit();
}

Use an interface to communicate between fragments. For example
public YourFirstFragment extends Fragment {
public interface FragmentCallBack {
void callBack();
}
private FragmentCallBack fragmentCallBack;
public void setFragmentCallBack(FragmentCallBack fragmentCallBack) {
this.fragmentCallBack = fragmentCallBack;
}
private void callThisWhenYouWantToCallTheOtherFragment(){
fragmentCallBack.callBack();
}
}
Then in You activity
private void setCallToFragment{
yourFirstFragment.setFragmentCallBack(new FragmentCallBack(){
void callBack(){
yourSecondFragment.doWhatEver();
}})
}

First you need to create an interface which defines methods that will be used by your fragment to invoke code from the respective activity it is attached to
public interface OnFragmentInteractionlistener {
// the method that you call from your fragment,
// add whatever parameter you need in the implementation of this
// method.
void onClickOfMyView();
}
once you have created the interface, implement it any and all activities that use this fragment.
public class MainActivity extends AppCompatActivity
implements OnMyFragmentInteractionListener {
#Override
public void onClickOfMyView() {
// DO your on click logic here, like starting the transaction
// to add/replace another fragment.
}
}
Then in the onAttach of your fragment to an activity be sure to check if the attaching activity implements this interface, else throw a RunTimeException like so
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMyFragmentInteractionListener) {
mListener = (OnMyFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnMyFragmentInteractionListener");
}
}
Here mListener is a interface reference you hold in your fragment class through which you invoke the onClickOfMyView() method when actually the click happens
Your fragment class where the view's click code is there.
myView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mListener.onClickOfMyview();
}
});

You should create some method in your activity. Supposedly it will look like this :
public void startFragment(Fragment fragment) {
fm.beginTransaction().replace(R.id.content_frame,new fragment).commit();
}
As you already done in youronNavigationItemSelected
Then, from your fragment, you can call
((MainActivity)getActivity()).startFragment(new SearchConsultanciesFragment())
for example

Create a method switchFragment in your MainActivity
FragmentTransaction ft;
public void switchFrag() {
try {
ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, new Your_Fragment.class);
ft.commit();
} else {
Log.e("test", "else part fragment ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Now from your current Fragment you can call this MainActivity's funciton throught the below code:
((MainActivity)getActivity()).switchFrag();
Let me know if this works for you! :)

Related

how to minimize the map in the google maps activity? [duplicate]

I am relatively new to Coding but please bear with me. I am trying to put a Google Map in a navigation drawer. I figured the best way is to use fragments but despite my various attempts I keep getting this error: "Error:(35, 62) error: incompatible types: MapsActivity cannot be converted to Fragment".
I have two Activities
1. MainActiyity: where there's an error.
2. MapsActivity: which is the default Activity when choosing to create google maps app on Android studio new project creation.
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set to start with fragment
MapsActivity fragment = new MapsActivity();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.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();
}
});
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.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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();
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_building) {
MapsActivity fragment = new MapsActivity();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_map) {
} else if (id == R.id.nav_timetable) {
} else if (id == R.id.nav_noticeboard) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_placeholder) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Also, the word 'fragment' in fragmentTransaction.replace(R.id.fragment_container, fragment);
is underlined red.
I have tried to find different tutorials and guides but nothing solved my issue.
You can't do a FragmentTransaction with an Activity.
In order to use a Google Map in a NavigationDrawer, use a Fragment that extends SupportMapFragment, and add all of the functionality that your MapsActivity class currently has.
Use this to start with:
public class MapsFragment extends SupportMapFragment
implements OnMapReadyCallback {
GoogleMap mGoogleMap;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
}
Then in the Activity, change this to use the Fragment:
// Set to start with fragment
MapsFragment fragment = new MapsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();

How to switch between fragments using button under navigation activity

I'm just new on Android Studio so please bear with me. I created two fragments named locate_before and locate_after. I have a button with an id of trigger on my locate_before fragment. I want to switch to locate_after after clicking that button.
Here's my main activity. I used a frame container for my fragments. I already created a code for what I want named onSelectFragment but it does not work. It says "method onSelectFragment is never used"
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Button trigger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
locate_before fragment = new locate_before();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction(); //check this out
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void onSelectFragment(View v){
Fragment newFragment;
if(v == findViewById(R.id.trigger)){
newFragment = new locate_after();
}
else{
newFragment = new locate_before();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.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_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
locate_before fragment java that ofc extends Fragment
public locate_before () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_locate_before, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
locate_before xml file button
<Button
android:id="#+id/trigger"
android:layout_width="284dp"
android:layout_height="58dp"
android:text="View Car's Location"
android:layout_marginRight="24dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.633"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="133dp" />
locate_after java
public class locate_after extends Fragment {
public locate_after () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_locate_after, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
Thank you!
Your buttom seems to have no onClickListener.
Add android:onClick="onSelectFragment" in your XML or bind your Button and add an onClickListener in your OnCreate.
use onNavigationItemSelected() to navigate to fragment. below is the examples code
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
if (id == R.id.nav_home) {
Fragment homeFragment = new HomeFragment();
fragmentManager.beginTransaction().replace(R.id.relative_layout_fragment1, homeFragment, homeFragment.getTag()).commit();
} else if (id == R.id.nav_logout) {
Toast.makeText(mContext, "logout", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
You have uncommited transaction after your onCreate()
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction(); //check this out
First of all, you are never using method OnSelectFragment().
In your OnCreate method add following
trigger = (Button) findViewById(R.id.trigger); //get Button
trigger.setOnClickListener(new View.OnClickListener() { // action to do when button is pressed
#Override
public void onClick(View view) {
if(before)
onSelectFragment(new locate_after());
else
onSelectFragment(new locate_before());
before = !before; //this makes it a switch
}
});
Declare attribute "before" along other attributes
boolean before = true;
And change your onSelectFragment method to following
public void onSelectFragment(Fragment newFragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Check current displayed fragment and set your desired fragment accordingly. Try the below code.
Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container);
if(!(fragment instanceof locate_before)) {
newFragment = new locate_after();
}
else{
newFragment = new locate_before();
}
getSupportFragmentManager().beginTransaction().replace(newFragment).commit();

handling the back button to go to HomeFragment?

navigation drawer, handling the back button to go to HomeFragment
This is SecurityFragment
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class SecurityFragment extends Fragment {
public SecurityFragment() {
// 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_security, container, false);
}
}
This is the HomeFragment (When onBackPressed i just want the user to be directed to the homepage)current situation is that on onBackPressed the running application is destroyed
package sampleapp.razen.com.sampleapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.widget.Toast;
public class Menu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
android.app.Fragment fragment = new MenuFragment(); // create a fragement object
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
//this the email icon on the home page
#Override
public void onClick(View view) {
String myEmail[]={"john#balloonventures.com"};
Intent sendMail = new Intent(Intent.ACTION_SEND);
sendMail.putExtra(Intent.EXTRA_EMAIL,myEmail);
sendMail.putExtra(Intent.EXTRA_SUBJECT,"(Type your subject)");
sendMail.setType("plain/text");
//incase you have to add something else put here
sendMail.putExtra(Intent.EXTRA_TEXT,"Your phone:+2547");
startActivity(sendMail);
}
});
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//taxi module
public void taxi_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.Taxi.class);
startActivity(timer);}
//host home module
public void hosthome_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.MainActivity.class);
startActivity(timer);}
//calling enterprenuers module
public void enter_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.SectionListView.class);
startActivity(timer);}
//calling UKV/ICV
public void ukvicv_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.UkvIcv_Home.class);
startActivity(timer);}
public void finacial_id(View view){
Intent finacial=new Intent(this,sampleapp.razen.com.sampleapp.FinacialHomePage.class);
startActivity(finacial);}
#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 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);
}
public void displayView(int viewId) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (viewId) {
case R.id.nav_12wks_program:
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.ExpandableListMainActivity.class);
startActivity(timer);
break;
case R.id.nav_emergency_contact:
Intent flow=new Intent(this,sampleapp.razen.com.sampleapp.EmergencyContact.class);
startActivity(flow);
break;
case R.id.nav_survey:
fragment = new SurveyFragment();
title = "Survey";
break;
case R.id.nav_psld:
fragment = new PsldFragment();
title = "Psld";
break;
case R.id.nav_security:
fragment = new SecurityFragment();
title = "All Volunteers Mu";
break;
case R.id.nav_ukv:
fragment = new UkvKiswaFragment();
title = "Ukv's kiswahili";
break;
case R.id.nav_agreement:
fragment = new AgreementFragment();
title = "Agreement ";
break;
case R.id.nav_njoro_geo:
fragment = new GeoNjoroFragment();
title = "Njoro Geography ";
break;
}
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
// set the toolbar title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
} #SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displayView(item.getItemId());
return true;
}
}
Add your fragment transection to Fragment Backstack befor commit
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.addToBackStack( "tag" );
ft.commit();

Navigation drawer not navigating to the fragment from MainAcvtivity

MainActivity.java
package piestudio.opinion;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.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();
}
});
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#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) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
int id = item.getItemId();
if (id == R.id.toi) {
FragmentOne FragmentOne = new FragmentOne();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.content_frame,FragmentOne,"Times of India")
.commit();
drawer.closeDrawer(navigationView);
} else if (id == R.id.thehindu) {
} else if (id == R.id.support) {
}
return true;
}
}
I want to navigate to the fragmentOne.java
package piestudio.opinion;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
/**
* Created by jene on 7/4/2016.
*/
public class FragmentOne extends Fragment{
Activity MainActivity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
MainActivity= activity;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final NavigationView navigationView = (NavigationView)getView().findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener(){
public boolean onNavigationItemSelected(MenuItem Item){
int id = Item.getItemId();
if( id == R.id.toi) {
DrawerLayout drawer = (DrawerLayout)getView().findViewById(R.id.drawer_layout);
FragmentOne FragmentOne = new FragmentOne();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.content_frame,FragmentOne,"Times of India")
.commit();
drawer.closeDrawer(navigationView);
}
DrawerLayout drawer = (DrawerLayout)getView().findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
);
}
}
I have 3 options in my navigation drawer and I want to move to the fragment to respective options of navigation from Main activity but my app is not doing that .
When I click first option of navigation drawer the entire app exit automatically
LOGCAT
ion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at piestudio.opinion.FragmentOne.onCreate(FragmentOne.java:36)
at android.app.Fragment.performCreate(Fragment.java:1673)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:854)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
at android.app.BackStackRecord.run(BackStackRecord.java:682)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Try this once. Call getSupportFragmentManager() instead of getFragmentManager():
for e.g.
FragmentManager fragmentManager = getSupportFragmentManager();
Try this code to open a new fragment when click on item of navigation menu.
/**
* Insert new fragment.
*
* #param fragment
* #param position
*/
#SuppressLint("NewApi")
private void initFragment(Fragment fragment, int position) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (fragment != null) {
// Replace current fragment by this new one
//ft.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_in_right, R.anim.enter_from_right, R.anim.exit_in_left);
ft.addToBackStack(fragment.getClass().getName());
ft.replace(R.id.main_content_fragment, fragment, position + "");
ft.commit();
}
}
Call this method like this:
FragmentOne FragmentOne = new FragmentOne();
initFragment(FragmentOne, position);

Null Pointer Exception calling fragments [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I want to call another fragment from the current fragment on the click of the button in the current fragment.Based on answers I got here, calling a fragment from fragment.
My revised code is as follows :
Here is my Mainactivity :
package com.kibitz4college.k4c;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.asd.fragments.RecommendationsFragment;
import com.asd.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.SearchResultsFragment;
import com.asd.fragments.TrendingFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SearchCoachingFragment.searchbtnclickedlistner {
#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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).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();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
if (id == R.id.search_colleges) {
// Handle the Search Colleges action
fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();
}
else if (id == R.id.search_consultancies) {
fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();
}
else if (id == R.id.search_coaching) {
fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();
}
else if (id == R.id.my_recommendations) {
fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();
}
else if (id == R.id.trending) {
fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();
} else if (id == R.id.profile) {
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void showresults() {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new SearchResultsFragment()).commit();
}
}
Here is one of my fragment from which I'm trying to call another :
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.kibitz4college.k4c.R;
public class SearchCoachingFragment extends Fragment {
Button search_coll_btn;
searchbtnclickedlistner searchbtnclickedlistner_var;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.fragment_search_coaching, container, false);
search_coll_btn = (Button) rootview.findViewById(R.id.Search_coaching_btn );
search_coll_btn.setOnClickListener(new View.OnClickListener() {
TextView lite=(TextView) rootview.findViewById(R.id.textView3);
#Override
public void onClick(View v) {
searchbtnclickedlistner_var.showresults();
}
});
return rootview;
}
public interface searchbtnclickedlistner
{
public void showresults();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
searchbtnclickedlistner_var=(searchbtnclickedlistner)context;
}
catch(Exception e){
throw new RuntimeException(context.toString()+ " must implement OnMyFragmentInteractionListener");
}
}
}
I've implemented interface & Overridden in the mainactivity, now I get a nullpointer exception as follows:
java.lang.NullPointerException: Attempt to invoke interface method
void com.asd.fragments.SearchCoachingFragment$searchbtnclickedlistner.showresults() on a null object reference.
can someone please tell me what I'm doing wrong?
You are calling a method from the interface and that interface is null. You should implement that interface in another class for the callback. Also you should create the interface outside the fragment for a better structure.
The problem could be caused from the fact, you don't put replaced/removed Fragment in the backstack, calling the method addToBackStack().
If you do not call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and will be resumed if the user navigates back.
So when you try to use a method of a replaced/removed Fragment you have NullPointerException. This is the link.

Categories

Resources