I am A Beginner in android development, actually I have a Navigation drawer with Fragments my issue is when i go to fragment b from a the state in navigation drawer is updating to fragment b successfully but when go to fragment B From Fragment A by on 'backpressed' method the drawer item state is not updating / changing to fragment A . please help me in fixing this.
Here is my Main Activity Code :
public class MainActivity extends AbsRuntimePermission implements NavigationView.OnNavigationItemSelectedListener {
//, GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_PERMISSION = 10;
private Toolbar toolBar;
private NavigationView navDrawer;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
private View btnLogOut;
private int selectedItem;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
// private GoogleApiClient googleApiClient;
private FloatingActionButton fab;
private CoordinatorLayout coordinatorLayout;
private HomeFragment homeFragment=new HomeFragment();
final String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String userID = user.getUid();
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Contact_FAB.class);
startActivity(intent);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_content, homeFragment);
tx.commit();
final WebView webView = (WebView) findViewById(R.id.WV);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
public void onPageFinished(WebView view, String url) {
// do your stuff here}
#Override
public void onReceivedError (WebView view,int errorCode, String description, String
failingUrl){
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
webView.loadUrl("https://google.co.in");
requestAppPermissions(new String[] {
Manifest.permission.READ_CONTACTS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
R.string.msg,REQUEST_PERMISSION);
toolBar =(Toolbar)
findViewById(R.id.app_bar);
setSupportActionBar(toolBar);
// If a notification message is tapped, any data accompanying the notification
// message is available in the intent extras. In this project the launcher
// intent is fired when the notification is tapped, so any accompanying data would
// be handled here. If you want a different intent fired, set the click_action
// field of the notification message to the desired intent. The launcher intent
// is used when no click_action is specified.
//
// Handle possible data accompanying notification message.
if(
getIntent().
getExtras() !=null)
{
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("AnotherActivity") && value.equals("True")) {
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
}
// subscribeToPushService();
drawerLayout =(DrawerLayout)
findViewById(R.id.drawer_layout);
navDrawer =(NavigationView)
findViewById(R.id.menu_drawer);
navDrawer.setNavigationItemSelectedListener(this);
drawerToggle =new
ActionBarDrawerToggle(this,drawerLayout, toolBar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectedItem =savedInstanceState ==null?R.id.nav_item_1 :savedInstanceState.getInt("selectedItem");
}
#Override
public boolean onNavigationItemSelected (MenuItem menuItem){
menuItem.setChecked(true);
selectedItem = menuItem.getItemId();
Fragment fragment = null;
switch (selectedItem) {
case R.id.nav_item_1:
fragment = new HomeFragment();
break;
case R.id.nav_item_2:
fragment = new MicrosoftDskFragment();
break;
case R.id.nav_item_3:
fragment = new GoogleDskFragment();
break;
case R.id.nav_item_4:
fragment = new AppleDskFragment();
break;
case R.id.nav_item_5:
fragment = new OthersDskFragment();
break;
case R.id.nav_item_6:
fragment = new MobiSpecsFragment();
break;
case R.id.nav_item_8:
Intent intent = new Intent(MainActivity.this, About.class);
startActivity(intent);
break;
default:
break;
}
if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Plz check your network connectivity", Toast.LENGTH_SHORT).show();
} else {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_content, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
boolean twice = false;
#Override
public void onBackPressed () {
DrawerLayout layout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (layout.isDrawerOpen(GravityCompat.START)) {
layout.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
Log.d(TAG, "click");
if (twice == true) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice: " + twice);
//super.onBackPressed();
Toast.makeText(MainActivity.this, "Please Press Again To Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice: " + twice);
}
}, 3000);
}
}
}
#Override
public boolean onKeyDown ( int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
homeFragment.OnKeyDown(keyCode);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#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.profile) {
Intent intent = new Intent(MainActivity.this, Profile.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState){
super.onSaveInstanceState(outState, outPersistentState);
outState.putInt("selectedItem", selectedItem);
}
#Override
public void onPermissionsGranted ( int requestCode){
//Do anything when permisson granted
// Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();
}
/* #Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
*/
}
}
When you popBackStack() the fragment from back stack will appear on screen so you need to listen for Back stack changes.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.containerFrame);
if (fragment != null) {
// check for fragment and set the drawer state
if(fragment instanceof Frag1){
// set drawer state for 1
}else if(fragment instanceof Frag2){
// set drawer state for 2
}
}
}
});
Related
I am receiving the following crash reports from fabric.io (mainly after I added a SettingsActivity which can be loaded from my SlidingMenue to my App):
The code of to post the pendingRunnable has not been changed recently, anyway it started to receive the exceptions.
Fatal Exception: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:650)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609)
at my.app.ui.activity.MainActivity$2.run(MainActivity.java:271)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5530)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:733)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:623)
This is my MainActivity.java
public class MainActivity extends AppCompatActivity implements MyAppFragment.OnListFragmentInteractionListener, AsyncResponse {
private MyAppDatabaseHandler myAppDatabaseHandler;
private SharedPreferences sharedpreferences;
private SharedPreferences defaultPrefs;
private FragmentA fragmentA;
public static boolean activityVisible = true;
private boolean isAttached;
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private Toolbar toolbar;
// index to identify current nav menu item
private static int navItemIndex = 0;
public static String CURRENT_TAG = MyAppConstants.TAG_A;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.myAppDatabaseHandler= MyAppDatabaseHandler.getInstance(this);
defaultPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sharedpreferences = getSharedPreferences(MyAppConstants.PREFERENCES, Context.MODE_PRIVATE);
setContentView(R.layout.activity_main);
fragmentA = new FragmentA();
// Init UI
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.sliding_menu_item_activity_titles);
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = MyAppConstants.TAG_A;
loadNextFragment();
}
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
// Init NavigationHeader
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadNextFragment() {
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag( CURRENT_TAG) != null && navItemIndex != 4) {
drawer.closeDrawers();
return;
}
if (navItemIndex == 4) {
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
} else {
// set toolbar title
setToolbarTitle();
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the activity_main_header_with_item content by replacing fragments
Fragment fragment = getNextFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
}
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getNextFragment() {
switch (navItemIndex) {
case 0:
// home
return this.fragmentA;
case 1:
FragmentB fragmentB = new FragmentB();
return fragmentB;
case 2:
// About Fragment
AboutFragment aboutFragment = new AboutFragment();
return aboutFragment;
case 3:
// Licence Fragment
LicenceFragment licenceFragment = new LicenceFragment();
return licenceFragment;
default:
return this.fragmentA;
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the activity_main_header_with_item content with ContentFragment Which is our Inbox View;
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = MyAppConstants.TAG_A;
break;
case R.id.nav_recently:
navItemIndex = 1;
CURRENT_TAG = MyAppConstants.TAG_B;
break;
case R.id.nav_about_us:
navItemIndex = 2;
CURRENT_TAG = MyAppConstants.TAG_ABOUT;
break;
case R.id.nav_licences:
navItemIndex = 3;
CURRENT_TAG = MyAppConstants.TAG_LICENCES;
break;
case R.id.nav_settings:
navItemIndex = 4;
// do not set CURRENT_TAG
break;
default:
navItemIndex = 0;
}
loadNextFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress && CURRENT_TAG != MyAppConstants.TAG_A) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = MyAppConstants.TAG_A;
loadNextFragment();
return;
}
}
finish();
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_header_with_item, menu);
// Disable Player Icon in case no player is found on device
Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, MyAppConstants.MUSIC_APP);
List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);
if(activities == null || activities.size() <= 0) {
MenuItem player = menu.findItem(R.id.player);
if(player != null){
player.setVisible(false);
}
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void notifyOnDelete(View v) {
myAppDatabaseHandler.deleteAll();
}
#Override
public void onListFragmentInteraction(Song item) {
}
#Override
public void processFinish(String output) {
if (isAttached) {
...
}
}
#Override
public void onAttachedToWindow() {
isAttached = true;
super.onAttachedToWindow();
}
#Override
public void onDetachedFromWindow() {
isAttached = false;
super.onDetachedFromWindow();
}
#Override
public void onResume() {
activityVisible = true;
updateFragmentA();
super.onResume();
}
#Override
public void onPause() {
activityVisible = false;
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
}
public void updateFragmentA() {
if (CURRENT_TAG == MyAppConstants.TAG_A) {
Timber.i( "updating FragmentA");
fragmentA.swap();
}
}
}
Any ideas about the cause of this issue?
Try this first setContentView(R.layout.activity_main); than perform your action
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.myAppDatabaseHandler= MyAppDatabaseHandler.getInstance(this);
defaultPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sharedpreferences = getSharedPreferences(MyAppConstants.PREFERENCES, Context.MODE_PRIVATE);
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/
I am developing an app and want users to be able to use their phones horizontally or vertically, however, if I start in portrait and switch to landscape, the app crashes. It also crashes if I start landscape and switch to portrait.
Here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="sensor">
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="screenSize|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="net.sourceforge.zbar.android.CameraTest.CameraTestActivity" />
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
</application>
I have already tried this this, but then the app cannot go to landscape as described here.
Here is the activity that it crashed in (MainActivity):
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, UserDelegate {
private static final int SCAN_COUPONS = 1;
public GoogleApiClient googleApiClient;
private Location lastLocation;
EditText zip;
public static User user;
public SharedPreferences sharedPreferences;
public static SQLiteDatabase database;
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_bar_container);
/*
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.actionbar);
}
*/
sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
database = openOrCreateDatabase("CouponWallet", MODE_PRIVATE, null);
/*Typeface iconFont = FontManager.getTypeface(getApplicationContext(), FontManager.FONTAWESOME);
FontManager.markAsIconContainer(findViewById(R.id.content_main), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.drawer_layout), iconFont);
//FontManager.markAsIconContainer(findViewById(R.id.nav_drawer), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.top_toolbar), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.bottom_toolbar), iconFont);*/
FontIconTypefaceHolder.init(getAssets(), "fonts/FontAwesome.ttf"); //allows for icons
// set up toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.top_toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Coupon Wallet");
toolbar.hideOverflowMenu();
FontManager.setFont(findViewById(R.id.top_toolbar), FontManager.getTypeface(this, FontManager.CANDY));
googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
Log.v("onCreate", "api client created");
//set up drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
new Thread(new Runnable() {
#Override
public void run() { // does ouside of ui thread
setIcons();
}
}).start();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
/*if(sharedPreferences.getInt("user_id", 0) == 0){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new LoginFragment());
ft.addToBackStack(null);
ft.commit();
getSupportActionBar().setTitle("Login");
}*/
//user = new User(sharedPreferences.getInt("user_id", 1), database);
//if (Functions.isOnline()) {
Log.v("onCreate", "creating user " + sharedPreferences.getInt("user_id", 1));
this.user = new User(1, this);
//}
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} 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);
LayerDrawable layerDrawable = (LayerDrawable) menu.findItem(R.id.action_barcode).getIcon();
layerDrawable.setDrawableByLayerId(R.id.main_icon, Functions.getFAIcons(this).get("barcode"));
Functions.setBadgeCount(this, layerDrawable, 2, R.id.num_circle);
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();
if (id == R.id.action_barcode) {
final AlertDialog dialog = new AlertDialog.Builder(this).setView(R.layout.redeem_code_layout).create();
dialog.show();
Toolbar toolbar = (Toolbar) dialog.findViewById(R.id.redeem_toolbar);
toolbar.inflateMenu(R.menu.redeem_menu);
toolbar.setTitle("Redeem Codes");
toolbar.setNavigationIcon(Functions.getFAIcons(this).get("times"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
toolbar.inflateMenu(R.menu.redeem_menu);
toolbar.hideOverflowMenu();
toolbar.setTitleTextColor(getResources().getColor(R.color.colorBlack));
FontManager.setFont(toolbar, FontManager.getTypeface(this, FontManager.CHAMPAGNE));
MenuItem help = toolbar.getMenu().add("Help");
help.setIcon(Functions.getFAIcons(this).get("question"));
help.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Toast.makeText(getApplicationContext(), "Help Clicked", Toast.LENGTH_LONG).show();
return false;
}
});
final ImageView code = (ImageView) dialog.findViewById(R.id.redeem_code);
code.setImageDrawable(user.barcode);
Spinner spinner = (Spinner) dialog.findViewById(R.id.redeem_scan_type);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item, new String[]{"Barcode", "QR Code", "PDF417", "Aztec"});
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
code.setImageDrawable(user.barcode);
break;
case 1:
code.setImageDrawable(user.qr_code);
break;
case 2:
code.setImageDrawable(user.pdf417);
break;
case 3:
code.setImageDrawable(user.aztec);
break;
}
/*for(int j = 0; j < 4; j++){
if (i != j) {
TextView item = ((TextView) adapterView.getChildAt(j));
item.setBackgroundColor(getResources().getColor(R.color.colorWhite));
item.setTextColor(getResources().getColor(R.color.colorGray));
} else {
TextView item = ((TextView) adapterView.getChildAt(j));
item.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
item.setTextColor(getResources().getColor(R.color.colorWhite));
}
}*/
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
code.setImageDrawable(user.barcode);
}
});
TextView textView = (TextView) dialog.findViewById(R.id.redeem_num);
long uid = user.id;
textView.setText(String.format(Locale.US, "%s%011d", "891", uid));
}
return super.onOptionsItemSelected(item);
}
/**
* #param item item selected in nav menu
* #return if view switch was successful
*/
//#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
String title = "";
Toolbar toolbar = (Toolbar) findViewById(R.id.bottom_toolbar);
toolbar.getMenu().clear();
switch (id) { //based on which section was selected
case R.id.nav_search:
title = "Search";
fragment = new SearchFragment();
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("gear"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.my_wallet);
MenuItem map1 = toolbar.getMenu().getItem(0); //only item in the menu
map1.setIcon(Functions.getFAIcons(getApplicationContext()).get("map"));
map1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.v("bottom_toolbar", "map clicked");
return true;
}
});
break;
case R.id.nav_profile:
title = "Profile";
break;
case R.id.nav_notifications:
title = "Notifications";
break;
case R.id.nav_categories:
try {
lastLocation = getLastKnownLocation();
if (lastLocation != null) {
Log.v("categories", "Location accessed");
Bundle bundle2 = new Bundle();
bundle2.putDouble("lat", lastLocation.getLatitude());
bundle2.putDouble("lon", lastLocation.getLongitude());
bundle2.putString("type", "loc");
fragment = new CategoriesFragment();
fragment.setArguments(bundle2);
title = "Categories";
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("gear"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.categories);
break;
}
} catch (SecurityException e) { // if can't get location go straight to search
}
Log.v("categories", "Location not accessable");
Toast.makeText(this, "Turn on location services get faster results", Toast.LENGTH_LONG).show();
AlertDialog dialog2 = new AlertDialog.Builder(this).setView(R.layout.get_zip_dialog).setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).create();
dialog2.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
dialogInterface.dismiss();
Toast.makeText(getApplicationContext(), "Cannot get local categories without location", Toast.LENGTH_LONG).show();
}
});
zip = (EditText) findViewById(R.id.zip_code);
dialog2.show();
break;
case R.id.nav_wallet:
fragment = new MyWalletFragment(); //sets up view
// setting up toolbars
title = "My Wallet";
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("columns"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.my_wallet);
MenuItem map = toolbar.getMenu().getItem(0); //only item in the menu
map.setIcon(Functions.getFAIcons(getApplicationContext()).get("map"));
map.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.v("bottom_toolbar", "map clicked");
return true;
}
});
//toolbar.setLogo(R.id.horizontal);
break;
case R.id.nav_scan:
title = "Scan Coupons";
Intent intent = new Intent(this, CameraTestActivity.class);
startActivityForResult(intent, SCAN_COUPONS);
break;
case R.id.nav_map:
title = "Map";
break;
case R.id.nav_settings:
fragment = new SettingFragment(); //sets up view
title = "Settings";
break;
case R.id.nav_help:
title = "Help";
// Assuming the Help in the nav bar is the same as the settings menu
fragment = new HelpSettingsFragment();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
FontManager.setFont(findViewById(R.id.content_frame), FontManager.getTypeface(this, FontManager.CHAMPAGNE));
//noinspection ConstantConditions
getSupportActionBar().setTitle(title);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onLocationChanged(Location location) {
Log.v("onLocationChanged", "Location changed");
lastLocation = location;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.v("onConnected", "connected");
try {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
/**
* Process a coupon scan
*
* #param requestCode Type of activity
* #param resultCode if result ok
* #param data the returned data
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) {
Log.e("onActivityResult", "result canceled");
} else if (resultCode == RESULT_OK) {
if (requestCode == SCAN_COUPONS) {
String result = data.getStringExtra("result");
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
Log.v("onActivityResult", result);
}
}
}
/**
* Set the icons in the drawer
*/
private void setIcons() {
Map<String, Drawable> map = Functions.getFAIcons(getApplicationContext());
int[] sections = {R.id.nav_search, R.id.nav_profile, R.id.nav_notifications, R.id.nav_categories, R.id.nav_wallet,
R.id.nav_scan, R.id.nav_map, R.id.nav_settings, R.id.nav_help};
Drawable[] icons = {map.get("search"), map.get("user"), map.get("bookmark"), map.get("list"), map.get("barcode"),
map.get("camera"), map.get("map_o"), map.get("gear"), map.get("question")};
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu m = navigationView.getMenu();
for (int i = 0; i < sections.length; i++) {
MenuItem item = m.findItem(sections[i]);
item.setIcon(icons[i]);
}
}
/**
* Gets the last known Location
*
* #return The last known location
* #throws SecurityException if proper permissions not given
*/
private Location getLastKnownLocation() throws SecurityException {
LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
Log.v("getLastKnownLocation", "looping through providers");
for (String provider : providers) {
Log.v("getLastKnownLocation", provider);
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
public void settingOnClick(View v) {
/*
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_shortcut)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mBuilder.setAutoCancel(true);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
*/
Fragment fragment = null;
switch (v.getId()) {
case R.id.setting_account:
case R.id.setting_userIcon:
fragment = new AccountSettingsFragment();
break;
case R.id.setting_location:
case R.id.setting_locationArrow:
fragment = new LocationSettingsFragment();
break;
case R.id.setting_notifications:
case R.id.setting_notificationIcon:
fragment = new NotificationSettingsFragment();
break;
case R.id.setting_help:
case R.id.setting_helpIcon:
fragment = new HelpSettingsFragment();
break;
case R.id.setting_contact:
case R.id.setting_contactIcon:
fragment = new ContactUsSettingsFragment();
break;
case R.id.setting_privacy:
case R.id.setting_privacyIcon:
fragment = new PrivacyPolicySettingsFragment();
break;
case R.id.setting_about:
case R.id.setting_aboutIcon:
fragment = new AboutSettingsFragment();
break;
case R.id.tutorial_loc_enterAnotherLocation:
fragment = new EnterAnotherLocation();
break;
case R.id.tutorial_1_saving:
case R.id.tutorial_2_saving:
case R.id.tutorial_3_saving:
fragment = new FirstTimeLocation();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
}
#Override
public void userFinished(User user) {
this.user = user;
Log.v("UserFinished", user.toString());
}
}
And the error that i get is here. It is a link to a .txt file as it brings the question over the character limit.
Hii for working in landscape and portrait mode, you have to use saved instance and restore saved instance or else your application values
googleApiClient,lastLocation,zip,user values may have null value and causes this issue
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
savedInstanceState.putParcelable("parcelable", "");
savedInstanceState.putSerializable("serializable", "");
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate() and also onRestoreInstanceState() where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
In my app I have the following navigationview.
So when the user click the menu item Καλώς ήρθες(meaning welcome in Greek),I want the this to be shown in the toolbar. This is my code for the navigationview.
public class Welcome extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private SessionManager session;
Toolbar toolbar;
private int mIconSize;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(getApplicationContext());
SharedPreferences userName = PreferenceManager.getDefaultSharedPreferences(this);
//UserId = userName.getString("id","");
username = userName.getString("user_name", "");
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
if (savedInstanceState == null) {
//Restore the fragment's instance and geo coordinates!
//homeFragment = (FragmentHome) getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
setSelected(R.id.welcome);
}else{
//profileFragment = (FragmentProfile) fm2.findFragmentByTag(PROFILE_FRAGMENT);
}
ActionBarDrawerToggle adt = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
R.string.open_drawer,R.string.close_drawer){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.addDrawerListener(adt);
adt.syncState();
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setBackgroundColor(getResources().getColor(R.color.navigation_bg_color));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
boolean result = setSelected(item.getItemId());
return result;
}
});
View v = navigationView.getHeaderView(0);
TextView t = (TextView)v.findViewById(R.id.username);
t.setText(username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.log_out, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.log_out:
logoutUser();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logoutUser() {
session.setLogin(false);
// Launching the login activity
Intent intent = new Intent(Welcome.this, MainActivity.class);
startActivity(intent);
finish();
}
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
WelcomeFragment welcomeFragment = new WelcomeFragment();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction fragmentTra1 = fm1.beginTransaction();
fragmentTra1.replace(R.id.content,welcomeFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra1.commit();
return true;
case R.id.general:
GeneralFragment generalFragment= new GeneralFragment();
FragmentManager fm2 = getSupportFragmentManager();
FragmentTransaction fragmentTra2 = fm2.beginTransaction();
fragmentTra2.replace(R.id.content,generalFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra2.commit();
return true;
case R.id.announcements:
AnnouncementsFragment announcementsFragment= new AnnouncementsFragment();
FragmentManager fm3 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubOne = fm3.beginTransaction();
fragmentTraSubOne.replace(R.id.content,announcementsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubOne.commit();
return true;
case R.id.sub_one:
NewsFragment newsFragment= new NewsFragment();
FragmentManager fm4 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubTwo = fm4.beginTransaction();
fragmentTraSubTwo.replace(R.id.content,newsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubTwo.commit();
return true;
case R.id.sub_two:
FanClubFragment fanClubFragment= new FanClubFragment();
FragmentManager fm5 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubThree = fm5.beginTransaction();
fragmentTraSubThree.replace(R.id.content,fanClubFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubThree.commit();
return true;
}
return false;
}
public static Intent newIntent(Context context) {
return new Intent(context,MainActivity.class);
}
#Override
public void onBackPressed() {
if(isNavDrawerOpen()){
closeDrawerLayout();
}else {
super.onBackPressed();
}
}
public boolean isNavDrawerOpen() {
return drawerLayout!=null && drawerLayout.isDrawerOpen(GravityCompat.START);
}
private void closeDrawerLayout(){
if(drawerLayout != null){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return (keyCode == KeyEvent.KEYCODE_BACK ? true :
super.onKeyDown(keyCode, event));
}
}
Any ideas?
Thanks,
Theo.
Try using setTitle():
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
toolbar.setTitle("Welcome");
......
}
.....
}
Try using:
getSupportActionBar().setTitle("title");
in the switch-case
I think you could use something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
item.setIcon(R.drawable.drawable_resource_name);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
Also this link might help: Here
Hope it helps ;)
btw your app looks great!
I use MaterialDrawer and code MainActivity is:
public class MainActivity extends AppCompatActivity implements KitchenFragment.CallbackOne {
public static final String TAG = "myLogTag";
private Toolbar mToolbar;
private Drawer drawer;
private FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "CLICK NOCL");
}
});
setSupportActionBar(mToolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(false);
fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.content_frame);
if (fragment == null) {
fragment = MenuFragment.newInstance();
fm.beginTransaction()
.add(R.id.content_frame, fragment)
.commit();
}
drawer = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.withActionBarDrawerToggle(true)
.withHeader(R.layout.drawer_header)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.menu).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.kitchen_title).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.information_title).withEnabled(false)
).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
Log.d(TAG, "position clicked: " + position);
Fragment fragment = MenuFragment.newInstance();
switch (position) {
case 1:
fragment = MenuFragment.newInstance();
break;
case 2:
fragment = KitchenFragment.newInstance();
break;
default:
fragment = new Fragment();
}
fm.beginTransaction().replace(R.id.content_frame, fragment).commit();
return false;
}
})
.withFireOnInitialOnClick(true)
.withSavedInstance(savedInstanceState)
.withOnDrawerNavigationListener(new Drawer.OnDrawerNavigationListener() {
#Override
public boolean onNavigationClickListener(View view) {
Log.d(TAG, "CLICK in DNL");
if (!drawer.getActionBarDrawerToggle().isDrawerIndicatorEnabled()) {
onBackPressed();
return true;
} else
return false;
}
})
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "CLICK OIS");
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState = drawer.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen())
drawer.closeDrawer();
else if (getFragmentManager().getBackStackEntryCount() == 1) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawer.getActionBarDrawerToggle().syncState();
getFragmentManager().popBackStack();
} else if (getFragmentManager().getBackStackEntryCount() > 0)
getFragmentManager().popBackStack();
else
super.onBackPressed();
}
#Override
public void setFirstSelected() {
drawer.setSelection(1);
}
}
I'm trying to trace a Click in mToolbar.setNavigationOnClickListener
and withOnDrawerNavigationListener and onOptionsItemSelected.
None of the listeners not reacted for clicking.
How you see i use Activity that launches Fragment (1), which in turn lets Fragment (2 and 3). In 2 and 3 Fragment in OnCreate i use ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); , and I need to by pressing the back button (in toolbar), returning the previous fragment, and not open Drawer
The MaterialDrawer already handles all the listeners for you. If you need to do an action after the drawer opens or closes you can provide the listener via the DrawerBuilder
For the icon you have this listener:
OnDrawerNavigationListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1158
For drawer close / open this listener:
OnDrawerListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1116
I suggest you to create new Activity using android studio wizard. File->New->Activity->Navigation Drawer Activity.
In that case ActionBarDrawerToaggle is used
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
This toggle contains click listener which handle open/close drawer functionality for you.
Also you can that item clicks implemented through OnNavigationItemSelectedListener.onNavigationItemSelected(MenuItem item)