Button will not work inside Fragment - android

So my problem is that the buttons that are contained within my fragments throw up an error "Unhandled Exception - Object reference not set to an instance of an object"
I thought because I had referenced the layout that contains the button that this would not cause an error. If anyone could shed some light to what I am doing wrong that would be great. I think I am either missing some vital code or have completely messed it up as I am new to using fragments and understand that they work differently from activities.
This is my MainActivity:
public class MainActivity : ActionBarActivity
{
private SupportToolbar mToolbar;
private MyActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mLeftDrawer;
private HomeFragment mHomeFragment;
private LogInFragment mLogInFragment;
private MatchCentreFragment mMatchCentreFragment;
private PrevCompFragment mPrevCompFragment;
private PrevFixFragment mPrevFixFragment;
private SettingsFragment mSettingsFragment;
private SocialFragment mSocialFragment;
private UpcomCompFragment mUpcomCompFragment;
private UpcomFixFragment mUpcomFixFragment;
private SupportFragment mCurrentFragment = new SupportFragment();
private Stack<SupportFragment> mStackFragments;
private ArrayAdapter mLeftAdapter;
private List<string> mLeftDataItems;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
mToolbar = FindViewById<SupportToolbar>(Resource.Id.toolbar);
mDrawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
mLeftDrawer = FindViewById<ListView>(Resource.Id.left_drawer);
mHomeFragment = new HomeFragment();
mLogInFragment = new LogInFragment();
mMatchCentreFragment = new MatchCentreFragment();
mPrevCompFragment = new PrevCompFragment();
mPrevFixFragment = new PrevFixFragment();
mSettingsFragment = new SettingsFragment();
mSocialFragment = new SocialFragment();
mUpcomCompFragment = new UpcomCompFragment();
mUpcomFixFragment = new UpcomFixFragment();
mStackFragments = new Stack<SupportFragment>();
mLeftDrawer.Tag = 0;
SetSupportActionBar(mToolbar);
mLeftDataItems = new List<string>();
mLeftDataItems.Add("Home");
mLeftDataItems.Add("Log In");
mLeftDataItems.Add("Match Centre");
mLeftDataItems.Add("Previous Fixtures");
mLeftDataItems.Add("Upcoming Fixtures");
mLeftDataItems.Add("Previous Competitions");
mLeftDataItems.Add("Upcoming Competitions");
mLeftDataItems.Add("Settings");
mLeftDataItems.Add("Social");
mLeftAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, mLeftDataItems);
mLeftDrawer.Adapter = mLeftAdapter;
mLeftDrawer.ItemClick += MenuListView_ItemClick;
mDrawerToggle = new MyActionBarDrawerToggle(this, mDrawerLayout, Resource.String.openDrawer, Resource.String.closeDrawer);
if (bundle != null)
{
if (bundle.GetString("DrawerState") == "Opened")
{
SupportActionBar.SetTitle(Resource.String.openDrawer);
}
else
{
SupportActionBar.SetTitle(Resource.String.closeDrawer);
}
}
else
{
SupportActionBar.SetTitle(Resource.String.closeDrawer);
}
Android.Support.V4.App.FragmentTransaction trans = SupportFragmentManager.BeginTransaction();
trans.Add(Resource.Id.fragmentContainer, mHomeFragment);
trans.Add(Resource.Id.fragmentContainer, mLogInFragment);
trans.Hide(mLogInFragment);
trans.Add(Resource.Id.fragmentContainer, mMatchCentreFragment);
trans.Hide(mMatchCentreFragment);
trans.Add(Resource.Id.fragmentContainer, mPrevFixFragment);
trans.Hide(mPrevFixFragment);
trans.Add(Resource.Id.fragmentContainer, mUpcomFixFragment);
trans.Hide(mUpcomFixFragment);
trans.Add(Resource.Id.fragmentContainer, mPrevCompFragment);
trans.Hide(mPrevCompFragment);
trans.Add(Resource.Id.fragmentContainer, mUpcomCompFragment);
trans.Hide(mUpcomCompFragment);
trans.Add(Resource.Id.fragmentContainer, mSettingsFragment);
trans.Hide(mSettingsFragment);
trans.Add(Resource.Id.fragmentContainer, mSocialFragment);
trans.Hide(mSocialFragment);
mCurrentFragment = mHomeFragment;
trans.Commit();
}
void MenuListView_ItemClick (object sender, AdapterView.ItemClickEventArgs e)
{
Android.Support.V4.App.Fragment fragment = null;
switch (e.Id)
{
case 0:
ShowFragment(mHomeFragment);
break;
case 1:
ShowFragment(mLogInFragment);
break;
case 2:
ShowFragment(mMatchCentreFragment);
break;
case 3:
ShowFragment(mPrevFixFragment);
break;
case 4:
ShowFragment(mUpcomFixFragment);
break;
case 5:
ShowFragment(mPrevCompFragment);
break;
case 6:
ShowFragment(mUpcomCompFragment);
break;
case 7:
ShowFragment(mSettingsFragment);
break;
case 8:
ShowFragment(mSocialFragment);
break;
}
mDrawerLayout.CloseDrawers();
mDrawerToggle.SyncState();
}
private void ShowFragment (SupportFragment fragment)
{
if (fragment.IsVisible)
{
return;
}
var trans = SupportFragmentManager.BeginTransaction();
fragment.View.BringToFront();
mCurrentFragment.View.BringToFront();
trans.Hide(mCurrentFragment);
trans.Show(fragment);
trans.AddToBackStack(null);
mStackFragments.Push(mCurrentFragment);
trans.Commit();
mCurrentFragment = fragment;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
//The hamburger icon was clicked which means the drawer toggle will handle the event
mDrawerToggle.OnOptionsItemSelected(item);
return true;
case Resource.Id.action_refresh:
//Refresh
return true;
case Resource.Id.action_help:
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.drawer_menu, menu);
return base.OnCreateOptionsMenu(menu);
}
protected override void OnSaveInstanceState(Bundle outState)
{
if(mDrawerLayout.IsDrawerOpen((int)GravityFlags.Left))
{
outState.PutString("DrawerState", "Opened");
}
else
{
outState.PutString("DrawerState", "Closed");
}
base.OnSaveInstanceState(outState);
}
protected override void OnPostCreate(Bundle savedInstanceState)
{
base.OnPostCreate(savedInstanceState);
mDrawerToggle.SyncState();
}
public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
mDrawerToggle.OnConfigurationChanged(newConfig);
}
}
}
This is one of my fragments (there are several but they all contain basically the same code so far)
public class PrevFixFragment : Android.Support.V4.App.Fragment
{
Button button;
public PrevFixFragment()
{
}
public static Android.Support.V4.App.Fragment newInstance(Context context)
{
PrevFixFragment fragment = new PrevFixFragment();
return fragment;
}
public override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.PreviousFixtures, null);
button = View.FindViewById<Button>(Resource.Id.upcombutton);
button.Click += StartNewActivity;
return view;
}
void StartNewActivity(object sender, EventArgs e)
{
Intent intent = new Intent(Activity, typeof(UpcomFixActivity));
StartActivity(intent);
}
}
}

