"Can not perform this action after onSaveInstanceState" removing all fragments - android

I am trying remove all fragments in onStop() of ActionBarActivity but this throws an exception: Can not perform this action after onSaveInstanceState.
How could I do this ?
I'm trying this.
public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{
private ActionBar ab;
private DrawerLayout dl;
private ListView lv;
private ActionBarDrawerToggle tg;
private LinearLayout navdrawer;
private List<ItensListView> fragments;
private CharSequence tl; //titulo principal
private CharSequence tlf; //titulo fragment
public static final String APP_NAME = "App";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_drawerlayout);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.action_bar)));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar_custom);
init();
openFrag();
}
private void openFrag(){
//verifica notificacao e abre o fragment correspondente
String url = getIntent().getStringExtra("url") != null ? getIntent().getStringExtra("url") : null;
Log.i("URL_NOTIFICACAO->", url != null ? url : "");
if(url != null) {
if (url.equals("Noticias")) {
selectedItem(0);
} else if (url.equals("Eventos")) {
selectedItem(1);
} else if (url.equals("Tarefas") ||
url.equals("Advertencias") ||
url.equals("Agendas")) {
Log.i("Notificacao", url);
Log.i("LOGADO NA SESSION", SessionUsuario.isLogged(this) + "");
if(SessionUsuario.isLogged(this)){
Log.i("Notificao Logado", "esta logado na area do aluno");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment frag = AreaAlunoFrag.newInstance();
frag.getArguments().putString("url", url);
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
}
}
}else{
Log.i("ENTREI FIRST FRAG->","ENTREEIII");
//if(savedInstanceState == null){
selectedItem(0);
//}
}
}
private void init(){
//actionbar
onConfigActionBar();
//listview
configItensListView();
//drawerlayout
dl = (DrawerLayout)findViewById(R.id.dl);
navdrawer = (LinearLayout)findViewById(R.id.navdrawer);
//listview
lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new DrawerLayoutListViewAdapter(this, fragments));
lv.setOnItemClickListener(this);
//drawerlayout
//dl = (DrawerLayout)findViewById(R.id.dl);
//mDrawerRelativeLayout = (RelativeLayout)findViewById(R.id.left_drawer);
//actionbardrawertoggle
tg = new ActionBarDrawerToggle(this, dl, R.drawable.ic_launcher, R.string.drawer_open){
public void onDrawerClosed(View view) {
ab.setTitle(tl);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
ab.setTitle(tlf);
supportInvalidateOptionsMenu();
}
};
dl.setDrawerListener(tg);
tl = tlf = getTitle();
}
/** ativa actionbar e botao home na action bar */
private void onConfigActionBar(){
ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
tg.onConfigurationChanged(newConfig);
}
/** necessario */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
tg.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (tg.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** necessario */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_drawer_layout, menu);
return true;
}
/** necessario */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean status = dl.isDrawerOpen(navdrawer);
//menu.findItem(R.id.action_settings).setVisible(!status);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Log.i("POSITION->", position + "");
selectedItem(position);
}
/** seleciona o fragment q sera usado */
private void selectedItem(int position){
FragmentTransaction ft;
Fragment frag;
switch (position){
case 0:
ft = getSupportFragmentManager().beginTransaction();
frag = NoticiaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 1:
ft = getSupportFragmentManager().beginTransaction();
frag = EventoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 2:
ft = getSupportFragmentManager().beginTransaction();
frag = LoginFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 3:
ft = getSupportFragmentManager().beginTransaction();
frag = ContatoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 4:
ft = getSupportFragmentManager().beginTransaction();
frag = CompartilhaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 5:
ft = getSupportFragmentManager().beginTransaction();
frag = SobreFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
default:
closeApp();
break;
}
lv.setItemChecked(position, true);
setCustomTitle(fragments.get(position).getTexto());
dl.closeDrawer(navdrawer);
}
/** define o titulo da actionbar */
private void setCustomTitle(String title){
//SpannableString s = new SpannableString(title);
// s.setSpan(new TypefaceSpan(this, BatalhaConfigs.FONT), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//ab.setTitle(s);
//tl = s;
}
#Override
public void onBackPressed() {
//if(getSupportFragmentManager().getBackStackEntryCount() > 0){
// getSupportFragmentManager().popBackStackImmediate();
// }else{
super.onBackPressed();
//}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
}
/** Configura o List com as informacoes **/
private void configItensListView(){
fragments = new ArrayList<ItensListView>();
//define
ItensListView itens0 = new ItensListView("Noticias", R.drawable.setavermelha);
ItensListView itens1 = new ItensListView("Eventos", R.drawable.setavermelha);
ItensListView itens2 = new ItensListView("Área do Aluno", R.drawable.setavermelha);
ItensListView itens3 = new ItensListView("Contato", R.drawable.setavermelha);
ItensListView itens4 = new ItensListView("Redes Sociais", R.drawable.setavermelha);
ItensListView itens5 = new ItensListView("Sobre", R.drawable.setavermelha);
ItensListView itens6 = new ItensListView("Sair", R.drawable.setavermelha);
//add
fragments.add(itens0);
fragments.add(itens1);
fragments.add(itens2);
fragments.add(itens3);
fragments.add(itens4);
fragments.add(itens5);
fragments.add(itens6);
//AreaAlunoFrag
}
private void closeApp(){
System.exit(0);
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//super.onSaveInstanceState(outState, outPersistentState);
getSupportFragmentManager().beginTransaction().commitAllowingStateLoss();
}
private void removeAllFrags(){
FragmentManager fm = getSupportFragmentManager();
for(int x = 0; x < fm.getBackStackEntryCount(); x++){
getSupportFragmentManager().beginTransaction().remove(fm.findFragmentById(x)).commit();
}
finish();
}
#Override
protected void onStart() {
new SendProjectId(getApplicationContext());
super.onStart();
}
#Override
protected void onResume() {
PushControl.setIsVisible(true);
new SendProjectId(getApplicationContext());
super.onResume();
}
#Override
protected void onPause() {
PushControl.setIsVisible(false);
super.onPause();
}
#Override
protected void onStop() {
PushControl.setIsVisible(false);
removeAllFrags();
super.onStop();
}
#Override
protected void onDestroy() {
PushControl.setIsVisible(false);
super.onDestroy();
CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
Exception
java.lang.RuntimeException: Unable to stop activity {br.com.ferpapps.santaluzapp/br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3323)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3369)
at android.app.ActivityThread.access$1000(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1343)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1365)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1383)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:636)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:615)
at br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout.removeAllFrags(CustomDrawerLayout.java:320)
at br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout.onStop(CustomDrawerLayout.java:348)
at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1229)
at android.app.Activity.performStop(Activity.java:5516)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3320)
            at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3369)
            at android.app.ActivityThread.access$1000(ActivityThread.java:159)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1343)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)

