Google glass closing second level activity closes app - android

I have two activities, Main Activity and List Activity. I always want a menu displayed on Main Activity as there's no where else to go.
Main Activity has this code:
#Override
public void onOptionsMenuClosed(Menu menu) {
// Nothing else to do, closing the activity.
finish();
}
#Override
public void onResume() {
super.onResume();
openOptionsMenu();
}
When I close List Activity, my entire app closes - and its due to the onOptionsMenuClosed method in my MainActivity, really confused as to why this is the case, when ListActivity is closed I just want to go back to the menu.

I had the same problem and solved it like this:
public class StartActivity extends Activity{
private boolean cancel = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
openOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.startmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Item1){
cancel = false;
Intent intent = new Intent(this, ActivityA.class);
startActivityForResult(intent, 0);
return true;
}
else if(id == R.id.Item2){
cancel = false;
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_CANCELED) {
openOptionsMenu();
cancel = true;
}
}
}
#Override
public void onOptionsMenuClosed(Menu menu)
{
super.onOptionsMenuClosed(menu);
if(cancel){
finish();
}
}
}

Related

up button from preference fragment to return to preference headers

My app has preference headers on which you choose what fragment to start. After you are in some fragment I want that click on back button shows header again and if I press back again when headers are shown to return me to some other activity.
I overridded onOptionsItemSelected in Activity and in Fragment but it always calls action from activity because I am trying to bind fragment and activity to same action. Here is my code:
public class SettingsActivity extends AppCompatPreferenceActivity {
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preference_headers, target);
}
#Override
protected boolean isValidFragment(String fragmentName) {
return SettingsFragment.class.getName().equals(fragmentName);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.app_preferences);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
I managed to solve this by removing onOptionsItemSelected method from activity and leave inside fragment. Now when I press up inside fragment it goes to SettingsActivity and when up is pressed inside activity it acts like onBackPressed(). Hope this helps somebody.

Freeze or make Stable Web-view When I Select Action Bar Back?Prevent Loading/reloading every time