Try moving the following lines to override void OnViewCreated or override void onActivityCreated
button = View.FindViewById<Button>(Resource.Id.upcombutton);
button.Click += StartNewActivity;

You must write View with lowercase view in statement below:
button = View.FindViewById<Button>(Resource.Id.upcombutton);

Related

Performclick does not function with android fragment

I have a problem with android studio. I use a fragment with a bottomNavigationView. It works fine if you click on the bottomNavigation. But if you simulate a click on the bottomNavigation it works for the first time and at the second time if you simulate the performclick again, it does not work.
I used also view.callOnClick(); and for the fragment add and remove fragment, but both do not function for my problem. I really appreciate it, if anyone can solve my problem.
Here is the Code:
`
public class ProfileFragment extends Fragment {
private Button send_order_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState) {
return inflater.inflate(R.layout.profile_fragment, container,false);
}
#Override
public void onStart() {
send_order_button = (Button) getView().findViewById(R.id.auftrag_abschicken);
}
send_order_button.setOnClickListener(new View.OnClickListener() {
ProfilActivity pa = new ProfilActivity();
pa.changeFragment();
getActivity().finishActivity(ProfilActivity.class.hashCode());
}
}`
`
public class ProfilActivity extends AppCompatActivity {
public ProfilActivity() {}
public static Fragment selectedFragment = null;
public static BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
View view = bottomNavigationView.findViewById(R.id.nav_chat);
view.performClick();
}
public void changeFragment() {
// bottomNavigationView.setSelectedItemId(R.id.nav_store);
View view = bottomNavigationView.findViewById(R.id.nav_store);
view.performClick();
}
public BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_user :
selectedFragment = new ProfileFragment();
break;
case R.id.nav_chat :
selectedFragment = new MailFragment();
break;
case R.id.nav_store:
selectedFragment = new ShopFragment();
break;
}
try {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment, "fragment").commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
};
return true;
}
};
}`
It looks like you're trying to set the default selected item in the BottomNavigationView. Why not just use bottomNavigationView.setSelectedItemId(R.id.nav_store); ?

