start fragment from another fragment (Android) - android

i need to start a fragment from another fragment.
i have my MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
//Selecao dos menus
if (menuItem.getItemId() == R.id.nav_reservas) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new Reservas()).commit();
} else if (menuItem.getItemId() == R.id.nav_hotel) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
} else if (menuItem.getItemId() == R.id.nav_check) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new CheckIn()).commit();
} else if (menuItem.getItemId() == R.id.nav_loc) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Endereco()).commit();
} else if (menuItem.getItemId() == R.id.nav_avalie) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Avalie()).commit();
} else if (menuItem.getItemId() == R.id.nav_info) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Informacoes()).commit();
} else if (menuItem.getItemId() == R.id.nav_guia) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new GuiaDaCidade()).commit();
}
return false;
}
}
);
and i start the GuiaDaCidade extends fragment.
public class GuiaDaCidade extends Fragment {
View rootView;
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.guia_da_cidade, null);
View botaoPasseios = (View) rootView.findViewById(R.id.btpasseios);
View botaoAgenda = (View) rootView.findViewById(R.id.btagenda);
botaoPasseios.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
I need that when the button is clicked start the Passeios extends Fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.guia_passeios, null);
expListView = (ExpandableListView) rootView.findViewById(R.id.listaexp);
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
expandeAll();
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
mudaTela(groupPosition, childPosition);
return false;
}
});
return rootView;
}
I already tried everything possible but no way is working.

before you start another fragment, if you want to keep your current fragment into backstack so that it is available when user presses back button, add it to back stack using fragment manager. Then just use the same line: fragmentTransaction.replace(containerView,new Fragment(), TAG).commit();

GuiaDaCidade
botaoPasseios.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Passeios fragment = new Passeios();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.your_guiadacidade_layoutID, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
});

Related

ViewPager crashes when re-opening: NullPointerException SparseArray.get(int)