I have had this problem, If you call getFragmentManager() after SaveInstaceState is called you will get an error.
change
#Override
protected void onStop() {
PushControl.setIsVisible(false);
removeAllFrags();
super.onStop();
}
to
#Override
protected void onPause() {
PushControl.setIsVisible(false);
removeAllFrags();
super.onPause();
}

Try remove
finish();
from your removeAllFrags() method;

Related

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/

Android fragment change orientation and NullPointerException

i try create app on fragment, but i have some error:
FATAL EXCEPTION: main Process: pl.pionas.zabawa, PID: 3074
java.lang.NullPointerException
at pl.pionas.zabawa.Fragments.HomeFragment.initializeListViewPromo(HomeFragment.java:77)
at pl.pionas.zabawa.Fragments.HomeFragment.OnTaskCompletedArticlesPromo(HomeFragment.java:71)
at pl.pionas.zabawa.AsyncTasks.ArticlesPromoAsyncTask$1.onResponse(ArticlesPromoAsyncTask.java:70)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
This error is when i change class fragment (example go to LoginFragment.class) and orientation.
My MainMenuActivity.class:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
private Fragment fragment = null;
private Boolean restore = false;
private String mTitle;
FragmentManager fragmentManager;
private Boolean action = false;
String tag = null;
private int prev;
private ArrayList<MenuFragment> mapMenu = new ArrayList<MenuFragment>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
if (savedInstanceState != null) {
fragment = fragmentManager.getFragment(savedInstanceState, "currentFragment");
restore = savedInstanceState.getBoolean("restore");
mTitle = savedInstanceState.getString("mTitle");
mapMenu = savedInstanceState.getParcelableArrayList("mapMenu");
tag = fragment.getTag();
} else {
fragment = new HomeFragment();
mapMenu.add(new MenuFragment(getString(R.string.app_name), 0));
restore = false;
mTitle = getString(R.string.app_name);
tag = mTitle;
}
if (fragment != null) {
fragmentManager.beginTransaction().replace(R.id.flContent, fragment, tag).addToBackStack(tag).commit();
if (restore) {
fragmentManager.findFragmentByTag(tag);
} else {
fragmentManager.beginTransaction().replace(R.id.flContent, fragment, tag).addToBackStack(tag).commit();
}
}
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(mTitle);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
View headerLayout = nvDrawer.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
ImageView ivHeaderPhoto = (ImageView) headerLayout.findViewById(R.id.imageView);
Drawable myDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.logo, null);
ivHeaderPhoto.setImageDrawable(myDrawable);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
// `onPostCreate` called when activity start-up is complete after `onStart()`
// NOTE! Make sure to override the method with only a single `Bundle` argument
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
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) {
int menuId = menuItem.getItemId();
if (prev == menuId) {
mDrawer.closeDrawers();
return;
}
prev = menuId;
createNewFragment(menuId, true);
}
private void createNewFragment(int menuId, boolean add) { // Create a new fragment and specify the fragment to show based on nav item clicked
Class fragmentClass;
action = true;
int position = 0;
switch (menuId) {
case R.id.nav_login:
fragmentClass = LoginFragment.class;
mTitle = getString(R.string.menu_login);
position = 1;
break;
case R.id.nav_articles:
fragmentClass = CategoryFragment.class;
mTitle = getString(R.string.menu_articles);
position = 2;
break;
default:
fragmentClass = HomeFragment.class;
mTitle = APP_NAME;
break;
}
if (add) {
mapMenu.add(new MenuFragment(mTitle, menuId));
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
tag = mTitle;
if (action) {
// Insert the fragment by replacing any existing fragment
fragmentManager.beginTransaction().replace(R.id.flContent, fragment, tag).addToBackStack(tag).commit();
// Highlight the selected item has been done by NavigationView
nvDrawer.getMenu().getItem(position).setChecked(true);
}
// Set action bar title
getSupportActionBar().setTitle(mTitle);
// Close the navigation drawer
mDrawer.closeDrawers();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("restore", true);
outState.putParcelableArrayList("mapMenu", mapMenu);
outState.putString("mTitle", getSupportActionBar().getTitle().toString());
getSupportFragmentManager().putFragment(outState, "currentFragment", fragment);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
int i = mapMenu.size();
if (i > 1) {
mapMenu.remove(i - 1);
MenuFragment menuFragment = mapMenu.get((i - 2));
tag = menuFragment.getTitle();
createNewFragment(menuFragment.getMenuPosition(), false);
} else {
MainActivity.this.finish();
}
}
} }
My HomeFragment.class:
public class HomeFragment extends Fragment implements OnTaskCompletedArticlesLastAdded {
private ListView listViewLastAdded;
private ArrayList<Article> articleLastAddedList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArticlesLastAddedAsyncTask articlesLastAddedAsyncTask = new ArticlesLastAddedAsyncTask(getContext(), this);
articlesLastAddedAsyncTask.execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
listViewLastAdded = (ListView) rootView.findViewById(R.id.listViewLastAdded);
return rootView;
}
#Override
public void OnTaskCompletedArticlesLastAdded(ArrayList<Article> articleList) {
articleLastAddedList = articleList;
initializeListLastAdded();
}
private void initializeListLastAdded() {
ArticlesListAdapter adapter = new ArticlesListAdapter(getContext(), articleLastAddedList);
listViewLastAdded.setAdapter(adapter);
}
}
What i do wrong?
Thanks for help.
If you don't want Android to restart the activity when screen is rotated (this destroys your fragment and causes NULLPointer exception) you can add
android:configChanges="orientation|screenSize"
inside the activity tag in your Androidmanifest.xml