How to provide listeners for different fragment in a viewpager from a button in activity

I am trying to create a form using fragments in a viewpager which is a step by step process.
there are 6 fragments in the viewpager. a "Back" button and a "Next" button(in the activity).
I want to save the form when the user clicks the "Next" button.
To the Reference here is the code
The Adapter to load the Fragments
public class RegistrationPagerAdapter extends FragmentPagerAdapter {
Fragment fragment;
public RegistrationPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
fragment = new PersonalDetailsFragment();
break;
case 1:
fragment = new AboutMeFragment();
break;
case 2:
fragment = new HoroscopeFragment();
break;
case 3:
fragment = new EducationFragment();
break;
case 4:
fragment = new FamilyFragment();
break;
case 5:
fragment = new ExpectationFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 6;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}
There are two buttons in the activity(not in fragments)
public class FormActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "FormActivity";
AppCompatButton backButton, nextButton;
CustomViewPager viewpager;
Toolbar toolbar;
ApiInterface apiInterface;
RegistrationPagerAdapter adapter;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
initilizeToolbar();
}
#Override
protected void onRestart() {
super.onRestart();
}
private void initilizeToolbar() {
apiInterface = ApiClient.getClient(getApplicationContext()).create(ApiInterface.class);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
castComponents();
}
private void castComponents() {
viewpager = findViewById(R.id.viewPager);
backButton = findViewById(R.id.backButton);
nextButton = findViewById(R.id.nextButton);
nextButton.setOnClickListener(this);
backButton.setOnClickListener(this);
GetAllDetailsOfUser();
}
#Override
public void onResume() {
initilizeToolbar();
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
public void setViewPagerData(int status) {
FragmentManager fm = getSupportFragmentManager();
adapter = new RegistrationPagerAdapter(fm, 0);
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(status);
viewpager.setPagingEnabled(false);
}
public void GetAllDetailsOfUser() {
Call<AllProfileDetails> allDetails = apiInterface.allDetails(PrefUtils.getToken(this), PrefUtils.getID(this));
allDetails.enqueue(new Callback<AllProfileDetails>() {
#Override
public void onResponse(Call<AllProfileDetails> call, Response<AllProfileDetails> response) {
AllProfileDetails all = response.body();
if (all != null) {
if (all.getStatus()) {
Data data = all.getData();
setViewPagerData(data.getProfileCurrentStatus());
status = data.getProfileCurrentStatus();
}
}
}
public void onFailure(Call<AllProfileDetails> call, Throwable t) {
Crashlytics.log(t.getLocalizedMessage());
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backButton:
if (viewpager.getCurrentItem() == 0){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
}
break;
case R.id.nextButton:
if (viewpager.getCurrentItem() == 6){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
}
break;
}
}
}
this is Code is Fine but here is the problem...
When i save the data in Fragment1 i.e "PersonalDetailsFragment", it moves to fragment2 i.e "AboutMeFragment"
again when i click on save button for "AboutMeFragment" it runs the method of "PersonalDetailsFragment" only
please note that i call the activity buttons in fragments as
getActivity().findViewById(R.id.backButton);
getActivity().findViewById(R.id.nextButton);
You should have a interface like OnSaveTapped.
public interface OnSaveTapped{
void onSaveTapped();
}
Then make the fragments implement the interface above, ex:
public class PersonalDetailsFragment extends Fragment implements OnSaveTapped{
public void onSaveTapped(){
//do your business code here to save data
}
}
Finally ,In the activity class:
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backButton:
if (viewpager.getCurrentItem() == 0){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
}
break;
case R.id.nextButton:
if (viewpager.getCurrentItem() == 6){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
}
break;
case R.id.button_save:
((OnSaveTapped)viewpager.getCurrentFragment()).onSaveTapped();
}
Don't forget to create new method named getCurrentFragment() to return current item (fragment) in RegistrationPagerAdapter.
public class RegistrationPagerAdapter extends FragmentPagerAdapter {
private Fragment fragment;
/**other lines of code*/
public Fragment getCurrentFragment(){
return fragment;
}
}

how to add Activity class in DrawerLayout in android?

I have some slides with ViewPager that shows application help and I want to show it in DrawerLayout too.
this is HelpActivity.class:
public class HelpActivity extends Activity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.fragment_help);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_1,
R.layout.welcome_2,
R.layout.welcome_3,
R.layout.welcome_4,
R.layout.welcome_5,
R.layout.welcome_6,
R.layout.welcome_7};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(HelpActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(/*getString(R.string.start)*/ "Start");
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(/*getString(R.string.next)*/ "Next");
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
this is PrefManager.class:
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "stand up-welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
and I use this code for defining it to drawerLayout:
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
with clicking on help in drawer, nothing shows. what should I do?
This is MainActivity.class:
ublic class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
public NavigationView navigationView;
public ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new HomeFragment());
tx.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle= setupDrawerToggle();
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//navigation view
navigationView= (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(navigationView);
actionBarDrawerToggle.syncState();
// default item of navigation view
// navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(R.id.nav_item_home);
}//onCreate
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()==R.id.nav_item_setting){
startActivityForResult(new Intent(this, SettingActivity.class), 1002);
}
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
} return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState); // `onPostCreate` called when activity start-up is complete after `onStart()`
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
}
in your xml:
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#drawable/background_drawer"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/colorPrimary"
app:menu="#menu/menu_navigation" />
you have to add help options in your menu_navigation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_item_help"
android:icon="#drawable/profile_icon"
android:title="Help" />
</group>
</menu>
Also in your MainActivity:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_setting:
Intent i = new Intent(MainActivity.this, SettingActivity.class);
startActivity(i);
break;
case R.id.nav_item_help:
Intent i = new Intent(MainActivity.this, HelpActivity.class);
startActivity(i);
break;
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
In your preference manager:
public void setFirstTimeLaunch(boolean isFirstTime) {
Editor editor = pref.edit();
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
difference between startactivity and startActivityForResult is:
1. startActvity():
startActivity() will start the activity you want to start without worrying about getting any result from new child activity started by startActivity to parent activity.
2. startAcitvityForResult():
startAcitvityForResult() starts another activity from your activity and it expect to get some data from newly started child activity by startAcitvityForResult() and return that to parent activity.
see this blog:https://malikshafique.wordpress.com/2012/06/14/android-startactivity-and-startactivityforresult/

How to Move From Activity to Fragment?

I have to include three Fragment on my main Activity on click of Three Buttons on app bar. Now, Question is I want to go back from second activity to specific fragment on mainActivity I am using Intent but at start of app intent is null and get nullpointer exception and app crash.
Here is MainActivity.java
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
FragmentTransaction fragmentTransaction;
HomeFragment homeFrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
//--------Set and Get Tool Bar-------//
setSupportActionBar(binding.appbar);
getSupportActionBar().setTitle("");
if(getIntent() !=null){
String is = getIntent().getStringExtra("check");
if(is.equals("1")){
SearchFragment searchFrag = new SearchFragment();
if(searchFrag != null){
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, searchFrag)
.addToBackStack(null).commit();
}
}
}else{
homeFrag = new HomeFragment();
if(homeFrag!=null) {
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, homeFrag).commit();
}
}
}
public void MoveToSearchActivity(View view){
SearchFragment searchFag = new SearchFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer,searchFag).commit();
}
public void MoveToHomeActivity(View view){
if(homeFrag!=null) {
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, homeFrag).commit();
}
}
public void MoveToAlertFrag(View view){
AlertFragment alertFragment = new AlertFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer,alertFragment).commit();
}
And here is my FilterActivity.java from which I'm going back to fragment:
public class FilterActivity extends AppCompatActivity{
private ActivityFilterBinding binding;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter);
//--------------Get ToolBar-----------//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(" ");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Intent homeIntent = new Intent(FilterActivity.this, MainActivity.class);
homeIntent.putExtra("check",1);
startActivity(homeIntent);
break;
default:
break;
}
return true;
}
}
Thanks.
Try this in MainActivity,
// Toolbar code
...
int is = -1;
if (getIntent() != null && getIntent().hasExtra("check")) {
is = getIntent().getIntExtra("check", -1);
}
switch (is) {
case 1:
// load SearchFragment
break;
case 2:
// load MoveToAlertFrag
break;
default:
// load HomeFragment
break;
}