I've recently switched my ViewPager's adapter from FragmentPagerAdapter to FragmentStatePagerAdapter. However, whenever I return to my ViewPager the app crashes. This was not happening with FragmentPagerAdapter. The Logcat shows:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.util.SparseArray.get(int)' on a null object reference
I'm in that awkward position where I don't know enough to understand what questions I should be asking. All of my searches have turned up nothing useful.
Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.util.SparseArray.get(int)' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:905)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:216)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1455)
at android.view.View.dispatchRestoreInstanceState(View.java:17706)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3745)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3751)
at android.view.View.restoreHierarchyState(View.java:17684)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:415)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1454)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
MainActivity.java
public class MainActivity extends AppCompatActivity
implements FragmentQuiz_Selection_Instruments.QuizSelectionInterface,
FragmentQuiz_Started.OnQuizExit,
FragmentQuiz_Selection_Topics.StartQuizInterface {
private DrawerLayout mDrawerLayout;
private Fragment mQuizFragment;
private Fragment mInstrumentsFragment;
private Fragment mReferenceFragment;
private ArrayList<String> mQuizSelection;
private ViewModel_ForegroundView viewModel;
private BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialise mQuizSelection
mQuizSelection = new ArrayList<String>();
mQuizSelection.clear();
//Initialise bottomNavigationView
bottomNavigationView = findViewById(R.id.navigation_bottom);
//Set Bottom-Navigation icon
bottomNavigationView.getMenu().getItem(1).setChecked(true);
//Initialise ViewModel_ForegroundView
viewModel = ViewModelProviders.of(this).get(ViewModel_ForegroundView.class);
//Initialise ActionBar
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
//Initialise Top-Navigation Drawer
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.navigation_top);
// Set the onClickListener for the NavigationDrawer
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// set item as selected to persist highlight
item.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Handle item clicks
int itemId = item.getItemId();
if (itemId == R.id.nav_top_ww) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_WWind");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_WWind.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_WWind");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_br) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_Brass");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_Brass.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_Brass");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_pp) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_PercPit");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_PercPit.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_PercPit");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_pu) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_PercUnp");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_PercUnp.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_PercUnp");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_sp) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_StrPlu");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_StrPlu.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_StrPlu");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_ky) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_Keys");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_Keys.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_Keys");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_sb) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_StrBow");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_StrBow.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_StrBow");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, mInstrumentsFragment);
transaction.commit();
//Record foreground-fragment change
viewModel.recordForegroundFragment(mInstrumentsFragment);
//Set 'Quiz Exit' button's visibility to 'false,' set Quiz-Ext button.
viewModel.recordQuizBtnStatus(false);
setQuizExtBtn();
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
drawerView.bringToFront();
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}});
// Bottom-Navigation Menu
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.nav_btm_quiz) {
if (mQuizFragment != null) {
String string = mQuizFragment.toString();
if (string.contains("Started") || string.contains("Topics")) {
viewModel.recordQuizBtnStatus(true);
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mQuizFragment);
fragmentTransaction.commit();
//Record foreground-fragment change
viewModel.recordForegroundFragment(mQuizFragment);
} else {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentQuiz_Selection_Instruments");
if (fragment == null) {
mQuizFragment = FragmentQuiz_Selection_Instruments.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mQuizFragment, "FragmentQuiz_Selection_Instruments");
fragmentTransaction.commit();
viewModel.recordForegroundFragment(mQuizFragment);
} else {
mQuizFragment = fragment;
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mQuizFragment);
fragmentTransaction.commit();
viewModel.recordForegroundFragment(mQuizFragment);
}
}
} else if (itemId == R.id.nav_btm_instruments) {
viewModel.recordQuizBtnStatus(false);
if (mInstrumentsFragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mInstrumentsFragment);
fragmentTransaction.commit();
viewModel.recordForegroundFragment(mInstrumentsFragment);
} else {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_WWind");
if (fragment == null) {
mQuizFragment = FragmentInstruments_WWind.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_layout, mQuizFragment, "FragmentInstruments_WWind");
fragmentTransaction.commit();
} else {
mQuizFragment = fragment;
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, fragment);
fragmentTransaction.commit();
}
}
} else if (itemId == R.id.nav_btm_reference) {
viewModel.recordQuizBtnStatus(false);
if (mReferenceFragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mReferenceFragment);
fragmentTransaction.commit();
} else {
mReferenceFragment = FragmentReference.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mReferenceFragment, "FragmentReference");
fragmentTransaction.commit();
}
}
//Set Quiz-Ext button's visibility.
setQuizExtBtn();
//Call 'invalidateOptionsMenu' to set the Quiz-Exit button's visibility.
invalidateOptionsMenu();
return true;
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
/**Display FragmentInstruments_WWind when opening the app for the first time.
* If the app is being resumed, use getForegroundFragment.
*/
if (viewModel.getForegroundFragment() == null) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_WWind");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_WWind.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_WWind");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, mInstrumentsFragment);
transaction.commit();
//Record foreground-fragment change
viewModel.recordForegroundFragment(mInstrumentsFragment);
//Set Quiz-Exit Status
viewModel.recordQuizBtnStatus(false);
//Set 'Reference' icon as checked
bottomNavigationView.getMenu().getItem(1).setChecked(true);
} else if (viewModel.getForegroundFragment() != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment foregroundFragment = viewModel.getForegroundFragment();
transaction.replace(R.id.frame_layout, foregroundFragment);
transaction.commit();
//Record foreground-fragment change, set bottom-navigation icon
viewModel.recordForegroundFragment(foregroundFragment);
String fragment = foregroundFragment.toString();
if (fragment.contains("Quiz")) {
bottomNavigationView.getMenu().getItem(0).setChecked(true);
} else if (fragment.contains("Reference")) {
bottomNavigationView.getMenu().getItem(1).setChecked(true);
} else if (fragment.contains("Help")) {
bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
}
}
#Override
protected void onPause(){
super.onPause();
//Actions onPause
viewModel.recordInstrumentsFragment(mInstrumentsFragment);
}
//Search function handled here
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar, menu);
//Set 'Quiz Exit' button's visibility.
boolean status = viewModel.getQuizBtnStatus();
menu.findItem(R.id.ab_quiz_exit).setVisible(status);
return true;
}
//Handle action-bar button clicks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.ab_quiz_exit:
onQuizExit();
}
return super.onOptionsItemSelected(item);
}
Parent Fragment
public class FragmentInstruments_Brass extends Fragment {
public static FragmentInstruments_Brass newInstance() {
FragmentInstruments_Brass fragment = new FragmentInstruments_Brass();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Fragment screen orientation normal both portrait and landscape
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_instruments, container, false);
//Setting ViewPager for each tab
ViewPager viewPager = view.findViewById(R.id.viewPager_instruments);
tabsToViewPager(viewPager);
//Set tabs inside toolbar
TabLayout tabLayout = view.findViewById(R.id.tabLayout_instruments);
tabLayout.setupWithViewPager(viewPager, false);
return view;
}
//Add Fragments to Tabs
private void tabsToViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
//Brass Fragments
adapter.addFragment(new Inst_Br_Frag1(), "Name1");
adapter.addFragment(new Inst_Br_Frag2(), "Name2");
adapter.addFragment(new Inst_Br_Frag3(), "Name3");
adapter.addFragment(new Inst_Br_Frag4(), "Name4");
adapter.addFragment(new Inst_Br_Frag5(), "Name5");
adapter.addFragment(new Inst_Br_Frag6(), "Name6");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentStatePagerAdapter {
//mFragmentList stores ChildFragments
private final List<Fragment> mFragmentList = new ArrayList<>();
//mFragmentTitleList stores the displayed name of each ChildFragment
private final List<String> mFragmentTitleList = new ArrayList<>();
Adapter(FragmentManager manager) {
super(manager);
}
// Return the Fragment associated with a specified position
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
// getCount() returns the number of views available
#Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
//This method may be called by the ViewPager to obtain a title string to describe the specified page.
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}