Notification does not open the fragment?

I created a Notification and I want it to open a Fragment when clicked. It works in general, but when I have another Fragment open in my application at the time, it does not work.
For example, I have two Fragments: NoticiaFrag and EventoFrag. If I open my application and open the NoticiaFrag after pressing the home button of the device to minimize the application and receiving a notification to EventoFrag, when I click the notification opens NoticiaFrag and not EventoFrag.
To make this work I need close the application with the back button. After the application closes it works fine. I think I need to reopen the application when I click the Notification, but I don't know how.
The method that opens the Fragments from the Notification is in CustomDrawerLayout and called openFrag().
How can I solve this issue?
Notification
public class SendNotification {
public SendNotification(Context context, String title, String tickerText, String message, String url) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent;
Intent intent = new Intent(context, CustomDrawerLayout.class);
Bundle bd = new Bundle();
bd.putString("url", url);
intent.putExtras(bd);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setTicker(tickerText)
.setContentTitle(title)
.setShowWhen(true)
.setWhen(System.currentTimeMillis())
.setContentText(message);
mBuilder.setContentIntent(contentIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.vibrate = new long[]{150, 300, 150, 600};
mNotificationManager.notify(AndroidSystemUtil.randInt(), notification);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.ferpapps.santaluzapp" >
<!--Internet -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--GCM Permissions -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name=".permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name=".permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
<!---->
<!-- permissoes extra -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:name=".cv.CustomVolleySingleton"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<!-- GCM -->
<receiver
android:name=".push.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="br.com.ferpapps" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service
android:name=".push.GcmIntentService" >
</service>
<!-- close GCM -->
<activity
android:name=".act.SplashView"
android:label="#string/app_name"
android:windowSoftInputMode="adjustPan|adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".menu.CustomDrawerLayout"/>
<activity android:name=".act.AreaAlunoMainActivity" />
</application>
</manifest>
ActionBarActivity
public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{
private ActionBar ab;
private DrawerLayout dl;
private ListView lv;
private ActionBarDrawerToggle tg;
private LinearLayout navdrawer;
private List<ItensListView> fragments;
private CharSequence tl; //titulo principal
private CharSequence tlf; //titulo fragment
public static final String APP_NAME = "App";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_drawerlayout);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.action_bar)));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar_custom);
init();
openFrag();
}
private void openFrag(){
//verifica notificacao e abre o fragment correspondente
String url = getIntent().getStringExtra("url") != null ? getIntent().getStringExtra("url") : null;
Log.i("URL_NOTIFICACAO->", url != null ? url : "");
if(url != null) {
//Open By Notification
if (url.equals("Noticias")) {
selectedItem(0);
} else if (url.equals("Eventos")) {
selectedItem(1);
} else if (url.equals("Tarefas") ||
url.equals("Advertencias") ||
url.equals("Agendas")) {
Log.i("Notificacao", url);
Log.i("LOGADO NA SESSION", SessionUsuario.isLogged(this) + "");
if(SessionUsuario.isLogged(this)){
Log.i("Notificao Logado", "esta logado na area do aluno");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment frag = AreaAlunoFrag.newInstance();
frag.getArguments().putString("url", url);
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
}
}
}else{
Log.i("ENTREI FIRST FRAG->","ENTREEIII");
//if(savedInstanceState == null){
selectedItem(0);
//}
}
}
private void init(){
//actionbar
onConfigActionBar();
//listview
configItensListView();
//drawerlayout
dl = (DrawerLayout)findViewById(R.id.dl);
navdrawer = (LinearLayout)findViewById(R.id.navdrawer);
//listview
lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new DrawerLayoutListViewAdapter(this, fragments));
lv.setOnItemClickListener(this);
//drawerlayout
//dl = (DrawerLayout)findViewById(R.id.dl);
//mDrawerRelativeLayout = (RelativeLayout)findViewById(R.id.left_drawer);
//actionbardrawertoggle
tg = new ActionBarDrawerToggle(this, dl, R.drawable.ic_launcher, R.string.drawer_open){
public void onDrawerClosed(View view) {
ab.setTitle(tl);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
ab.setTitle(tlf);
supportInvalidateOptionsMenu();
}
};
dl.setDrawerListener(tg);
tl = tlf = getTitle();
}
/** ativa actionbar e botao home na action bar */
private void onConfigActionBar(){
ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
tg.onConfigurationChanged(newConfig);
}
/** necessario */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
tg.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (tg.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** necessario */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_drawer_layout, menu);
return true;
}
/** necessario */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean status = dl.isDrawerOpen(navdrawer);
//menu.findItem(R.id.action_settings).setVisible(!status);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Log.i("POSITION->", position + "");
selectedItem(position);
}
/** seleciona o fragment q sera usado */
private void selectedItem(int position){
FragmentTransaction ft;
Fragment frag;
switch (position){
case 0:
ft = getSupportFragmentManager().beginTransaction();
frag = NoticiaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 1:
ft = getSupportFragmentManager().beginTransaction();
frag = EventoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 2:
ft = getSupportFragmentManager().beginTransaction();
frag = LoginFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 3:
ft = getSupportFragmentManager().beginTransaction();
frag = ContatoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 4:
ft = getSupportFragmentManager().beginTransaction();
frag = CompartilhaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 5:
ft = getSupportFragmentManager().beginTransaction();
frag = SobreFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
default:
closeApp();
break;
}
lv.setItemChecked(position, true);
setCustomTitle(fragments.get(position).getTexto());
dl.closeDrawer(navdrawer);
}
/** define o titulo da actionbar */
private void setCustomTitle(String title){
//SpannableString s = new SpannableString(title);
// s.setSpan(new TypefaceSpan(this, BatalhaConfigs.FONT), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//ab.setTitle(s);
//tl = s;
}
#Override
public void onBackPressed() {
//if(getSupportFragmentManager().getBackStackEntryCount() > 0){
// getSupportFragmentManager().popBackStackImmediate();
// }else{
super.onBackPressed();
//}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
}
/** Configura o List com as informacoes **/
private void configItensListView(){
fragments = new ArrayList<ItensListView>();
//define
ItensListView itens0 = new ItensListView("Noticias", R.drawable.setavermelha);
ItensListView itens1 = new ItensListView("Eventos", R.drawable.setavermelha);
ItensListView itens2 = new ItensListView("Área do Aluno", R.drawable.setavermelha);
ItensListView itens3 = new ItensListView("Contato", R.drawable.setavermelha);
ItensListView itens4 = new ItensListView("Redes Sociais", R.drawable.setavermelha);
ItensListView itens5 = new ItensListView("Sobre", R.drawable.setavermelha);
ItensListView itens6 = new ItensListView("Sair", R.drawable.setavermelha);
//add
fragments.add(itens0);
fragments.add(itens1);
fragments.add(itens2);
fragments.add(itens3);
fragments.add(itens4);
fragments.add(itens5);
fragments.add(itens6);
//AreaAlunoFrag
}
private void closeApp(){
System.exit(0);
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//super.onSaveInstanceState(outState, outPersistentState);
getSupportFragmentManager().beginTransaction().commitAllowingStateLoss();
}
private void removeAllFrags(){
FragmentManager fm = getSupportFragmentManager();
for(int x = 0; x < fm.getBackStackEntryCount(); x++){
//getSupportFragmentManager().beginTransaction().remove(fm.findFragmentById(x)).commit();
fm.popBackStackImmediate();
}
}
#Override
protected void onStart() {
new SendProjectId(getApplicationContext());
super.onStart();
}
#Override
protected void onResume() {
PushControl.setIsVisible(true);
new SendProjectId(getApplicationContext());
super.onResume();
}
#Override
protected void onPause() {
PushControl.setIsVisible(false);
super.onPause();
}
#Override
protected void onStop() {
PushControl.setIsVisible(false);
//removeAllFrags();
super.onStop();
}
#Override
protected void onDestroy() {
PushControl.setIsVisible(false);
super.onDestroy();
CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
Update CustomDrawerLayout and Manifest - It works fine.
CustomDrawerLayout
public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{
private ActionBar ab;
private DrawerLayout dl;
private ListView lv;
private ActionBarDrawerToggle tg;
private LinearLayout navdrawer;
private List<ItensListView> fragments;
private CharSequence tl; //titulo principal
private CharSequence tlf; //titulo fragment
public static final String APP_NAME = "App";
private static String URL_NOTIFICATION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_drawerlayout);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.action_bar)));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar_custom);
init();
if(savedInstanceState == null){
selectedItem(0);
}
}
/** open fragment by notification */
private void openFragByNotification(){
if(!URL_NOTIFICATION.isEmpty()) {
//Open By Notification
if (URL_NOTIFICATION.equals("Noticias")) {
selectedItem(0);
} else if (URL_NOTIFICATION.equals("Eventos")) {
selectedItem(1);
} else if (URL_NOTIFICATION.equals("Tarefas") ||
URL_NOTIFICATION.equals("Advertencias") ||
URL_NOTIFICATION.equals("Agendas")) {
Log.i("Notificacao", URL_NOTIFICATION);
Log.i("LOGADO NA SESSION", SessionUsuario.isLogged(this) + "");
if(SessionUsuario.isLogged(this)){
Log.i("Notificao Logado", "esta logado na area do aluno");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment frag = AreaAlunoFrag.newInstance();
frag.getArguments().putString("url", URL_NOTIFICATION);
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
}
}
}
}
private void init(){
//actionbar
onConfigActionBar();
//listview
configItensListView();
//drawerlayout
dl = (DrawerLayout)findViewById(R.id.dl);
navdrawer = (LinearLayout)findViewById(R.id.navdrawer);
//listview
lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new DrawerLayoutListViewAdapter(this, fragments));
lv.setOnItemClickListener(this);
//drawerlayout
//dl = (DrawerLayout)findViewById(R.id.dl);
//mDrawerRelativeLayout = (RelativeLayout)findViewById(R.id.left_drawer);
//actionbardrawertoggle
tg = new ActionBarDrawerToggle(this, dl, R.drawable.ic_launcher, R.string.drawer_open){
public void onDrawerClosed(View view) {
ab.setTitle(tl);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
ab.setTitle(tlf);
supportInvalidateOptionsMenu();
}
};
dl.setDrawerListener(tg);
tl = tlf = getTitle();
}
/** ativa actionbar e botao home na action bar */
private void onConfigActionBar(){
ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
tg.onConfigurationChanged(newConfig);
}
/** necessario */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
tg.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (tg.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** necessario */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_drawer_layout, menu);
return true;
}
/** necessario */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean status = dl.isDrawerOpen(navdrawer);
//menu.findItem(R.id.action_settings).setVisible(!status);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Log.i("POSITION->", position + "");
selectedItem(position);
}
/** seleciona o fragment q sera usado */
private void selectedItem(int position){
FragmentTransaction ft;
Fragment frag;
switch (position){
case 0:
ft = getSupportFragmentManager().beginTransaction();
frag = NoticiaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 1:
ft = getSupportFragmentManager().beginTransaction();
frag = EventoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 2:
ft = getSupportFragmentManager().beginTransaction();
frag = LoginFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 3:
ft = getSupportFragmentManager().beginTransaction();
frag = ContatoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 4:
ft = getSupportFragmentManager().beginTransaction();
frag = CompartilhaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 5:
ft = getSupportFragmentManager().beginTransaction();
frag = SobreFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
default:
closeApp();
break;
}
lv.setItemChecked(position, true);
setCustomTitle(fragments.get(position).getTexto());
dl.closeDrawer(navdrawer);
}
/** define o titulo da actionbar */
private void setCustomTitle(String title){
//SpannableString s = new SpannableString(title);
// s.setSpan(new TypefaceSpan(this, BatalhaConfigs.FONT), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//ab.setTitle(s);
//tl = s;
}
#Override
public void onBackPressed() {
//if(getSupportFragmentManager().getBackStackEntryCount() > 0){
// getSupportFragmentManager().popBackStackImmediate();
// }else{
super.onBackPressed();
//}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
}
/** Configura o List com as informacoes **/
private void configItensListView(){
fragments = new ArrayList<ItensListView>();
//define
ItensListView itens0 = new ItensListView("Noticias", R.drawable.setavermelha);
ItensListView itens1 = new ItensListView("Eventos", R.drawable.setavermelha);
ItensListView itens2 = new ItensListView("Área do Aluno", R.drawable.setavermelha);
ItensListView itens3 = new ItensListView("Contato", R.drawable.setavermelha);
ItensListView itens4 = new ItensListView("Redes Sociais", R.drawable.setavermelha);
ItensListView itens5 = new ItensListView("Sobre", R.drawable.setavermelha);
ItensListView itens6 = new ItensListView("Sair", R.drawable.setavermelha);
//add
fragments.add(itens0);
fragments.add(itens1);
fragments.add(itens2);
fragments.add(itens3);
fragments.add(itens4);
fragments.add(itens5);
fragments.add(itens6);
//AreaAlunoFrag
}
private void closeApp(){
System.exit(0);
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//super.onSaveInstanceState(outState, outPersistentState);
getSupportFragmentManager().beginTransaction().commitAllowingStateLoss();
}
private void removeAllFrags(){
FragmentManager fm = getSupportFragmentManager();
for(int x = 0; x < fm.getBackStackEntryCount(); x++){
//getSupportFragmentManager().beginTransaction().remove(fm.findFragmentById(x)).commit();
fm.popBackStackImmediate();
}
}
#Override
protected void onNewIntent(Intent intent) {
URL_NOTIFICATION = intent.getStringExtra("url");
Log.i("URL_NOTIFICATION", URL_NOTIFICATION);
super.onNewIntent(intent);
}
#Override
protected void onStart() {
new SendProjectId(getApplicationContext());
super.onStart();
}
#Override
protected void onResume() {
PushControl.setIsVisible(true);
new SendProjectId(getApplicationContext());
openFragByNotification();
super.onResume();
}
#Override
protected void onPause() {
PushControl.setIsVisible(false);
URL_NOTIFICATION = "";
super.onPause();
}
#Override
protected void onStop() {
PushControl.setIsVisible(false);
URL_NOTIFICATION = "";
super.onStop();
}
#Override
protected void onDestroy() {
PushControl.setIsVisible(false);
super.onDestroy();
CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
Manifest
<activity android:name=".menu.CustomDrawerLayout" android:launchMode="singleTop"/>
The problem is that Android by default doesn't deliver a new Intent to an Activity that is already running. If you close your app via the back button, the Activity is destroyed and the next time startActivity() is called a new instance is created and the new Intent delivered. If you leave the Activity via the home button, the Activity is not destroyed. When you call startActivity() in this case, the already running instance of the Activity is brought to the foreground, but a new Intent is not delivered.
To change this behaviour you can define your activity in the manifest with launchMode="singleTop":
<activity
...
android:launchMode="singleTop"
...
>
</activity>
In this case Android will deliver a new Intent via onNewIntent(), which you can override:
This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
Just noticed the flags you're passing into your Intent. In that case you probably just have to override onNewIntent() in your Activity.
I've run into this problem myself before and asked a question here. There's some more background in that question, the accepted answer, and the comments.

Creating header to drawerlayout?

I'm trying create a Header to my DrawerLayout. When I add ImageView does throws an exception and stop the app.
How could I do this ?
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/dl"
android:background="#drawable/splash"
>
<FrameLayout
android:id="#+id/fl"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<LinearLayout
android:layout_width="250dp"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:src="#drawable/logo"
/>
<ListView
android:id="#+id/lv"
android:layout_width="250dp"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="#DCDCDC"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:dividerHeight="1dp"
android:background="#color/action_bar"
android:layout_gravity="start"
>
</ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
ActionBarActivity
public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{
private ActionBar ab;
private DrawerLayout dl;
private ListView lv;
private ActionBarDrawerToggle tg;
private List<ItensListView> fragments;
private CharSequence tl; //titulo principal
private CharSequence tlf; //titulo fragment
public static final String APP_NAME = "App";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_drawerlayout);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.action_bar)));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar_custom);
init();
if(savedInstanceState == null){
selectedItem(0);
}
}
private void init(){
//actionbar
onConfigActionBar();
//listview
configItensListView();
lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new DrawerLayoutListViewAdapter(this, fragments));
lv.setOnItemClickListener(this);
//drawerlayout
dl = (DrawerLayout)findViewById(R.id.dl);
//actionbardrawertoggle
tg = new ActionBarDrawerToggle(this, dl, R.drawable.ic_launcher, R.string.drawer_open){
public void onDrawerClosed(View view) {
ab.setTitle(tl);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
ab.setTitle(tlf);
supportInvalidateOptionsMenu();
}
};
dl.setDrawerListener(tg);
tl = tlf = getTitle();
}
/** ativa actionbar e botao home na action bar */
private void onConfigActionBar(){
ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
tg.onConfigurationChanged(newConfig);
}
/** necessario */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
tg.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (tg.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** necessario */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_drawer_layout, menu);
return true;
}
/** necessario */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean status = dl.isDrawerOpen(lv);
menu.findItem(R.id.action_settings).setVisible(!status);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Log.i("POSITION->", position + "");
selectedItem(position);
}
/** seleciona o fragment q sera usado */
private void selectedItem(int position){
FragmentTransaction ft;
Fragment frag;
switch (position){
case 0:
ft = getSupportFragmentManager().beginTransaction();
frag = NoticiaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack("NoticiaFrag");
ft.commit();
break;
case 1:
ft = getSupportFragmentManager().beginTransaction();
frag = EventoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 2:
ft = getSupportFragmentManager().beginTransaction();
frag = LoginFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 3:
ft = getSupportFragmentManager().beginTransaction();
frag = ContatoFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 4:
ft = getSupportFragmentManager().beginTransaction();
frag = CompartilhaFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
case 5:
ft = getSupportFragmentManager().beginTransaction();
frag = SobreFrag.newInstance();
ft.replace(R.id.fl, frag);
ft.addToBackStack(APP_NAME);
ft.commit();
break;
default:
closeApp();
break;
}
lv.setItemChecked(position, true);
setCustomTitle(fragments.get(position).getTexto());
dl.closeDrawer(lv);
}
/** define o titulo da actionbar */
private void setCustomTitle(String title){
//SpannableString s = new SpannableString(title);
// s.setSpan(new TypefaceSpan(this, BatalhaConfigs.FONT), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//ab.setTitle(s);
//tl = s;
}
#Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportFragmentManager().popBackStackImmediate();
}else{
super.onBackPressed();
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
}
/** Configura o List com as informacoes **/
private void configItensListView(){
fragments = new ArrayList<ItensListView>();
//define
ItensListView itens0 = new ItensListView("Noticias", R.drawable.setavermelha);
ItensListView itens1 = new ItensListView("Eventos", R.drawable.setavermelha);
ItensListView itens2 = new ItensListView("Área do Aluno", R.drawable.setavermelha);
ItensListView itens3 = new ItensListView("Contato", R.drawable.setavermelha);
ItensListView itens4 = new ItensListView("Redes Sociais", R.drawable.setavermelha);
ItensListView itens5 = new ItensListView("Sobre", R.drawable.setavermelha);
ItensListView itens6 = new ItensListView("Sair", R.drawable.setavermelha);
//add
fragments.add(itens0);
fragments.add(itens1);
fragments.add(itens2);
fragments.add(itens3);
fragments.add(itens4);
fragments.add(itens5);
fragments.add(itens6);
//AreaAlunoFrag
}
private void closeApp(){
System.exit(0);
}
#Override
protected void onResume() {
PushControl.setIsVisible(true);
super.onResume();
}
#Override
protected void onPause() {
PushControl.setIsVisible(false);
super.onPause();
}
#Override
protected void onStop() {
PushControl.setIsVisible(false);
super.onStop();
}
#Override
protected void onDestroy() {
PushControl.setIsVisible(false);
super.onDestroy();
CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
Exception
java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.ferpapps.santaluzapp/br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout}: java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.support.v4.widget.DrawerLayout$LayoutParams
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.support.v4.widget.DrawerLayout$LayoutParams
at android.support.v4.widget.DrawerLayout.isDrawerView(DrawerLayout.java:1100)
at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1305)
at br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout.selectedItem(CustomDrawerLayout.java:210)
at br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout.onCreate(CustomDrawerLayout.java:66)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
            at android.app.ActivityThread.access$700(ActivityThread.java:159)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)