problems with Fragment onBackPress

in my navigation drawer there are 5 menu items.one of them is about us item.when I click on this item, I call AboutUsFragment and show it(its content is just a text).but when I click onBackPress, fragment is gone but its texts remains on my activity.how can I solve this problem?what`s it related to?!
select item of navigation drawer in my activity:
public void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
if (!Constants.login_state) {
fragment = new LoginFragment();
} else {
Logout();
}
break;
case 1:
Constants.filter = false;
Constants.gender = "-1";
fragment = new HomeFragment();
break;
case 2:
Constants.filter = false;
Constants.gender = "2";
StyleFragment.SortingMode = 1;
fragment = new StyleFragment();
break;
case 3:
Constants.filter = false;
Constants.gender = "1";
StyleFragment.SortingMode = 1;
fragment = new StyleFragment();
break;
case 4:
fragment = new AboutUsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentTransaction fragmentManager = getSupportFragmentManager().beginTransaction();
fragmentManager.replace(R.id.rl_container, fragment);
fragmentManager.addToBackStack(null);
fragmentManager.commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(Gravity.END);
} else {
Log.e("HomeActivity", "Error in creating fragment");
}
}
and AboutUsFragment:
public class AboutUsFragment extends android.support.v4.app.Fragment{
private View view;
private TextView about_us_fragment_text_view;
public static AboutUsFragment newInstance() {
AboutUsFragment fragment = new AboutUsFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_about_us, container, false);
Casting(view);
about_us_fragment_text_view.setText(getResources().getString(R.string.about_us));
ChangeUIFont.ChangeFont((ViewGroup) view, getContext());
return view;
}
//casting parameters
public void Casting(View v){
about_us_fragment_text_view= (TextView) v.findViewById(R.id.about_us_fragment_text_view);
}}
onBackPress in my activity:
#Override
public void onBackPressed() {
if (SearchOpened) {
lv_searchResult.setVisibility(View.GONE);
SearchOpened = false;
} else
super.onBackPressed();
}
---------------------------------------AfterSearching-------------------------------------------
Finally I found the solution!
in my fragment I added below code:
public static final String FRAGMENT_NAME = AboutUsFragment.class.getName();
and in my activity,I set the tag of fragment when I call it,instead of null!
fragmentManager.replace(R.id.rl_container, fragment,fragmentName);
used this method instead of onBackPressed
if you have toolbar then here is my solution,
type under the oncreate method below toolbar,
assert getSupportActionBar() != null;
// getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
and set this code in your manifest file for your fragment
<activity android:name=".yourCurrentFragment">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".whichActivityYouWantToGo" />
</activity>
Try this:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}

Categories

Resources