i am getting the null pointer exception in adapter

I am using listview to inflate navigation menu. I am getting the above error when
main activity is launched. I am sharing the code of adapter and main activity.
public class DrDrawerListAdapter extends BaseAdapter {
Activity activity;
int[] imageId;
private LayoutInflater inflater = null;
ArrayList<String> titles;
public DrDrawerListAdapter(Activity activity, ArrayList<String> titles, int[] icons){
this.titles= titles;
this.activity = activity;
this.imageId = icons;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return titles.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
View view = inflater.inflate(R.layout.dr_drawer_item, null);
holder.iconView = view.findViewById(R.id.im_icon);
holder.titleView = view.findViewById(R.id.tv_title);
holder.titleView.setText(titles.get(position));
Glide.with(activity.getApplicationContext()).load(imageId[position]).into(holder.iconView);
return view;
}
public class Holder{
ImageView iconView;
TextView titleView;
}
}
*** and here is my mainactivity file
package com.example.azim.qphew.Dr.view.uiactivity;
import butterknife.BindView;
import butterknife.ButterKnife;
public class DrMainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = DrMainActivity.class.getSimpleName();
#BindView(R.id.drawer_layout) DrawerLayout drawerLayout;
//NavigationView navigationView;
#BindView(R.id.toolbar) Toolbar toolbar;
#BindView(R.id.lv_drawer) ListView listView;
#BindView(R.id.dr_profile) ImageButton profileButton;
#BindView(R.id.dr_schedule) ImageButton scheduleButton;
#BindView(R.id.live) ImageButton liveButton;
#BindView(R.id.dr_message) ImageButton messageButton;
#BindView(R.id.dr_logout) ImageButton logoutButton;
private ActionBar actionBar;
ArrayList<String> nav_items;
int[] icons = {R.drawable.time, R.drawable.appointment_history, R.drawable.live_appointment, R.drawable.medicine_reminder,
R.drawable.video, R.drawable.blog, R.drawable.faq, R.drawable.live_appointment};
DrDrawerListAdapter listAdapter;
ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dr_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.app_bar_color)));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DashboardFragment());
ft.commit();
setDrawer();
init();
initClickListener();
}
private void setDrawer(){
if (toggle == null){
toggle = new ActionBarDrawerToggle(DrMainActivity.this,drawerLayout,R.string.open, R.string.close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
}
};
drawerLayout.addDrawerListener(toggle);
}
toggle.syncState();
listAdapter = new DrDrawerListAdapter(DrMainActivity.this, nav_items, icons);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new DrDrawerItemClickListener());
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.live:
setLiveQueue();
break;
case R.id.dr_profile:
setProfile();
break;
case R.id.dr_schedule:
setSchedule();
break;
case R.id.dr_message:
setMessage();
break;
case R.id.dr_logout:
setLogout();
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}switch (item.getItemId()){
default:
return super.onOptionsItemSelected(item);
}
}
private class DrDrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
private void selectItem(int position){
switch (position){
case 0:
setDashBoard();
drawerLayout.closeDrawers();
break;
case 1:
setAppointment();
drawerLayout.closeDrawers();
break;
case 2:
setLiveQueue();
drawerLayout.closeDrawers();
break;
case 3:
setMessage();
drawerLayout.closeDrawers();
break;
case 4:
setVideos();
drawerLayout.closeDrawers();
break;
case 5:
setBlog();
drawerLayout.closeDrawers();
break;
}
}
}
private void initClickListener(){
profileButton.setOnClickListener(this);
scheduleButton.setOnClickListener(this);
liveButton.setOnClickListener(this);
messageButton.setOnClickListener(this);
logoutButton.setOnClickListener(this);
}
private void init(){
nav_items = new ArrayList<>();
nav_items.add("My Account");
nav_items.add("Search");
nav_items.add("Live Appointmet");
nav_items.add("My Appointments");
nav_items.add("Upgrade to Premium");
nav_items.add("FAQ");
nav_items.add("Vedios");
nav_items.add("Blog");
//icons = getResources().getIntArray(R.array.dr_drawer_icons);
}
private void setDashBoard(){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DashboardFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setAppointment(){}
private void setProfile(){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_main, new DrProfileFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setLiveQueue(){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DrLiveQueueFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setVideos(){}
private void setMessage(){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DrMessageFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setLogout(){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_main, new DrLogoutFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setBlog(){}
private void setFaq(){}
private void setContactUs(){}
private void setSchedule() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DrScheduleFragment());
ft.addToBackStack(null);
ft.commit();
}
}
you should initial your array before call setDrawer method
change init() order line with setDrawer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dr_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.app_bar_color)));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DashboardFragment());
ft.commit();
init();
setDrawer();
initClickListener();
}
Call init() before setDrawer method.Before initialising the arraylist you are setting adapter with null
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dr_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new
ColorDrawable(getResources().getColor(R.color.app_bar_color)));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DashboardFragment());
ft.commit();
init();
setDrawer();
initClickListener();

