I am making an app that will has three activities. The user can navigate to a new activity pressing buttons (home, graph, and write). This part works fine, but I only want three activities to be created max. Right now if I push the buttons 10 times I get 10 separate activities. Is there a way to prevent this and have the button call an activity if it has already been created instead of creating a new one each time?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_toGraph = (Button) findViewById(R.id.home_to_graph);
button_toGraph.setOnClickListener(goToSecondListener);
Button button_toWrite = (Button) findViewById(R.id.home_to_write);
button_toWrite.setOnClickListener(goToThirdListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private OnClickListener goToSecondListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
doButton();
}};
private void doButton()
{
startActivity(new Intent(this, GraphScreen.class));
}
private OnClickListener goToThirdListener = new OnClickListener(){
#Override
public void onClick(View v) {
doBacktoThird();
}
private void doBacktoThird() {
startActivity(new Intent(MainActivity.this, WriteScreen.class));
}
};
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
Any help will be greatly appreciated! Thank you!
create three Boolean Variables.
if suppose button_toGraph is clicked .. make the
Boolean button_toGraph_IsCreated = true;
and when Activity is Finished ( YourActivity.finish ) make it Again false.
make a check on the button by using these variable like
if(button_toGraph_IsCreated) // if the variable is true
{
// do nothing as already activity created
}
else
{
doBacktoThird();
}
if you are using database then it should not be hard to get the values to main activity.
Related
FeedFragment.java
public class FeedFragment extends Fragment {
Button bt_scan;
private Object Button;
public FeedFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_feed, container, false);
bt_scan = (Button) v.findViewById(R.id.bt_scan);
bt_scan.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent MainIntent = new Intent(getActivity(), MainActivityQR.class);
startActivity(MainIntent);
/* if you want to finish the first activity then just call
finish(); */
}
});
return v;
}
}
I already tried but the camera for scanning QR Code wont come out
The use of the camera require a permission request and a declaration in the AndroidManifest file
I have a fragment with multiple toggle buttons. On click of a particular button in my Activity, I'd like to upload the status of all these toggle buttons to the server. I see there is one way of doing it as explained in the below link, where we create a listener interface and on every click of each toggle button, we update some tag/integer in the activity corresponding to each toggle button.
https://developer.android.com/training/basics/fragments/communicating.html
But I would like to know if there is any way to know the checked/unchecked status of all toggle buttons in the fragment from the activity without implementing the interface methods for each time a toggle button is clicked. Hope I'm clear.
Here's a working example of how to achieve that. The activity:
public class MainActivity extends AppCompatActivity {
ToggleFragment toggleFragment;
Button updateStatusButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
updateStatusButton = (Button) findViewById(R.id.updateStatusButton);
toggleFragment = ToggleFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_frame, toggleFragment, "ToggleFragment")
.commit();
updateStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean buttonsChecked = toggleFragment.areToggleButtonsChecked();
Toast.makeText(MainActivity.this, String.format("Toggle buttons checked: %s", buttonsChecked), Toast.LENGTH_LONG).show();
}
});
}
}
And the Fragment:
public class ToggleFragment extends Fragment {
ToggleButton toggleButton1;
ToggleButton toggleButton2;
ToggleButton toggleButton3;
public static ToggleFragment newInstance() {
Bundle args = new Bundle();
ToggleFragment fragment = new ToggleFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.toggle_fragment, container, false);
toggleButton1 = (ToggleButton) view.findViewById(R.id.toggleButton1);
toggleButton2 = (ToggleButton) view.findViewById(R.id.toggleButton2);
toggleButton3 = (ToggleButton) view.findViewById(R.id.toggleButton3);
return view;
}
public boolean areToggleButtonsChecked() {
return toggleButton1.isChecked()
&& toggleButton2.isChecked()
&& toggleButton3.isChecked();
}
}
Honestly, the best way that you could accomplish this is with a ViewModel from the Android Architecture Components library. The ViewModel can have an ObservableField or LiveData value that each of the Fragments can observe, and always have the correct information. This would also make it easier to be lifecycle-aware.
I recently made a simple app that allows users to register information, login, and logout. I want to increase the complexity of this app by adding a tabbed activity that the user sees when they login, and having the third tab contain a TextView that will log them out.
Here is what I did previously to log out in my Main Activity before adding tabs:
public class MainActivity extends AppCompatActivity{
private Button bLogout;
private Session session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Session(this);
if(!session.loggedin()){
logout();
}
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
logout();
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
}
Now, I want to transfer this same concept to my Tab3 Fragment Class, but I keep getting errors. Here is the Tab3 class without errors:
public class Tab3User extends Fragment{
private TextView tvLogout;
private Session session;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3User, container, false);
tvLogout = (TextView) rootView.findViewById(R.id.tvLogout);
return rootView;
}
}
The errors happen when I try to create a new session using this as Context, as well as in the 'startActivity' method in my logout function when I try to use 'Tab3User.this'. The onClickListener seems to be working, but I am very new to android dev so I'm sure I'm just making a mistake. Here is my attempt to add in everything:
public class Tab3User extends Fragment{
private TextView tvLogout;
private Session session;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3User, container, false);
tvLogout = (TextView) rootView.findViewById(R.id.tvLogout);
return rootView;
//error here under the "this"
session = new Session(this);
if(!session.loggedin()){
logout();
}
tvLogout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
logout();
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(Tab3User.this, LoginActivity.class));
}
}
Thanks for any and all help. I've been looking online but many answers to questions like this are very ambiguous so I decided to post.
Inside a fragment you need to use getContext() / getActivity().
session = new Session(getContext());
I have my main activity actionbaractivity One where you can screenslide through some fragmets, on each fragment you have an imageView and a ListView where you can click any item and the image will change. Also in the menu options you have a button where you change to an almost exact activity: actiobbaractivity Two which also have this button to change to activity One
What I'm able to do is to keep the image when sliding the fragments, but unable to keep the fragments state's through the change of activities.
For example
I'm in activity One on fragment 3 with the image: "something". I click on the button to change to activity Two, I do things here and then, I click on the button to change to activity One and I want to see my fragment 3 with the image: "something" and not the default fragment 1 and default image
Im using ActionBarActivity, FragmentStatePagerAdapter and Fragment for each activity
Thanks for the help
According to the Activity and Fragment lifecycles (http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle and http://developer.android.com/guide/components/fragments.html#Lifecycle), the most reliable way of persisting states between activity/fragment changes is to use the default API for saving and restoring states:
When the activity/fragment is being dismissed (either because of a configuration change such as screen rotation or because the user requested to go to another activity/fragment), you can save its state in a Bundle object. When it is being created, you can restore its saved state, thus recreating a new instance exactly like the one the user left - so the user feels nothing has changed. This does not depend on the specific subclass of activity/fragment you are using.
I have implemented something like what you want: in my case, a fragment containing a menu with buttons that would each lead the user to another fragment containing a submenu with a "back" button. So if the user went from menu to submenu 1, then back to menu, then to submenu 2, then back to menu and finally again to submenu 1, I wanted that submenu 1 to appear just like the user has left it in the first time.
For that I have created:
1) an interface defining my submenu types, implemented by my activities so they could change between my submenus
2) a master generic class, which all my submenus would extend, that had a Bundle object to store their state
3) in my activities, I had an array of Bundle capable of storing one instance of each of my submenus (because I am only interested in restoring the last state, so I don't need more than one)
The interface (item 1):
public interface SubmenusManager {
public static enum Submenus {
ROOTMENU,
SUBMENU1,
SUBMENU2;
private static final int size = Submenus.values().length;
public static int size() {
return size;
}
public static int getId(Submenus test) {
switch(test) {
case SUBMENU1:
return 1;
case SUBMENU2:
return 2;
case ROOTMENU:
default:
return 0;
}
}
}
public void cloneCurrentSubmenuState(Parcelable toOverwrite);
public Bundle getLastStoredSubmenuState(Submenus submenu);
public void setCurrentSubmenuTo(Submenus submenu);
}
The generic class (item 2):
public class MenuFragment extends Fragment {
private Bundle menuData = new Bundle();
public static String RESTORE_MAIN_OBJECT = "restore_main";
public Bundle getMenuData() {
return menuData;
}
public Bundle cloneMenuData() {
return new Bundle(menuData);
}
public void setMenuData(Bundle menuData) {
this.menuData = menuData;
}
}
One of the activities (item 3):
public class ExampleAct extends FragmentActivity implements SubmenusManager {
/**
* instance variables
*/
private MenuFragment mMenu;
private Bundle [] menuData; // the Array of Bundles!
private static final String CONTAINER = "parcelable_container";
private static final String SUBMENU = "saved_submenu";
private Submenus curSubmenu = Submenus.ROOTMENU; // the default state is the ROOTMENU
private boolean restoreLastSavedState = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) { // first time creating this activity
menuData = new Bundle[Submenus.size()];
} else { // this activity has a saved state from before
// restore all the data from all the submenus
menuData = (Bundle[]) savedInstanceState.getParcelableArray(CONTAINER);
// restore the info about which is the current active submenu
curSubmenu = (Submenus) savedInstanceState.getSerializable(SUBMENU);
}
buildMenuFragment(true);
//(...) stuff
}
private void buildMenuFragment(boolean restoreState) {
// (re)builds fragment inside menu.
// restoreState flags whether activity should look for
// saved state data and restore it
restoreLastSavedState = restoreState;
switch(curSubmenu) {
// Eclipse warns you about which are the constants in your enum
case ROOTMENU:
mMenu = new FragmentRootMenu();
break;
case SUBMENU1:
mMenu = new FragmentSubmenu1();
break;
case SUBMENU2:
mMenu = new FragmentSubmenu2();
break;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, mMenu)
.commit();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(SUBMENU, curSubmenu);
cloneCurrentSubmenuState(mMenu.getMenuData().
getParcelable(MenuFragment.RESTORE_MAIN_OBJECT));
outState.putParcelableArray(CONTAINER, menuData);
// (...) stuff
}
#Override
public void cloneCurrentSubmenuState(Parcelable toOverwrite) {
if (menuData == null) menuData = new Bundle[Submenus.size()];
if (toOverwrite != null)
mMenu.getMenuData().putParcelable(MenuFragment.RESTORE_MAIN_OBJECT, toOverwrite);
menuData[Submenus.getId(curSubmenu)] = mMenu.cloneMenuData();
}
#Override
public Bundle getLastStoredSubmenuState(Submenus forThisSubmenu) {
return
(menuData == null || !restoreLastSavedState) ? new Bundle() : menuData[Submenus.getId(forThisSubmenu)];
}
#Override
public void setCurrentSubmenuTo(Submenus toThisSubmenu) {
if (mMenu != null) {
cloneCurrentSubmenuState(mMenu.getMenuData().
getParcelable(MenuFragment.RESTORE_MAIN_OBJECT));
}
curSubmenu = toThisSubmenu;
buildMenuFragment(true);
}
One of the submenus (extension of item 2):
public class FragmentSubmenu1 extends MenuFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_submenu1, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
// (...) stuff
MyParcelableObject tmp = null; // MyParcelableObject is a class
// that implements Parcelable and stores
// relevant info to rebuild this menu
// from a saved state
SubmenusManager m = (SubmenusManager) getActivity(); // remember activity implements SubmenusManager
Bundle bnd = m.getLastStoredSubmenuState(SubmenusManager.Submenus.SUBMENU1);
if (bnd != null) tmp = bnd.getParcelable(MenuFragment.RESTORE_MAIN_OBJECT);
if (tmp == null) {
tmp = new MyParcelableObject();
tmp.buildFromScratch(); // initializes with default data
}
// back button
Button backToMainMenu = (Button) getView().findViewById(R.id.submenu1_back);
backToMainMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((SubmenusManager) getActivity()).
setCurrentSubmenuTo(SubmenusManager.Submenus.ROOTMENU);
}
});
// (...) stuff
}
}
The Root menu (extension of item 2):
public class FragmentRootMenu extends MenuFragment {
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_rootmenu, null);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
Button btnSubmenu1 = (Button) myView.findViewById(R.id.btn_call_submenu1);
btnSubmenu1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((SubmenusManager) getActivity()).
setCurrentSubmenuTo(SubmenusManager.Submenus.SUBMENU1);
}
});
Button btnSubmenu2 = (Button) myView.findViewById(R.id.btn_call_submenu2);
btnSubmenu2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((SubmenusManager) getActivity()).
setCurrentSubmenuTo(SubmenusManager.Submenus.SUBMENU2);
}
});
}
}
For that to work between activities, all you need to do is pass that object that stores the last state of all fragments (in my case, that would be Bundle [] menuData) to the activity that is being called through its Intent; you would recover it the same way as my ExampleAct did in its onCreate(). You could also wrap that Bundle [] inside a custom Parcelable object (very similar to my example MyParcelableObject; inside that one I had stuff like HashMap) if using an array is a problem.
Here how to pass a Parcelable between activities:
How to send an object from one Android Activity to another using Intents?
I have a menu and when clicked on a menu, it goes inside another menu.
for example, mainmenu-->click on airport guide --> menu2
but when i am in menu2 and press on the back button, the app is closing instead of going back to mainmenu . i am not able to figure out the problem here. i am new to android development
package com.shashank.sharjahinternationalairport;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class MainActivity extends Activity {
ImageButton flightInfoButton;
ImageButton airportGuideButton;
ImageButton visitorInfoButton;
ImageButton saaDcaButton;
ImageButton cargoButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flightInfoButton = (ImageButton) findViewById(R.id.flightInfo);
airportGuideButton = (ImageButton) findViewById(R.id.airportGuide);
visitorInfoButton = (ImageButton) findViewById(R.id.visitorInfo);
saaDcaButton = (ImageButton) findViewById(R.id.saaDca);
cargoButton = (ImageButton) findViewById(R.id.cargo);
airportGuideButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.airport_guide);
}
});
visitorInfoButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.visitor_info);
}
});
saaDcaButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.saa_dca);
}
});
}
#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);
return true;
}
You are using setContentView, so you are just changing the view layout. When you press the backbutton, the Android calls onBackPressed, which the default implementation is to call finnish() method, that closes the activity.
You can override the onBackPressed method to set the other view.
#Override
public void onBackPressed()
{
//setContentView the previous view
}
Hope it helps!
you can always override the onBackPressed method of Activity, you'll have something like this
public class MainActivity extends Activity {
ImageButton flightInfoButton;
ImageButton airportGuideButton;
ImageButton visitorInfoButton;
ImageButton saaDcaButton;
ImageButton cargoButton;
private enum VIEWS {
VIEW_1, VIEW_2, VIEW_3
};
private VIEWS mSelectedView = VIEWS.VIEW_1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flightInfoButton = (ImageButton) findViewById(R.id.flightInfo);
airportGuideButton = (ImageButton) findViewById(R.id.airportGuide);
visitorInfoButton = (ImageButton) findViewById(R.id.visitorInfo);
saaDcaButton = (ImageButton) findViewById(R.id.saaDca);
cargoButton = (ImageButton) findViewById(R.id.cargo);
airportGuideButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView1();
}
});
visitorInfoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView2();
}
});
saaDcaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView3();
}
});
}
private void showView1() {
setContentView(R.layout.airport_guide);
mSelectedView = VIEWS.VIEW_1;
}
private void showView2() {
setContentView(R.layout.visitor_info);
mSelectedView = VIEWS.VIEW_2;
}
private void showView3() {
setContentView(R.layout.saa_dca);
mSelectedView = VIEWS.VIEW_3;
}
#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);
return true;
}
#Override
public void onBackPressed() {
switch (mSelectedView) {
case VIEW_1:
super.onBackPressed();
break;
case VIEW_2:
showView1();
break;
case VIEW_3:
showView2();
break;
}
}
}
All you is doing that you are changing the Content View of the class MainActivity you need to create sperate classes for your difreent layouts and you can call it by INTENT
This is happennig because you are using only one activity, and on click just changing the content view. Even though this appears like a multi page activity, it is only one screen. Hence onBackPressed() it closes. Yo will have to create different activiies for each of your menu options and start them using Intents on Button Click.
Intent i = new Intent(this, SecondActivity.class);
startActivity(i);
You are using only one activity, if it is many activity mean you can track back to previously loaded activity.
else you must needed only one activity mean please store the layouts in some array, then in the onBackPressed() you can it get LIFO manner
#Override
public void onBackPressed() {
}