Try this:
<LinearLayout
android:id="#+id/navdrawer"
android:layout_width="250dp"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
...
/>
<ListView
...
>
</ListView>
</LinearLayout>
and
LinearLayout ll = (LinearLayout) findViewById(R.id.navdrawer);
...
dl.isDrawerOpen(ll);
...
dl.closeDrawer(ll);

android.view.InflateException not sure why its force closing

I have an error I am having trouble reproducing. I think it comes about when the app is being used then the user switches aps and of goes to the homescreen for awhile then comes back to my app. The full error is:
android.view.InflateException: Couldn't resolve menu item onClick handler
goToSearch in class android.view.ContextThemeWrapper
at android.view.MenuInflater$InflatedOnMenuItemClickListener
.<init>(MenuInflater.java:202)
at android.view.MenuInflater$MenuState.setItem(MenuInflater.java:402)
at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:436)
at android.view.MenuInflater.parseMenu(MenuInflater.java:173)
at android.view.MenuInflater.inflate(MenuInflater.java:95)
at com.beerportfolio.beerportfoliopro.MainDrawer2.onCreateOptionsMenu(MainDrawer2.java:172)
at android.app.Activity.onCreatePanelMenu(Activity.java:2513)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:415)
at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:770)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:3179)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:5060)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by: java.lang.NoSuchMethodException:
goToSearch [interface android.view.MenuItem]
at java.lang.Class.getConstructorOrMethod(Class.java:460)
at java.lang.Class.getMethod(Class.java:915)
at android.view.MenuInflater$InflatedOnMenuItemClickListener.<init>(MenuInflater.java:200)
at android.view.MenuInflater$MenuState.setItem(MenuInflater.java:402)
at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:436)
at android.view.MenuInflater.parseMenu(MenuInflater.java:173)
at android.view.MenuInflater.inflate(MenuInflater.java:95)
at com.beerportfolio.beerportfoliopro.MainDrawer2.onCreateOptionsMenu(MainDrawer2.java:172)
at android.app.Activity.onCreatePanelMenu(Activity.java:2513)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:415)
at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:770)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:3179)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:5060)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(NativeStart.java)
My main drawer2 class looks like this:
public class MainDrawer2 extends FragmentActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(
Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
displayNavFragment((MainNavItem)parent
.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null) {
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem) {
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else {
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item) {
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item) {
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode,
int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator
.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting,
//load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BarcodeFrag(scanContent);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
Lastly my menu xml looks like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<item android:id="#+id/menu_search2"
android:actionViewClass="android.widget.SearchView"
android:title="Search"
android:icon="#android:drawable/ic_menu_search"
android:showAsAction="always|collapseActionView"
android:onClick="goToSearch" />
<item android:id="#+id/action_scan"
android:icon="#drawable/barcode"
android:onClick="scanBarcode"
android:showAsAction="ifRoom|collapseActionView"/>
</menu>
I cannot for the life of me figure out where this error is coming from.
I would recommend using the onOptionsItemSelected mechanism if possible instead of manually wiring the click methods.
Take a look at the documentation:
Android Developer Guide:Menus
You might have found a platform bug. Does it still happen if you set your activity theme to Theme.Holo or Theme.Holo.Light? Specifically, try it with something that isn't based on Theme.Holo.Light.DarkActionBar.
If this fixes your original problem please report this at http://b.android.com.
You have wrong method signature.
This is yours
public void goToSearch(MenuItem item){
}
This is how it should be
public void goToSearch(View v){
}
please see
http://developer.android.com/reference/android/R.attr.html#onClick
for reference

Categories

Resources