Creating header to drawerlayout? - android

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);

Related

Change from drawer icon to arrow when using a NavigationView

I have an Activity that uses a NavigationView to display my app menu.
When menu opens and closes my App bar change from the drawer icon to the back arrow as expected.
I have a scenario, where i click on item 1 from my app menu, and it opens a fragment in my FrameLayout, and then i need to click a button that opens another fragment, replacing the previous one.
The app bar has the drawer icon in the 2 fragments, and i want to have a back arrow on the second fragment, so i can return to first fragment
Here is my MainActivity
public class MainActivity extends SuperActivity {
#BindView(R.id.nav_view) NavigationView navigationView;
#BindView(R.id.drawer_layout) DrawerLayout drawerLayout;
#BindView(R.id.container) FrameLayout frameLayout;
#BindView(R.id.toolbar) Toolbar toolbar;
ActionBarDrawerToggle drawerToggle;
SuperFragment nextFragment;
FragmentManager fragmentManager;
String activeName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fragmentManager = getSupportFragmentManager();
setupView();
if (savedInstanceState == null) showHome();
}
private void setupView() {
setSupportActionBar(toolbar);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerLayout.setScrimColor(Color.TRANSPARENT);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
setupDrawerContent(navigationView);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(Gravity.LEFT);
activeName = item.getTitle().toString();
toolbar.setTitle(activeName);
selectDrawerItem(item);
return false;
}
});
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
private void showHome() {
selectDrawerItem(navigationView.getMenu().getItem(0));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
private void selectDrawerItem(MenuItem menuItem) {
drawerLayout.closeDrawer(Gravity.LEFT);
switch (menuItem.getItemId()) {...}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
drawerToggle.syncState();
super.onPostCreate(savedInstanceState);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
private Runnable Logout_Callback = new Runnable() {
public void run() {
Toast.makeText(getApplication(),"Log out",Toast.LENGTH_SHORT).show();
}
};
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
that extends from this
public class SuperActivity extends AppCompatActivity implements InterfaceHostActivity{
private SuperFragment selectedFragment;
// Navigation adapter
public NavigationListAdapter mNavigationAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void replaceFragment(SuperFragment fragment, boolean addToBackStack) {
replaceFragment(fragment, addToBackStack, R.id.container);
}
public void replaceFragment(SuperFragment fragment, boolean addToBackStack, int layout) {
try {
FragmentManager manager = getSupportFragmentManager();
if (fragment.isMainFragment) {
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
String backStateName = ((Object) fragment).getClass().getName();
boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
FragmentTransaction ft = manager.beginTransaction();
ft.replace(layout, fragment, backStateName);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
if (addToBackStack)
ft.addToBackStack(backStateName);
ft.commit();
}
getSupportFragmentManager().executePendingTransactions();
} catch (Exception e) {
LogManager.logException(e);
}
}
#Override
public void setSelectedFragment(SuperFragment fragment) {
this.selectedFragment = fragment;
}
#Override
public void popBackStack() {
getSupportFragmentManager().popBackStackImmediate();
}
#Override
public void popBackStackUntilTag(String tag) {
getSupportFragmentManager().popBackStackImmediate(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
#Override
public void addFragment(SuperFragment fragment, boolean addToBackStack) {
try {
String backStateName = ((Object) fragment).getClass().getName();
String fragmentTag = backStateName;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
if (addToBackStack)
ft.addToBackStack(backStateName);
ft.commit();
} catch (Exception e) {
LogManager.logException(e);
}
}
#Override
public void addMultipleFragments(SuperFragment[] fragments) {
}
#Override
public void onBackPressed() {
boolean eventConsumed = false;
if (selectedFragment != null) {
eventConsumed = eventConsumed || selectedFragment.onBackPressed();
}
if (!eventConsumed) {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}
and my XML
<android.support.v4.widget.DrawerLayout 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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pt.sibs.android.mpos.activities.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
<include layout="#layout/toolbar" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:customTypeface="#string/font_lato_light"
android:background="#color/menuBG"
android:layout_marginTop="?attr/actionBarSize"
app:itemTextColor="#color/drawer_text_color_selector"
app:itemTextAppearance="#style/TextViewBody"
app:itemIconTint="#color/menu_icon_selector"
app:itemBackground="#drawable/menu_item_bg"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>

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

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;

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.

android.view.InflateException: Binary XML file line #28: Error inflating class fragment

I'm trying to develop an app that has a Navigation Drawer and a Fragment to display data. This is my app activity stack:
->Login(checks if it's logged in, it skips loading the view and proceeds to Timeline)
->Timeline
This is the way I get the error:
->I start the app
->It bypasses the Login screen because I'm already logged in
->Everything looks fine, then I click Log Out from the Menu Drawer or press Back Button
->I get back to the Login Screen
->Now if I press Login again and start the Timeline activity again, my app crashes...
Here are the codes. This is the logcat:
11-15 21:11:52.050 18695-18695/lazarko.pocketformulas E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{lazarko.pocketformulas/lazarko.pocketformulas.Timeline}: android.view.InflateException: Binary XML file line #28: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #28: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:324)
at android.app.Activity.setContentView(Activity.java:1912)
at lazarko.pocketformulas.Timeline.onCreate(Timeline.java:35)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
            at android.app.ActivityThread.access$600(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5520)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v4.widget.DrawerLayout.isDrawerView(DrawerLayout.java:1097)
at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1306)
at lazarko.pocketformulas.NavigationDrawerFragment.selectItem(NavigationDrawerFragment.java:209)
at lazarko.pocketformulas.NavigationDrawerFragment.onCreate(NavigationDrawerFragment.java:82)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:798)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1015)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1114)
at android.app.Activity.onCreateView(Activity.java:4722)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:324)
            at android.app.Activity.setContentView(Activity.java:1912)
            at lazarko.pocketformulas.Timeline.onCreate(Timeline.java:35)
            at android.app.Activity.performCreate(Activity.java:5066)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
            at android.app.ActivityThread.access$600(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5520)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
            at dalvik.system.NativeStart.main(Native Method)
This is my Activity code:
public class Timeline extends FragmentActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks, SearchView.OnQueryTextListener {
private static NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
public static Context context;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
context = getApplicationContext();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
public static Context getContext() {
return context;
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onStart();
FragmentManager fragmentManager = getSupportFragmentManager();
SharedPreferences preferencesFragmentData = getSharedPreferences("fragmentData", 0);
String fragmentID = preferencesFragmentData.getString("currentFragment", "");
if(fragmentID == "FAVORITES_FRAGMENT")
fragmentManager.beginTransaction().replace(R.id.container, new Favorites()).commit();
else if (fragmentID == "TIMELINE_FRAGMENT")
fragmentManager.beginTransaction().replace(R.id.container, new PlaceholderFragment()).commit();
else if (fragmentID == "SETTINGS_FRAGMENT")
fragmentManager.beginTransaction().replace(R.id.container, new Settings()).commit();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
SharedPreferences preferencesFragmentData = getSharedPreferences("fragmentData", 0);
SharedPreferences.Editor editorFragmentData = preferencesFragmentData.edit();
switch(position) {
case 1:
//Timeline clicked
editorFragmentData.putString("currentFragment", "TIMELINE_FRAGMENT");
editorFragmentData.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, new PlaceholderFragment(), "TIMELINE_FRAGMENT")
.commit();
break;
case 2:
//Favorites clicked
editorFragmentData.putString("currentFragment", "FAVORITES_FRAGMENT");
editorFragmentData.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, new Favorites(), "FAVORITES_FRAGMENT")
.commit();
break;
case 3:
//Settings clicked
editorFragmentData.putString("currentFragment", "SETTINGS_FRAGMENT");
editorFragmentData.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, new Settings())
.commit();
break;
case 4:
//Log Out clicked
SharedPreferences loginDataPreferences = getSharedPreferences("loginData", 0);
SharedPreferences.Editor editorLogin = loginDataPreferences.edit();
editorLogin.putBoolean("loggedIn", false);
editorLogin.commit();
Intent intent = new Intent(getApplicationContext(), Login.class);
startActivity(intent);
break;
default:
editorFragmentData.putString("currentFragment", "TIMELINE_FRAGMENT");
editorFragmentData.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, new PlaceholderFragment())
.commit();
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if(!mNavigationDrawerFragment.isDrawerOpen()) {
menu.clear();
getMenuInflater().inflate(R.menu.timeline, menu);
//restoreActionBar();
searchView = new SearchView(getActionBar().getThemedContext());
searchView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
searchView.setQueryHint(Html.fromHtml("<font color=#FFFFFF>Search ... </font>"));
searchView.setOnQueryTextListener(this);
searchView.clearFocus();
menu.add("Search").setIcon(R.drawable.ic_action_action_search).setActionView(searchView).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return false;
}
//User searched for a formula and pressed Enter
#Override
public boolean onQueryTextSubmit(String s) {
SharedPreferences preferencesFragmentData = getSharedPreferences("fragmentData", 0);
String currentFragment = preferencesFragmentData.getString("currentFragment", "");
if(currentFragment == "TIMELINE_FRAGMENT"){
//Log.e("TIMELINE", currentFragment + "IN THE IF FRAGMENT");
//Toast.makeText(getContext(), "You searched for: " + s + " in Timeline Fragment!", Toast.LENGTH_SHORT).show();
} else if (currentFragment == "FAVORITES_FRAGMENT"){
//Log.e("TIMELINE", currentFragment + "IN THE IF FRAGMENT");
//Toast.makeText(getContext(), "You searched for: " + s + " in FAVORITES Fragment!", Toast.LENGTH_SHORT).show();
}
//Hide the keyboard
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
invalidateOptionsMenu();
return true;
}
//user started typing, this code block is for Autocomplete or Suggestions based on his current input
#Override
public boolean onQueryTextChange(String s) {
return false;
}
}
This is the first Fragment that's being shown:
/**
* Created by lazarnikolov on 11/8/14.
*/
public class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static View rootView;
FavoritesDatabaseAdapter favoritesDB;
SwipeRefreshLayout swipeRefreshLayout = null;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public PlaceholderFragment() {
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_timeline, container, false);
} catch (InflateException e) {
}
favoritesDB = new FavoritesDatabaseAdapter(getActivity().getApplicationContext());
final ContentValues contentValues = new ContentValues();
final LinearLayout llScrollViewContainerItems = (LinearLayout) container.findViewById(R.id.llScrollViewContainerItems);
llScrollViewContainerItems.removeAllViews();
ActionBar actionBar = getActivity().getActionBar();
final Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "ubuntu.ttf");
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.PeterRiver)));
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("Timeline");
swipeRefreshLayout = (SwipeRefreshLayout) container.findViewById(R.id.container);
swipeRefreshLayout.setColorSchemeResources(R.color.Alizarin, R.color.Emerald, R.color.PeterRiver, R.color.Amethyst, R.color.WetAsphalt);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {...}
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = (Fragment) getFragmentManager()
.findFragmentByTag("TIMELINE_FRAGMENT");
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
}
Here's my activity_timeline.xml file, where the error occurs:
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".Timeline">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<android.support.v4.widget.SwipeRefreshLayout android:id="#+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/svContainerViews">
<LinearLayout android:id="#+id/llScrollViewContainerItems" android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
</LinearLayout>
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="lazarko.pocketformulas.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
And my Login Activity class:
/**
* Created by lazarnikolov on 11/8/14.
*/
public class Login extends Activity{
EditText etEmail, etPassword;
Button bLogin, bRegister;
Typeface font;
TextView tvLogIn;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preferences = getSharedPreferences("loginData", 0);
boolean loggedIn = preferences.getBoolean("loggedIn", false);
if(loggedIn) {
Intent intent = new Intent("android.intent.action.TIMELINE");
startActivity(intent);
}
SharedPreferences initialFragmentData = getSharedPreferences("fragmentData", 0);
SharedPreferences.Editor initialEditorFragmentData = initialFragmentData.edit();
initialEditorFragmentData.putString("currentFragment", "TIMELINE_FRAGMENT");
initialEditorFragmentData.commit();
setContentView(R.layout.login);
font = Typeface.createFromAsset(getAssets(), "ubuntu.ttf");
etEmail = (EditText) findViewById(R.id.etEmail);
etEmail.setTypeface(font);
etPassword = (EditText) findViewById(R.id.etPassword);
etPassword.setTypeface(font);
tvLogIn = (TextView) findViewById(R.id.tvRegister);
tvLogIn.setTypeface(font);
bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setTypeface(font);
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preferences = getSharedPreferences("loginData", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("loggedIn", true);
editor.commit();
communicate();
Intent intent = new Intent("android.intent.action.TIMELINE");
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setTypeface(font);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent("android.intent.action.REGISTER");
startActivity(intent);
}
});
}
// SERVER COMMUNICATION CLASS INITIALIZATION
private void communicate() {
new GetData().execute();
}
// SERVER COMMUNICATION CLASS
private class GetData extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
Looper.prepare();
String data = "";
InputStream inputStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("*******");
String json = "";
JSONObject object = new JSONObject();
object.accumulate("email", etEmail.getText().toString());
object.accumulate("password", etPassword.getText().toString());
json = object.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
inputStream = response.getEntity().getContent();
if(inputStream != null){
Toast.makeText(getApplicationContext(), "Logged in!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Invalid username/password", Toast.LENGTH_SHORT).show();
}
} catch(Exception e) {
Log.e("log_tag", "Error in http connection: " + e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
#Override onStart(), onRestart(), onResume()...
}
I've been searching for way too long and I still couldn't find a solution. Please take a look and post me what you think it's the problem!
Thanks a lot!
Look closer/debug lazarko.pocketformulas.NavigationDrawerFragment.java line 209 (it belongs to selectItem() method)
According to your stack trace you may have a null or not properly initialized object thereUpdate
To get to the reason of why it sometime happens and sometime not (if I correctly understand) there are more questions to ask.
1) Does it happen when you start your activity after a while? If so it may be linked to the fact that system has freed resources and your activity is recreated
2) If not - you have to move step by step to find reason. Track down where the object get nulled. It may be:
-- on re-creation of parent object (when you don't initialize it properly)
-- inside its class (just ctrl+f all occurrences)
-- outside its class. To track this make object private and declare setter method
Okay I've fixed the bug. I've been using the wrong Flag for the intent. This is the fix:
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
I inserted this where I'm starting the Timeline activity, and on the Log Out button too. Now I don't get that NullPointerException error on setContentView.

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