I want to Prevent Page reload or Freeze the Current Web-view When I Select any menu from option menu
This is My Webview
public class MyWebV extends AppCompatActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mwview);
Toolbar toolbar = (Toolbar) findViewById(R.id.tb1);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.web5);
WebSettings set = webView.getSettings();
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
set.setJavaScriptEnabled(true);
set.setJavaScriptCanOpenWindowsAutomatically(true);
set.setLoadWithOverviewMode(true);
set.setUseWideViewPort(true);
set.setDomStorageEnabled(true);
set.setAllowUniversalAccessFromFileURLs(true);
set.setJavaScriptCanOpenWindowsAutomatically(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
final ProgressDialog progressBar = ProgressDialog.show(MyWebV.this, "Please Wait", "Loading...");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient()
{
public void onLoadResource (WebView view, String url) {
if (progressBar == null) {
progressBar.setTitle("Please Wait !");
progressBar.setMessage("Loading...");
progressBar.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.setWebChromeClient(new WebChromeClient() {
String url = "www.example.com/login.php";
webView.loadUrl(url);
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
webView.restoreState(savedInstanceState);
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m_MyWebV, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.about1) {
Intent aboutIntent = new Intent(this, About.class);
startActivity(aboutIntent);
return true;
}
else if (id == R.id.set1) {
Intent webIntent = new Intent(this, Settings.class);
startActivity(webIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
I My Web-view I have Some Menus So When I click on any menu like Setting or About... It is showing But After that When I go back to Home with Option or Back arrow from Action Bar or Option Menu Its Reloading
So I need to login and And check the previous page its difficult for every time.. Can any one suggest me how to freeze web-view or How to prevent reload with the same app menus...
Update
This is my about Us class
public class About extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutus);
Toolbar toolbar = (Toolbar) findViewById(R.id.tb3);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m_about, menu);
/*something*/
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
Intent mypIntent = new Intent(this, MyWebV.class);
About.this.finish();
startActivity(mypIntent);
return true;
}
else if (id == R.id.about1) {
Intent aboutIntent = new Intent(this, About.class);
About.this.finish();
startActivity(aboutIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
so for example if this is action bar back
so When I click on arrow Its reloading the webview.. On device Hardware back I have disabled... on hardware back its fine but... On action bar back its Reloading
I have just performed a test using two activities, a MainActivity containing a webView just like yours, and a menu button that opens a second activity (About.java), using the exact same intent that you used in onOptionsItemSelected().
After opening About activity from the menu, if I press my phone's hardware back button, it returns to MainActivity without reloading the contents of the WebView, so it works as you expect.
I think the problem you are experiencing is with the code you use to go back to the main activity. You may be using an Intent to open your main activity again from your secondary activities, causing a new instance of your main activity to be created, triggering onCreate(), and thus re-creating your WebView and reloading the page.
To test if that's the case, you can add some debugging statements inside onCreate() using Log.d() or System.out.println(), to check if it's being called when you try to return to your main activity (MyWebV). If you see your debug messages in the logs, it's because you are not returning to your Main Activity properly.
The way you should close your secondary activities to return to your main activity is calling:
finish()
That method will close current activity and restore the previous activity in the stack (your MyWebV activity in this case), without re-creating it, just calling onStart() and onResume(), which wouldn't re-create your WebView or reload the page.
About us or Setting page code where you used your custom back event or hardware back event.I think you are creating activity again inside your back event which is doesn't require you just need to call finish method your Settings or About us page finish there and Webview page remain same as it is.Thats why i am requesting you post your code of one of page at least i can understand what you did exactly.
public class About extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutus);
Toolbar toolbar = (Toolbar) findViewById(R.id.tb3);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m_about, menu);
/*something*/
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
finish();
return true;
}
else if (id == R.id.about1) {
Intent aboutIntent = new Intent(this, About.class);
About.this.finish();
startActivity(aboutIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
#Override public boolean onOptionsItemSelected(MenuItem item)
{ int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}

How to go back to the previous fragment properly?

I'm trying to handle the back button in a fragment. I want it to go back to the fragment it came from, but the #Override I've doesn't override from its superclass, but I don't why. Futhermore the method onBackPressed() is never used. I think it's weird as it works in my activities.
public class RateFrag extends Fragment implements View.OnClickListener {
private RatingBar ratingBar;
private Button rateknap;
private Forslag forslag;
#Override
public View onCreateView(LayoutInflater i, ViewGroup container, Bundle savedInstanceState) {
View rod = i.inflate(R.layout.activity_rate, container, false);
setHasOptionsMenu(true);
forslag = ((AnnonceDisplay) this.getActivity()).getForslag();
getActivity().setTitle(forslag.getTitle());
ratingBar = (RatingBar) rod.findViewById(R.id.ratingBar);
rateknap = (Button) rod.findViewById(R.id.rateknap);
rateknap.setOnClickListener(this);
return rod;
}
#Override
public void onClick(View v) {
if (v == rateknap) {
AlertDialog alert = new AlertDialog.Builder(getActivity())
.setMessage("Vil du give " + ratingBar.getRating() + " stjerner?")
.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
launchintent();
}
}
)
.setNegativeButton("Nej", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}
).show();
}
}
private void launchintent() {
FragmentManager fm = getFragmentManager();
Fragment f = fm.findFragmentById(R.id.fragment);
if(fm.getBackStackEntryCount() > 0){
fm.popBackStack();
} else{
getActivity().finish();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Forside) {
Intent intent = new Intent(this.getActivity(), Forside.class);
startActivity(intent);
}
else if (id == R.id.Logud){
Intent intent = new Intent(this.getActivity(), LogInd.class);
startActivity(intent);
}
return true;
}
#Override //Method does not override method from its superclass
public void onBackPressed() { //Method onBackPressed is never used
if (getFragmentManager().getBackStackEntryCount() == 0) {
getActivity().finish();
} else {
getFragmentManager().popBackStack();
}
return;
}
}
Before anyone says it's a possible duplicate, I've searched here on Stackoverflow and Google. I actually got this Override from here, so please tell me what is wrong, and how I fix it.
Thanks :)
Override the onBackPress on your Activity like this
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}