Backstack in Fragment Android

I am working in an application where i am calling Fragment2 from Fragment1, when I am pressing default back button in Fragment2 it is taking me to Fragment1 but when I am pressing any other button and calling getActivity.finish() it is closing my Activity.
I have added the code below:
MainActivity.java
public class MainActivity extends AppCompatActivity {
AHBottomNavigation bottomNavigation;
Fragment selectedFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigation = (AHBottomNavigation) findViewById(R.id.navigation);
AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.home, R.drawable.home, R.color.colorAccent);
AHBottomNavigationItem item2 = new AHBottomNavigationItem(R.string.menu, R.drawable.menu, R.color.colorAccent);
AHBottomNavigationItem item3 = new AHBottomNavigationItem(R.string.cart, R.drawable.cart, R.color.colorAccent);
AHBottomNavigationItem item4 = new AHBottomNavigationItem(R.string.orders, R.drawable.orders, R.color.colorAccent);
AHBottomNavigationItem item5 = new AHBottomNavigationItem(R.string.settings, R.drawable.setting, R.color.colorAccent);
bottomNavigation.addItem(item1);
bottomNavigation.addItem(item2);
bottomNavigation.addItem(item3);
bottomNavigation.addItem(item4);
bottomNavigation.addItem(item5);
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
bottomNavigation.setAccentColor(Color.parseColor("#571e19"));
selectedFragment = ItemHomeFragment.newInstance(bottomNavigation);
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
if (position == 0) {
selectedFragment = ItemHomeFragment.newInstance(bottomNavigation);
} else if (position == 4) {
selectedFragment = Fragment1 (bottomNavigation);
}
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout,selectedFragment);
fragmentTransaction.commit();
return true;
}
});
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, ItemHomeFragment.newInstance(bottomNavigation));
fragmentTransaction.commit();
}
public void setNotification(){
bottomNavigation.setNotification("1", 1);
}
}
Fragment1.java
public class Fragment1 extends Fragment {
public static AHBottomNavigation bottomNavigation1;
TextView txtLogout,txtMyProfile,txtTermsCondition,txtRate;
public int LANGUAGE_REQUEST_CODE = 113;
private SharedPreferences prefs ;
Boolean languageBoolean = true;
MyApplication myApplication;
private UIView uiView = UIView.getInstance();
ProgressDialog pDialog;
static int index;
public static ItemSettingsFragment newInstance(AHBottomNavigation bottomNavigation) {
ItemSettingsFragment fragment = new ItemSettingsFragment();
bottomNavigation1 = bottomNavigation;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
showNotificationCounter(32);
View view = inflater.inflate(R.layout.fragment_settings, container, false);
TextView txtLanguage = (TextView) view.findViewById(R.id.txtLanguage);
txtLanguage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), LanguageActivity.class);
startActivity(intent);
}
});
txtMyProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment fragment2 = new ProfileFragment();
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return view;
}
Fragment2.java
public class Fragment2 extends Fragment{
public Fragment2() { }
public static Fragment newInstance() {
Fragment2 profileFragment = new Fragment2();
return profileFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.language, container, false);
TextView fragment2 = (TextView) view.findViewById(R.id.txtLanguage);
fragment2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
return view;
}
}
Don't
getActivity.finish()
finish() clear the Activity.
Do
popBackStack();
Example
FragmentManager fmOBJ= getFragmentManager();
fmOBJ.popBackStack();

