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.
Related
I have asked multiple questions on SO regarding different problems I am having with onNewIntent method in both fragments and activities. My problem now is that onNewIntent in Activity is never being called no matter what I do. The Activity that has the onNewIntent contains multiple tabs. My tabs (Fragments) contain codes for writing and reading NFC tag.
This is the code for the Activity:
public class MyAppHome extends AppCompatActivity {
protected DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;
NfcAdapter nfcAdapter;
private Toolbar mtoolbar;
private TextView mName;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_layout);
mtoolbar = (Toolbar) findViewById(R.id.nav_action);
setSupportActionBar(mtoolbar);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNavigationView= (NavigationView)findViewById(R.id.nav_view);
mDrawerLayout = findViewById(R.id.drawer_layout);
mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mtoggle);
mtoggle.syncState();
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition())
{
case 0:
mViewPager.setCurrentItem(0);
mtoolbar.setTitle("Home");
break;
case 1:
mViewPager.setCurrentItem(1);
mtoolbar.setTitle("Writer");
break;
case 2:
mViewPager.setCurrentItem(2);
mtoolbar.setTitle("Reader");
break;
case 3:
mViewPager.setCurrentItem(3);
mtoolbar.setTitle("Others");
break;
case 4:
mViewPager.setCurrentItem(4);
mtoolbar.setTitle("Alarm");
break;
default:
mViewPager.setCurrentItem(tab.getPosition());
mtoolbar.setTitle("My APP");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
switch (menuItem.getItemId()){
case R.id.nav_home:
mViewPager.setCurrentItem(0);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Home");
break;
case R.id.nav_writer:
mViewPager.setCurrentItem(1);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Writer");
break;
case R.id.nav_medication:
mViewPager.setCurrentItem(2);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Reader");
break;
case R.id.nav_missedPill:
mViewPager.setCurrentItem(3);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Others");
break;
case R.id.nav_alarm:
mViewPager.setCurrentItem(4);
mDrawerLayout.closeDrawers();
mtoolbar.setTitle("Alarm");
break;
case R.id.nav_logout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(getApplicationContext(),Login.class));
}
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}
}
);
initNFC(getIntent());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_dosis_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mtoggle.onOptionsItemSelected(item)){
return true;
}
//noinspection SimplifiableIfStatement
if (item.getItemId()== R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this.getApplicationContext(), this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(nfcAdapter !=null){
Log.d("W", "nfcadapter is not null");
nfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);
}
}
#Override
public void onPause() {
super.onPause();
if(nfcAdapter !=null){
disableForegroundDispatchSystem();
}
}
public boolean write2NFC(MyNfcMessage m ) {
NdefMessage ndefMessage = createNdefMessage(m.key1, m.key2,m.key3);
writeNdefMessage(tag, ndefMessage);
return true;
}
private void initNFC(Intent intent) {
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
// if (nfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
//Toast.makeText(getActivity(), "NfcIntent!", Toast.LENGTH_SHORT).show();
tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
protected void onNewIntent(Intent intent) {
System.out.print("I am here in Home");
Log.d("my tag", "I am here now");
initNFC(intent);
Log.d("my tag ", "onNewIntent: something ");
}
private void disableForegroundDispatchSystem() {
nfcAdapter.disableForegroundDispatch(this);
}
private void formatTag(Tag tag, Nde
fMessage ndefMessage) {
try {
NdefFormatable ndefFormatable = NdefFormatable.get(tag);
if (ndefFormatable == null) {
Toast.makeText(this, "Tag is not ndef formatable!", Toast.LENGTH_SHORT).show();
}
else{
ndefFormatable.connect();
ndefFormatable.format(ndefMessage);
ndefFormatable.close();
Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("formatTag", e.getMessage());
}
}
private void writeNdefMessage(Tag tag, NdefMessage ndefMessage) {
try {
if (tag == null) {
Toast.makeText(this, "Tag object cannot be null", Toast.LENGTH_SHORT).show();
return;
}
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
// format tag with the ndef format and writes the message.
formatTag(tag, ndefMessage);
} else {
ndef.connect();
if (!ndef.isWritable()) {
Toast.makeText(this, "Tag is not writable!", Toast.LENGTH_SHORT).show();
ndef.close();
return;
}
ndef.writeNdefMessage(ndefMessage);
ndef.close();
Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("writeNdefMessage", e.getMessage());
}
}
private NdefRecord createTextRecord(String content) {
try {
byte[] language;
language = Locale.getDefault().getLanguage().getBytes("UTF-8");
final byte[] text = content.getBytes("UTF-8");
final int languageSize = la
nguage.length;
final int textLength = text.length;
final ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + languageSize + textLength);
payload.write((byte) (languageSize & 0x1F));
payload.write(language, 0, languageSize);
payload.write(text, 0, textLength);
return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
} catch (UnsupportedEncodingException e) {
Log.e("createTextRecord", e.getMessage());
}
return null;
}
private NdefMessage createNdefMessage(String content, String content2, String content3) {
NdefRecord ndefRecord = createTextRecord(content);
NdefRecord ndefRecord2 = createTextRecord(content2);
NdefRecord ndefRecord3 = createTextRecord(content3);
NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{ndefRecord, ndefRecord2, ndefRecord3});
return ndefMessage;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragments.add(new Home());
mFragments.add(new Writer());
mFragments.add(new Reader());
mFragments.add(new Others());
mFragments.add(new Alarm());
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
/*to set text instead of icons*/
public CharSequence getPageTitle(int position){
return null;
}
}
}
My AndroidManifest looks something like this:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-feature
android:name="android.hardware.fingerprint"
android:required="false" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:launchMode="singleTop"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".WelcomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FingerPrint"
android:screenOrientation="portrait" />
<activity
android:name=".MyAppHome"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<data android:mimeType="text/plain" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/nfc_tech_filter" />
</activity>
<activity
android:name=".Login"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
</application>
Home Fragment (tab) is used to write information to NFC tag:
public class Home extends Fragment {
NfcAdapter nfcAdapter;
Button writebtn;
Tag tag;
EditText txtName, txtCountry, txtID;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.home, container,false);
txtName = (EditText)view.findViewById(R.id.pName);
txtCountry= (EditText)view.findViewById(R.id.pCountry);
txtID= (EditText)view.findViewById(R.id.pID);
writebtn=(Button)view.findViewById(R.id.nfcWriteBtn);
writebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyAppHome homeActivity = (MyAppHome)getActivity();
MyNfcMessage message = new MyNfcMessage(txtName.getText().toString(), txtCountry.getText().toString(), txtID.getText().toString());
homeActivity.write2NFC(message);
}
});
return v;
}
I don't Understand Why onNewIntent in the Activity is never being called (No Toasts are being displayed on screen). Does it have something to do with my layout?
Update: The problem was solved by creating a new project and copying all the code from the old project to the new one.
Check this:
http://www.helloandroid.com/tutorials/communicating-between-running-activities
In manifest.xml, in an activity tag set launchmode="singleTask"
I am switching between 2 different fragments using 2 buttons. One fragment has a camera view and opens pretty well for the first time, but when returning to the same fragment again from second fragment gives a blank screen. camera preview cannot be seen although camera hardware is free.I am NOT using camera2 api but needs a solution to this bug. i have added my complete code and images for assistance.
MAnifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.root.meeransunday" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="portrait"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<supports-screens android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"
android:anyDensity="true"
android:resizeable="true"/>
</application>
<activity android:name="meeranSunday"
android:configChanges="orientation|keyboardHidden"
/>
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.CAMERA">
</uses-permission>
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera" />
</manifest>
Fragment java class
public class scan extends Fragment implements ZXingScannerView.ResultHandler {
private ZXingScannerView zXingScannerView;
private SurfaceView mySurfaceView;
private Camera mCamera;
private CameraPreview mPreview;
private String m_Text = "";
private String number = "";
private OnFragmentInteractionListener mListener;
public scan() {}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.e("handler", rawResult.getText()); // Prints scan results
Log.e("handler", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode)
// show the scanner result into dialog box.
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Scan Result");
builder.setMessage(rawResult.getText());
number = rawResult.getText().substring(rawResult.getText().length() - 13);
//
final EditText input = new EditText(this.getActivity());
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, m_Text + " Transferred To Your Account From MTM Account", null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
//
AlertDialog alert1 = builder.create();
alert1.show();
// If you would like to resume scanning, call this method below:
zXingScannerView.resumeCameraPreview(this);
}
// TODO: Rename and change types and number of parameters
public static scan newInstance() {
scan fragment = new scan();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scan, container, false);
if (checkCameraHardware(getActivity().getApplicationContext())) {
Toast.makeText(this.getActivity(), "camera hardware is free", Toast.LENGTH_SHORT).show();
zXingScannerView = new ZXingScannerView(this.getActivity().getApplicationContext());
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera(0);
} else {
Toast.makeText(this.getActivity(), "camera hardware is NOT free", Toast.LENGTH_SHORT).show();
}
FrameLayout preview = (FrameLayout) view.findViewById(R.id.camera_preview);
preview.addView(zXingScannerView);
return view;
}
#Override
public void onPause() {
super.onPause();
try {
mCamera = Camera.open();
} catch (RuntimeException e) {
Log.d("camera opening attempt:", e.getMessage());
} finally {
if (mCamera != null) {
Log.d("camera opening attempt:", "yups ");
mCamera.release();
zXingScannerView.stopCamera();
zXingScannerView.stopCameraPreview();
}
}
}
#Override
public void onResume() {
super.onResume();
zXingScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
zXingScannerView.startCamera(0); // Start camera on resume
}
public boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() +
" must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
Log.d("aa", "sdsdssdsddssssd");
try {
mCamera = Camera.open();
} catch (RuntimeException e) {
Log.d("camera opening attempt:", e.getMessage());
} finally {
if (mCamera != null) {
mCamera.release();
zXingScannerView.stopCamera();
zXingScannerView.stopCameraPreview();
}
}
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name\
void onFragmentInteraction(Uri uri);
}
}
MAinactivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public int check = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
message frags = new message();
fragmentTransaction.add(R.id.content_main, frags, "text");
fragmentTransaction.commit();
check += 1;
}
public void message(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
message sms = new message();
fragmentTransaction.replace(R.id.content_main, sms, "text");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public void scan(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
scan scan = new scan();
fragmentTransaction.replace(R.id.content_main, scan, "scan");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public void loadooncreate() {
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
message frags = new message();
fragmentTransaction.add(R.id.content_main, frags, "text");
fragmentTransaction.commit();
check += 1;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
Toolbar toolbar2 = (Toolbar) findViewById(R.id.toolbar1);
toolbar2.inflateMenu(R.menu.notify);
toolbar2.getMenu().findItem(R.id.notifications).setIcon(buildCounterDrawable(2, R.drawable.notification));
toolbar2.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem arg0) {
if (arg0.getItemId() == R.id.notifications) {
arg0.setIcon(buildCounterDrawable(0, R.drawable.notification));
((RelativeLayout) findViewById(R.id.content_main)).removeAllViews();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
BlankFragment frag = new BlankFragment();
fragmentTransaction.add(R.id.content_main, frag, "first");
fragmentTransaction.commit();
}
return false;
}
});
check = 1;
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//code to reset view
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.findFragmentByTag("first") != null) {
fragmentTransaction.remove(fragmentManager.findFragmentByTag("first"));
fragmentTransaction.commit();
loadooncreate();
} else {
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
// TextView textView = (TextView) view.findViewById(count);
// textView.setText("1");
}
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (check > 3) {
Toast.makeText(this.getApplicationContext(), "sdsdsdfdsfsd", Toast.LENGTH_SHORT).show();
MenuItem item = menu.getItem(R.id.notifications);
item.setIcon(buildCounterDrawable(2, R.drawable.notification));
}
//MenuItem item = (MenuItem)findViewById(R.id.notifications);
// item.setIcon(buildCounterDrawable(2, R.drawable.notification));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.Home) {
//close current fragment;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.findFragmentByTag("first") != null)
fragmentTransaction.remove(fragmentManager.findFragmentByTag("first"));
fragmentTransaction.commit();
loadooncreate();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
last stack error
W/MessageQueue: Handler (android.hardware.Camera$EventHandler) {428e2000} sending message to a Handler on a dead thread
java.lang.RuntimeException: Handler (android.hardware.Camera$EventHandler) {428e2000} sending message to a Handler on a dead thread
at android.os.MessageQueue.enqueueMessage(MessageQueue.java:294)
at android.os.Handler.sendMessageAtTime(Handler.java:473)
at android.os.Handler.sendMessageDelayed(Handler.java:446)
at android.os.Handler.sendMessage(Handler.java:383)
at android.hardware.Camera.postEventFromNative(Camera.java:852)
at dalvik.system.NativeStart.run(Native Method)
Can you try this, remove onAttach and onDetach. Also replace this code in onCreate
if (checkCameraHardware(getActivity().getApplicationContext())) {
Toast.makeText(this.getActivity(), "camera hardware is free", Toast.LENGTH_SHORT).show();
zXingScannerView = new ZXingScannerView(this.getActivity().getApplicationContext());
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera(0);
} else {
Toast.makeText(this.getActivity(), "camera hardware is NOT free", Toast.LENGTH_SHORT).show();
}
with this.
zXingScannerView = new ZXingScannerView(this.getActivity().getApplicationContext());
And change onPause and onResume like this.
#Override
public void onPause()
super.onPause(); {
if (zXingScannerView != null) {
zXingScannerView.stopCamera();
zXingScannerView.stopCameraPreview();
}
}
#Override
public void onResume() {
super.onResume();
if (checkCameraHardware(getActivity().getApplicationContext())) {
Toast.makeText(this.getActivity(), "camera hardware is free", Toast.LENGTH_SHORT).show();
zXingScannerView.setResultHandler(this); // Register ourselves as a
zXingScannerView.startCamera(0); // Start camera on resume
}
}
Also remove all these objects
private SurfaceView mySurfaceView;
private Camera mCamera;
private CameraPreview mPreview;
No need for them ,it's there in your zXingScannerView.
Actually you are not release objects when switch to other fragment first release all object in onPause() method and onResume() reconnect with camera. try this one :
#Override
public void onResume() {
super.onResume();
if (zXingScannerView!= null) {
zXingScannerView.stopCameraPreview();
zXingScannerView.resumeCameraPreview(this);
}
}
I have some slides with ViewPager that shows application help and I want to show it in DrawerLayout too.
this is HelpActivity.class:
public class HelpActivity extends Activity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.fragment_help);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_1,
R.layout.welcome_2,
R.layout.welcome_3,
R.layout.welcome_4,
R.layout.welcome_5,
R.layout.welcome_6,
R.layout.welcome_7};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(HelpActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(/*getString(R.string.start)*/ "Start");
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(/*getString(R.string.next)*/ "Next");
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
this is PrefManager.class:
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "stand up-welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
and I use this code for defining it to drawerLayout:
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
with clicking on help in drawer, nothing shows. what should I do?
This is MainActivity.class:
ublic class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
public NavigationView navigationView;
public ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new HomeFragment());
tx.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle= setupDrawerToggle();
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//navigation view
navigationView= (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(navigationView);
actionBarDrawerToggle.syncState();
// default item of navigation view
// navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(R.id.nav_item_home);
}//onCreate
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()==R.id.nav_item_setting){
startActivityForResult(new Intent(this, SettingActivity.class), 1002);
}
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
} return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState); // `onPostCreate` called when activity start-up is complete after `onStart()`
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
}
in your xml:
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#drawable/background_drawer"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/colorPrimary"
app:menu="#menu/menu_navigation" />
you have to add help options in your menu_navigation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_item_help"
android:icon="#drawable/profile_icon"
android:title="Help" />
</group>
</menu>
Also in your MainActivity:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_setting:
Intent i = new Intent(MainActivity.this, SettingActivity.class);
startActivity(i);
break;
case R.id.nav_item_help:
Intent i = new Intent(MainActivity.this, HelpActivity.class);
startActivity(i);
break;
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
In your preference manager:
public void setFirstTimeLaunch(boolean isFirstTime) {
Editor editor = pref.edit();
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
difference between startactivity and startActivityForResult is:
1. startActvity():
startActivity() will start the activity you want to start without worrying about getting any result from new child activity started by startActivity to parent activity.
2. startAcitvityForResult():
startAcitvityForResult() starts another activity from your activity and it expect to get some data from newly started child activity by startAcitvityForResult() and return that to parent activity.
see this blog:https://malikshafique.wordpress.com/2012/06/14/android-startactivity-and-startactivityforresult/
I am developing an app and want users to be able to use their phones horizontally or vertically, however, if I start in portrait and switch to landscape, the app crashes. It also crashes if I start landscape and switch to portrait.
Here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="sensor">
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="screenSize|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="net.sourceforge.zbar.android.CameraTest.CameraTestActivity" />
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
</application>
I have already tried this this, but then the app cannot go to landscape as described here.
Here is the activity that it crashed in (MainActivity):
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, UserDelegate {
private static final int SCAN_COUPONS = 1;
public GoogleApiClient googleApiClient;
private Location lastLocation;
EditText zip;
public static User user;
public SharedPreferences sharedPreferences;
public static SQLiteDatabase database;
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_bar_container);
/*
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.actionbar);
}
*/
sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
database = openOrCreateDatabase("CouponWallet", MODE_PRIVATE, null);
/*Typeface iconFont = FontManager.getTypeface(getApplicationContext(), FontManager.FONTAWESOME);
FontManager.markAsIconContainer(findViewById(R.id.content_main), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.drawer_layout), iconFont);
//FontManager.markAsIconContainer(findViewById(R.id.nav_drawer), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.top_toolbar), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.bottom_toolbar), iconFont);*/
FontIconTypefaceHolder.init(getAssets(), "fonts/FontAwesome.ttf"); //allows for icons
// set up toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.top_toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Coupon Wallet");
toolbar.hideOverflowMenu();
FontManager.setFont(findViewById(R.id.top_toolbar), FontManager.getTypeface(this, FontManager.CANDY));
googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
Log.v("onCreate", "api client created");
//set up drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
new Thread(new Runnable() {
#Override
public void run() { // does ouside of ui thread
setIcons();
}
}).start();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
/*if(sharedPreferences.getInt("user_id", 0) == 0){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new LoginFragment());
ft.addToBackStack(null);
ft.commit();
getSupportActionBar().setTitle("Login");
}*/
//user = new User(sharedPreferences.getInt("user_id", 1), database);
//if (Functions.isOnline()) {
Log.v("onCreate", "creating user " + sharedPreferences.getInt("user_id", 1));
this.user = new User(1, this);
//}
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
LayerDrawable layerDrawable = (LayerDrawable) menu.findItem(R.id.action_barcode).getIcon();
layerDrawable.setDrawableByLayerId(R.id.main_icon, Functions.getFAIcons(this).get("barcode"));
Functions.setBadgeCount(this, layerDrawable, 2, R.id.num_circle);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_barcode) {
final AlertDialog dialog = new AlertDialog.Builder(this).setView(R.layout.redeem_code_layout).create();
dialog.show();
Toolbar toolbar = (Toolbar) dialog.findViewById(R.id.redeem_toolbar);
toolbar.inflateMenu(R.menu.redeem_menu);
toolbar.setTitle("Redeem Codes");
toolbar.setNavigationIcon(Functions.getFAIcons(this).get("times"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
toolbar.inflateMenu(R.menu.redeem_menu);
toolbar.hideOverflowMenu();
toolbar.setTitleTextColor(getResources().getColor(R.color.colorBlack));
FontManager.setFont(toolbar, FontManager.getTypeface(this, FontManager.CHAMPAGNE));
MenuItem help = toolbar.getMenu().add("Help");
help.setIcon(Functions.getFAIcons(this).get("question"));
help.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Toast.makeText(getApplicationContext(), "Help Clicked", Toast.LENGTH_LONG).show();
return false;
}
});
final ImageView code = (ImageView) dialog.findViewById(R.id.redeem_code);
code.setImageDrawable(user.barcode);
Spinner spinner = (Spinner) dialog.findViewById(R.id.redeem_scan_type);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item, new String[]{"Barcode", "QR Code", "PDF417", "Aztec"});
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
code.setImageDrawable(user.barcode);
break;
case 1:
code.setImageDrawable(user.qr_code);
break;
case 2:
code.setImageDrawable(user.pdf417);
break;
case 3:
code.setImageDrawable(user.aztec);
break;
}
/*for(int j = 0; j < 4; j++){
if (i != j) {
TextView item = ((TextView) adapterView.getChildAt(j));
item.setBackgroundColor(getResources().getColor(R.color.colorWhite));
item.setTextColor(getResources().getColor(R.color.colorGray));
} else {
TextView item = ((TextView) adapterView.getChildAt(j));
item.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
item.setTextColor(getResources().getColor(R.color.colorWhite));
}
}*/
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
code.setImageDrawable(user.barcode);
}
});
TextView textView = (TextView) dialog.findViewById(R.id.redeem_num);
long uid = user.id;
textView.setText(String.format(Locale.US, "%s%011d", "891", uid));
}
return super.onOptionsItemSelected(item);
}
/**
* #param item item selected in nav menu
* #return if view switch was successful
*/
//#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
String title = "";
Toolbar toolbar = (Toolbar) findViewById(R.id.bottom_toolbar);
toolbar.getMenu().clear();
switch (id) { //based on which section was selected
case R.id.nav_search:
title = "Search";
fragment = new SearchFragment();
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("gear"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.my_wallet);
MenuItem map1 = toolbar.getMenu().getItem(0); //only item in the menu
map1.setIcon(Functions.getFAIcons(getApplicationContext()).get("map"));
map1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.v("bottom_toolbar", "map clicked");
return true;
}
});
break;
case R.id.nav_profile:
title = "Profile";
break;
case R.id.nav_notifications:
title = "Notifications";
break;
case R.id.nav_categories:
try {
lastLocation = getLastKnownLocation();
if (lastLocation != null) {
Log.v("categories", "Location accessed");
Bundle bundle2 = new Bundle();
bundle2.putDouble("lat", lastLocation.getLatitude());
bundle2.putDouble("lon", lastLocation.getLongitude());
bundle2.putString("type", "loc");
fragment = new CategoriesFragment();
fragment.setArguments(bundle2);
title = "Categories";
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("gear"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.categories);
break;
}
} catch (SecurityException e) { // if can't get location go straight to search
}
Log.v("categories", "Location not accessable");
Toast.makeText(this, "Turn on location services get faster results", Toast.LENGTH_LONG).show();
AlertDialog dialog2 = new AlertDialog.Builder(this).setView(R.layout.get_zip_dialog).setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).create();
dialog2.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
dialogInterface.dismiss();
Toast.makeText(getApplicationContext(), "Cannot get local categories without location", Toast.LENGTH_LONG).show();
}
});
zip = (EditText) findViewById(R.id.zip_code);
dialog2.show();
break;
case R.id.nav_wallet:
fragment = new MyWalletFragment(); //sets up view
// setting up toolbars
title = "My Wallet";
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("columns"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.my_wallet);
MenuItem map = toolbar.getMenu().getItem(0); //only item in the menu
map.setIcon(Functions.getFAIcons(getApplicationContext()).get("map"));
map.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.v("bottom_toolbar", "map clicked");
return true;
}
});
//toolbar.setLogo(R.id.horizontal);
break;
case R.id.nav_scan:
title = "Scan Coupons";
Intent intent = new Intent(this, CameraTestActivity.class);
startActivityForResult(intent, SCAN_COUPONS);
break;
case R.id.nav_map:
title = "Map";
break;
case R.id.nav_settings:
fragment = new SettingFragment(); //sets up view
title = "Settings";
break;
case R.id.nav_help:
title = "Help";
// Assuming the Help in the nav bar is the same as the settings menu
fragment = new HelpSettingsFragment();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
FontManager.setFont(findViewById(R.id.content_frame), FontManager.getTypeface(this, FontManager.CHAMPAGNE));
//noinspection ConstantConditions
getSupportActionBar().setTitle(title);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onLocationChanged(Location location) {
Log.v("onLocationChanged", "Location changed");
lastLocation = location;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.v("onConnected", "connected");
try {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
/**
* Process a coupon scan
*
* #param requestCode Type of activity
* #param resultCode if result ok
* #param data the returned data
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) {
Log.e("onActivityResult", "result canceled");
} else if (resultCode == RESULT_OK) {
if (requestCode == SCAN_COUPONS) {
String result = data.getStringExtra("result");
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
Log.v("onActivityResult", result);
}
}
}
/**
* Set the icons in the drawer
*/
private void setIcons() {
Map<String, Drawable> map = Functions.getFAIcons(getApplicationContext());
int[] sections = {R.id.nav_search, R.id.nav_profile, R.id.nav_notifications, R.id.nav_categories, R.id.nav_wallet,
R.id.nav_scan, R.id.nav_map, R.id.nav_settings, R.id.nav_help};
Drawable[] icons = {map.get("search"), map.get("user"), map.get("bookmark"), map.get("list"), map.get("barcode"),
map.get("camera"), map.get("map_o"), map.get("gear"), map.get("question")};
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu m = navigationView.getMenu();
for (int i = 0; i < sections.length; i++) {
MenuItem item = m.findItem(sections[i]);
item.setIcon(icons[i]);
}
}
/**
* Gets the last known Location
*
* #return The last known location
* #throws SecurityException if proper permissions not given
*/
private Location getLastKnownLocation() throws SecurityException {
LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
Log.v("getLastKnownLocation", "looping through providers");
for (String provider : providers) {
Log.v("getLastKnownLocation", provider);
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
public void settingOnClick(View v) {
/*
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_shortcut)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mBuilder.setAutoCancel(true);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
*/
Fragment fragment = null;
switch (v.getId()) {
case R.id.setting_account:
case R.id.setting_userIcon:
fragment = new AccountSettingsFragment();
break;
case R.id.setting_location:
case R.id.setting_locationArrow:
fragment = new LocationSettingsFragment();
break;
case R.id.setting_notifications:
case R.id.setting_notificationIcon:
fragment = new NotificationSettingsFragment();
break;
case R.id.setting_help:
case R.id.setting_helpIcon:
fragment = new HelpSettingsFragment();
break;
case R.id.setting_contact:
case R.id.setting_contactIcon:
fragment = new ContactUsSettingsFragment();
break;
case R.id.setting_privacy:
case R.id.setting_privacyIcon:
fragment = new PrivacyPolicySettingsFragment();
break;
case R.id.setting_about:
case R.id.setting_aboutIcon:
fragment = new AboutSettingsFragment();
break;
case R.id.tutorial_loc_enterAnotherLocation:
fragment = new EnterAnotherLocation();
break;
case R.id.tutorial_1_saving:
case R.id.tutorial_2_saving:
case R.id.tutorial_3_saving:
fragment = new FirstTimeLocation();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
}
#Override
public void userFinished(User user) {
this.user = user;
Log.v("UserFinished", user.toString());
}
}
And the error that i get is here. It is a link to a .txt file as it brings the question over the character limit.
Hii for working in landscape and portrait mode, you have to use saved instance and restore saved instance or else your application values
googleApiClient,lastLocation,zip,user values may have null value and causes this issue
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
savedInstanceState.putParcelable("parcelable", "");
savedInstanceState.putSerializable("serializable", "");
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate() and also onRestoreInstanceState() where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
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;