getIntent is not working inside MainActivity. Getting weird behaviour

I have one MainActivity and I have defined below code in onCreate() method. The intention is, when MainActivity gets extra String "EXIT" then show Toast message:
Intent current = getIntent();
if (current !=null && current.getStringExtra("EXIT") != null) {
Toast.makeText(this, "exiting", Toast.LENGTH_LONG).show();
}
This MainActivity starts another activity "DayOne" on some button press like:
public void processGo(View v){
Intent i = new Intent(MainActivity.this,DayOne.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
MainActivity.this.startActivity(i);
}
Now I am returning back from "DayOne" to MainActivity after putting extra string "EXIT". This I am doing inside onOptionsItemSelected(MenuItem item) method:
public boolean onOptionsItemSelected(MenuItem item){
if(item.getTitle().equals("Exit")){
Intent i = new Intent(DayOne.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("EXIT", "EXIT");
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
The issue is, when MainActivity is getting called from DayOne with extra string "EXIT"; I am not seeing the Toast message defined in MainActivity. What is missing or wrong here?
Appreciate any help.
Thanks all for your comments and helps.
I have figured out the issue here. It was because the manifest file had entry an entry android:launchMode="singleInstance" for Both the activities (MainActivity and DayOne Activity)..
Removing it from there, it worked fine.
First check your null then get the Intent String, can you just make your code look like below within in onCreate of MainActivity#
Bundle extra= getIntent().getExtras();
if(extra!=null){
String _StrExit=extra.getString("EXIT");
if(_StrExit.equalsIgnoreCase("EXIT")){
Toast.makeText(this, "exiting", Toast.LENGTH_LONG).show();
}
}
Update
Make change while calling Intent from menuitem
public boolean onOptionsItemSelected(MenuItem item){
if(item.getTitle().equals("Exit")){
Intent i = new Intent(DayOne.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
String _Str="EXIT";
i.putExtra("EXIT", _Str);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
Its working for me.
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent current = getIntent();
if (current != null && current.getStringExtra("EXIT") != null) {
Toast.makeText(this, "exiting", Toast.LENGTH_LONG).show();
}
}
public void processGo(View view) {
Intent i = new Intent(MainActivity.this, OneDayActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
OneDayActivity:
public class OneDayActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_one);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.day_one, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Exit")) {
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("EXIT", "EXIT");
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
dont clear the stack instead of if you want to do some task when you come back to your main activity (using "EXIT" string) you can achieve that using onActivityResult also.:
public void processGo(View v){
Intent i = new Intent(MainActivity.this,DayOne.class);
MainActivity.this.startActivity(i,10); // 10 is the id to handle
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data )
{
super.onActivityResult( requestCode, resultCode, data );
switch ( requestCode )
{
case ( 10 ): // id that we pass on start activity
{
if ( resultCode == Activity.RESULT_OK )
{
Toast.makeText(this, "exiting"+data.getStringExtra( "EXIT", "" ), Toast.LENGTH_LONG).show();
}
}
break;
}
}
On finish
public boolean onOptionsItemSelected(MenuItem item){
if(item.getTitle().equals("Exit")){
Intent resultIntent = new Intent();
resultIntent.putExtra( "EXIT", "EXIT" );
setResult( Activity.RESULT_OK, resultIntent );
finish();
}
return super.onOptionsItemSelected(item);
}
on finish it will go back to Main Activity and call onActivityResult automatically where you can do your task.
Sorry for the typo hope it will help.

Android Tabs with ListActivity BackButton

I have 3 Tabs
Tab1,Tab2,Tab3
public Class TabLayout extends TabActivity {
Tab1,Tab2,Tab3
}
Each Tab Contains one ListActivity
that means
Tab1>>>Tab1ListActivity(List with Image and Text)
Tab2>>>Tab2ListActivity(List with Image and Text)
Tab3>>>Tab3ListActivity(List with Image and Text)
and if i click on any listitem from(Tab1ListActivity,Tab2ListActivity etc.......)
I'm forwarding to one More Activity(Tab1ListItemActivity,Tab2ListItemActivity etc......)
But My Actual Requirement is if suppose I'm clicking backbutton from Tab2ListItemActivity ,then I
Should be able to forward to Tab2ListActivity
But,if i write my code like this
public class Tab2ListItemActivity extends Activity
{
//on Back Button Pressed
Intent intent=new Intent(Tab2ListItemActivity.this,TabLayout.class);
startActivity(intent);
Tab2ListItemActivity.this.finish();
}
when i execute above code I'm able to forward to my TabLayout(Tab1ListActivity) but not to Tab2ListActivity?,Beacuse
Tab2ListItemActivity related to Tab2ListActivity
Could any one help?
Why not leave the default behaviour (do not override onBackPressed)? It will restore to previous Activity.
Solution 1:
Do not finish the TabLayout Activity. And Leave the default implementation of back button in Tab2ListItemActivity activity.
Solution 2 (the hard, the force way):
Add the intent extra on what tab it should open.
Intent intent = new Intent(Tab2ListItemActivity.this, TabLayout.class);
intent.putExtra(TabLayout.EXTRA_TAB_TO_OPEN, 1);
startActivity(intent);
Tab2ListItemActivity.this.finish();
in TabLayout Activity
#Override
protected void onPostCreate(Bundle state) {
super.onPostCreate(state);
handleTab(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleTab(intent);
}
private void handleTab(Intent intent) {
// init tabs
final int tab = intent.getIntExtra(EXTRA_TAB_TO_OPEN, -1);
if (tab != -1) {
getTabHost().setCurrentTab(tab);
}
}
Why are you trying to override the Back button ? I mean, just let the default behaviour take place and then pressing the back button would take you to the previous activity.
If you really want to do it your way, then you would need to set the tab id before launching the TabLayout activity and inside the onCreate() of TabLayout you would need to check the tab id and launch the corresponding ListActivity. The tab id is 1 by default and that is why it is taking you to the Tab1ListActivity always.
I am getting same issue but i solve using this solution.
TabSample.class
public class TabSample extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1")
.setIndicator("OPT")
.setContent(new Intent(this, TabGroup1Activity.class)));
tabHost.addTab(tabHost.newTabSpec("tab2")
.setIndicator("EDIT")
.setContent(new Intent(this, TabGroup2Activity.class)));
tabHost.setCurrentTab(1);
}
}
TabGroup1Activity.class
public class TabGroup1Activity extends TabGroupActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,OptionsActivity.class));
}
}
OptionsActivity.class
public class OptionsActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.optionspage);
Button back = (Button) findViewById(R.id.BackButton1);
Button next = (Button) findViewById(R.id.NextButton1);
OnTouchListener backListener = new OnTouchListener() {
public boolean onTouch (View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_UP){
finish();
}
return false;
}
};
OnTouchListener nextListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_UP){
Intent edit = new Intent(getParent(), EditActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("EditActivity", edit);
return true;
}
return false;
}
};
back.setOnTouchListener(backListener);
next.setOnTouchListener(nextListener);
}
}
finally over TabGroupActivity.class which save all the stat instance.
public class TabGroupActivity extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null) mIdList = new ArrayList<String>();
}
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size()-1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index); index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
public void onBackPressed() {
int length = mIdList.size();
if ( length > 1) {
Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1));
current.finish();
}
}
}
This is awesome solution you can try this.and make appropriate manifest entry.

Categories

Resources