Change fragments with navigation drawer Error

I don't can change the fragment when i click in navigation item. It happens only in my FragmentTwo. The commit results an error and the app is close. Please, someone can help me? Where is the error?
MAIN CODE
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio_admin);
// Implementação do navigation view
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
if(savedInstanceState == null) {
FragmentOne frag1 = new FragmentOne();
FragmentTwo frag2 = new FragmentTwo();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.layoutFundo, frag1, "frag1");
ft.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(toggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentOne frag1 = new FragmentOne();
FragmentTwo frag2 = new FragmentTwo();
FragmentTransaction ft = fm.beginTransaction();
if (item.getItemId() == R.id.nav_menu_1) {
ft.replace(R.id.layoutFundo, frag1, "frag1");
ft.addToBackStack("pilha");
showMessage("IF", "Entrou no if");
Toast.makeText(InicioAdmin.this, "Novo", Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.nav_menu_2) {
ft.replace(R.id.layoutFundo, frag2, "frag2");
ft.addToBackStack("pilha");
showMessage("ELSEIF", "Entrou no Elseif");
Toast.makeText(InicioAdmin.this, "Outro", Toast.LENGTH_SHORT).show();
} else {
ft.replace(R.id.layoutFundo, frag1, "frag1");
ft.addToBackStack("pilha");
showMessage("ELSE", "Entrou no else");
}
ft.commit();
/* switch (item.getItemId()) {
case R.id.nav_menu_1:
break;
case R.id.nav_menu_2:
break;
default:
break;
}*/
DrawerLayout dl = (DrawerLayout) findViewById(R.id.drawerLayout);
if (dl.isDrawerOpen(GravityCompat.START))
dl.closeDrawer(GravityCompat.START);
return false;
}
// Método showMessage
public void showMessage (String title, String message)
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
FRAGMENT ONE CODE
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_one, null);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText("Fragmento 1");
return (view);
}
FRAGMENT TWO CODE
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
/*
View view = inflater.inflate(R.layout.fragment_two, null);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText("Fragmento 2");
*/
return (null);
}
The two classes extends Fragment
I think you are returning null in fragment that's why you are getting error. please add view in fragment and run this. hope it will help.

Fragment Hide do not work

I have created just sample application for fragment hiding and showing.At the first fragment is added into the view properly.But on menu press to hide fragment it don't get hide.I posted my code as follows..
public class SwapfragActivity extends Activity
{
FrameLayout fr;
FragmentManager fm = getFragmentManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fr = (FrameLayout) findViewById(R.id.fm1);
frag f = new frag();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add("SHOW");
menu.add("HIDE");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
frag f = new frag();
if (item.getTitle() == "SHOW")
{
if (!f.isAdded())
{
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fm1, f);
ft.commit();
}
else if (f.isHidden())
{
FragmentTransaction ft = fm.beginTransaction();
ft.show(f);
ft.commit();
}
}
else
{
if (f.isAdded())
{
FragmentTransaction ft = fm.beginTransaction();
ft.hide(f);
ft.commit();
}
}
return true;
}
}
class frag extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.a, container, false);
}
}

Categories

Resources