I have two activities,one is a MainActivity which has navigation drawer working.The Other is a testActivity which extends from the MainActivity.When I move from the MainActivity to the testActivity the navigation bar appears there but not working when i click there.
I have read too many posts on this like extending navigation drawer activity to other activities but I didnt understand them.
The following is my MainActivity
public class MainActivity extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
Button nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dl = (DrawerLayout) findViewById(R.id.activity_main);
t = new ActionBarDrawerToggle(this, dl, R.string.Open, R.string.Close);
nextBtn = (Button)findViewById(R.id.nextAct);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,TestActivity.class);
startActivity(intent);
}
});
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nv = (NavigationView) findViewById(R.id.nv);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.account:
Toast.makeText(MainActivity.this, "My Account", Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(MainActivity.this, "Settings", Toast.LENGTH_SHORT).show();
break;
case R.id.mycart:
Toast.makeText(MainActivity.this, "My Cart", Toast.LENGTH_SHORT).show();
break;
default:
return true;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(t.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
The following is the testActivity.
public class TestActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
}
The second activity gets the navigation bar as i have extended this from the MainActivity but that is not clickable in this new activity.Can any edit the code so that it will be clickable.
I think that the best way to do this is to use fragments. The navigation drawer + bar stays the same, and you change fragments in the rest of the screen. Hope it helps !
Related
I am learning android and I am facing a challenge no idea on how to resolve it. That is am unable to go back to the fragment that started the activity. I am opening second activity from fragment but when I press the back button on second activity it does not navigate to the fragment that opened the activity,it shows the home fragment. I have tried this and no success.
and this is the chat fragment that is opening the second fragment
and this is the second activity which if I press back button does not go to chat fragment
and when I press the back button of the second activity this is what am getting. Its showing home fragment content
Here is my Main Activity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
Toolbar toolbar;
TextView title,txt_profile_contact,txt_profile_name;
ActionBarDrawerToggle toggle;
DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationRepository=new NotificationRepository(this);
toolbar=findViewById(R.id.toolbar);
title=toolbar.findViewById(R.id.tool_bar_title);
title.setText(R.string.home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
drawer= findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
assert drawer != null;
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
doExit(false);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment=null;
int idd=R.id.main_fragment_main;
if (id == R.id.menu_chat)
{
title.setText("Chat");
fragment=new ChatFragment();
} else (id == R.id.menu_home) {
title.setText("Home");
fragment=new HomeFragment();
Utils.setIsOnChatActivity(this,false);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
load_fragment(fragment);
return true;
}
private void load_fragment(Fragment fragment)
{
if(fragment==null)
{
return;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.fadein, R.anim.fadeout);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
toolbar.setBackgroundResource(R.color.colorPrimary);
title.setTextColor(getResources().getColor(R.color.white));
try {
ft.replace(R.id.main_fragment, fragment)
.addToBackStack(null)
.commit();
} catch (IllegalStateException e) {
//ExceptionHandler.logException(e);
}
}
}
and here is the chat fragment
public class ChatFragment extends Fragment implements TutorListAdapter.TutorOnclickListener{
private static final String TAG = ChatFragment.class.getSimpleName();
public ChatFragment() {
// Required empty public constructor
}
FloatingActionButton actionButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_chat, container, false);
actionButton=view.findViewById(R.id.new_chat_list_btn);
actionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(getActivity(),SecondActivity.class);
startActivity(intent);
mActivity.overridePendingTransition(R.anim.fadein, R.anim.fade_out);
}
});
return view;
}
}
and here is my second activity. NB I have tried even the commented code and does not work
public class SecondActivity extends AppCompatActivity {
Toolbar toolbar;
TextView barText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject_details);
toolbar=findViewById(R.id.custom_tool_bar);
barText=toolbar.findViewById(R.id.toolbar_title);
barText.setText("My Activity");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
// #Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home) {
// onBackPressed();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// #Override
// public void onBackPressed() {
// Toast.makeText(this, "back pressed?", Toast.LENGTH_SHORT).show();
// if ( getFragmentManager().getBackStackEntryCount() > 0)
// {
// getFragmentManager().popBackStack();
// return;
// }
// super.onBackPressed();
// }
#Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
}
Step-1: Create a custom ViewModelFactory which is basically a Singleton class. This class provides ViewModel.
CustomViewModelProvider.java
public class CommonViewModelProvider extends ViewModelProvider.NewInstanceFactory {
private static CommonViewModelProvider commonViewModelProvider;
private final BottomNavigationViewModel bottomNavigationViewModel;
CommonViewModelProvider(){
bottomNavigationViewModel = new BottomNavigationViewModel();
}
public static CommonViewModelProvider getInstance(){
if (commonViewModelProvider == null)
commonViewModelProvider = new CommonViewModelProvider();
return commonViewModelProvider;
}
#NotNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass){
return (T) bottomNavigationViewModel;
}
}
BottomNavigationViewModel.java
public class BottomNavigationViewModel extends ViewModel {
private final MutableLiveData<Integer> currentFragmentId;
public Integer getCurrentFragmentId(){
return currentFragmentId.getValue();
}
public void setCurrentFragmentId(int currFragmentId){
currentFragmentId.setValue(currFragmentId);
}
public BottomNavigationViewModel(){
currentFragmentId = new MutableLiveData<>();
// R.id.navigation_snap is my first fragment. You should replace with your FirstFragment i.e HomeFragment
currentFragmentId.setValue(R.id.navigation_snap);
}
}
Step-2:
You would have a BottomNavigationActivity which has 3 fragments. And 3rd one is your ChatFragment. Inside this activity I am getting current fragment from BottomNavigationViewModel and set it to BottomNavigationView like navView.setSelectedItemId(currentFragment);. So that when you back from SecondActivity to BottomNavigationActivity, ChatFragment will be shown instead of HomeFragment.
BottomNavigationActivity.java
public class BottomNavigationActivity extends AppCompatActivity {
BottomNavigationViewModel bottomNavigationViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
//bottomNavigationViewModel = new ViewModelProvider(this).get(BottomNavigationViewModel.class);
CommonViewModelProvider commonViewModelProvider = CommonViewModelProvider.getInstance();
bottomNavigationViewModel = commonViewModelProvider.create(BottomNavigationViewModel.class);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_snap, R.id.navigation_home, R.id.navigation_chat)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
Integer currentFragment = bottomNavigationViewModel.getCurrentFragmentId();
navView.setSelectedItemId(currentFragment);
}
}
Step-3:
Now you want to open SecondActivity from ChatFragment. Well, in SecondActivity just update currentFragmentId variable of BottomNavigationViewModel, so that when you pressback button, this currentFragment will be shown in BottomNavigationActivity.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
CommonViewModelProvider commonViewModelProvider = CommonViewModelProvider.getInstance();
BottomNavigationViewModel bottomNavigationViewModel = commonViewModelProvider.create(BottomNavigationViewModel.class); Log.d("tisha==>>","View Model ID inside Second Activity"+ bottomNavigationViewModel.hashCode());
bottomNavigationViewModel.setCurrentFragmentId(R.id.navigation_chat);
}
}
NOTE: Whenever you want to open BottonNavigationActivity make sure you have set correct fragment which will be open first. Use below code to set currentFragment to ViewModel which is already done in SecondActivity.
CommonViewModelProvider commonViewModelProvider = CommonViewModelProvider.getInstance();
BottomNavigationViewModel bottomNavigationViewModel = commonViewModelProvider.create(BottomNavigationViewModel.class); Log.d("tisha==>>","View Model ID inside Second Activity"+ bottomNavigationViewModel.hashCode());
bottomNavigationViewModel.setCurrentFragmentId(R.id.navigation_chat);
Android Error I'm a real noob when it comes to Android Studio, and I'm trying to make it so when I click a button in IntroActivity, it will direct me to the FeaturedActivity page, which contains a list and navigation drawer, if that's important. But when I click the first time in the emulator, the app stops, and when I go back and click it again, nothing happens. I have Java Code for both activities. Could someone help me please?
<activity
android:name=".FeaturedActivity"
android:label="#string/title_activity_featured"
android:theme="#style/AppTheme.NoActionBar"></activity>
The first activity
public class IntroActivity extends AppCompatActivity {
Button ComeInButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
ComeInButton = (Button) findViewById(R.id.ComeIn);
ComeInButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(IntroActivity.this, FeaturedActivity.class);
startActivity(i);
}
});
}
}
Featured Activity
public class FeaturedActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String [] art_Names;
TypedArray pics;
String[] artist_Names;
String[] desc;
List<RowItem> rowItems;
ListView myListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_featured);
rowItems=new ArrayList<RowItem>();
art_Names=getResources().getStringArray(R.array.Featured_Arts);
pics=getResources().obtainTypedArray(R.array.Art_Pics);
artist_Names=getResources().getStringArray(R.array.Artist_Names);
desc=getResources().getStringArray(R.array.Descriptions);
for(int i=0;i<art_Names.length;i++){
RowItem item=new RowItem(art_Names[i], pics.getResourceId(i, -1),artist_Names[i],desc[i]);
rowItems.add(item);
}
myListView=(ListView)findViewById(R.id.list);
CustomerAdapter adapter = new CustomerAdapter(this,rowItems);
myListView.setAdapter(adapter);
myListView.setOnClickListener((View.OnClickListener) this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String art_name=rowItems.get(position).GetArtName();
Toast.makeText(getApplicationContext(),""+art_name,Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.featured, menu);
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
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;
}
}
The question is a little vague on the details, but taking a shot in the dark, did you register FeaturedActivity in the app manifest?
Something like:
<activity
android:name=".FeaturedActivity"
android:label="#string/title_activity_featured"
android:theme="#style/AppTheme">
should be in your AndroidManifest.xml file.
You are probably getting a nice error message in logcat, so please look there :)
I think the crash cause is where you are casting FeaturedActivity to View.OnClickListener inside FeatureActivity#onCreate(). since it does not implement View.OnClickListener, you get ClassCastException and since you do not catch this exception, then your app crashes.
EDIT I meant this line:
public class FeaturedActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
myListView.setOnClickListener((View.OnClickListener) this); // this line
}
...
}
EDIT 2 You can fix it by implementing View.OnClickListener in FeatureActivity like this:
public class FeaturedActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
myListView.setOnClickListener(this); // cast is not needed anymore
}
#Override
protected void onClick(View v) {
// handle click
}
...
}
By the way, If you want to handle item click for ListView you should use AdapterView#setOnItemClickListener() instead so you get notified when one of the items in ListView is clicked
I use MaterialDrawer and code MainActivity is:
public class MainActivity extends AppCompatActivity implements KitchenFragment.CallbackOne {
public static final String TAG = "myLogTag";
private Toolbar mToolbar;
private Drawer drawer;
private FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "CLICK NOCL");
}
});
setSupportActionBar(mToolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(false);
fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.content_frame);
if (fragment == null) {
fragment = MenuFragment.newInstance();
fm.beginTransaction()
.add(R.id.content_frame, fragment)
.commit();
}
drawer = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.withActionBarDrawerToggle(true)
.withHeader(R.layout.drawer_header)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.menu).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.kitchen_title).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.information_title).withEnabled(false)
).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
Log.d(TAG, "position clicked: " + position);
Fragment fragment = MenuFragment.newInstance();
switch (position) {
case 1:
fragment = MenuFragment.newInstance();
break;
case 2:
fragment = KitchenFragment.newInstance();
break;
default:
fragment = new Fragment();
}
fm.beginTransaction().replace(R.id.content_frame, fragment).commit();
return false;
}
})
.withFireOnInitialOnClick(true)
.withSavedInstance(savedInstanceState)
.withOnDrawerNavigationListener(new Drawer.OnDrawerNavigationListener() {
#Override
public boolean onNavigationClickListener(View view) {
Log.d(TAG, "CLICK in DNL");
if (!drawer.getActionBarDrawerToggle().isDrawerIndicatorEnabled()) {
onBackPressed();
return true;
} else
return false;
}
})
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "CLICK OIS");
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState = drawer.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen())
drawer.closeDrawer();
else if (getFragmentManager().getBackStackEntryCount() == 1) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawer.getActionBarDrawerToggle().syncState();
getFragmentManager().popBackStack();
} else if (getFragmentManager().getBackStackEntryCount() > 0)
getFragmentManager().popBackStack();
else
super.onBackPressed();
}
#Override
public void setFirstSelected() {
drawer.setSelection(1);
}
}
I'm trying to trace a Click in mToolbar.setNavigationOnClickListener
and withOnDrawerNavigationListener and onOptionsItemSelected.
None of the listeners not reacted for clicking.
How you see i use Activity that launches Fragment (1), which in turn lets Fragment (2 and 3). In 2 and 3 Fragment in OnCreate i use ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); , and I need to by pressing the back button (in toolbar), returning the previous fragment, and not open Drawer
The MaterialDrawer already handles all the listeners for you. If you need to do an action after the drawer opens or closes you can provide the listener via the DrawerBuilder
For the icon you have this listener:
OnDrawerNavigationListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1158
For drawer close / open this listener:
OnDrawerListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1116
I suggest you to create new Activity using android studio wizard. File->New->Activity->Navigation Drawer Activity.
In that case ActionBarDrawerToaggle is used
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
This toggle contains click listener which handle open/close drawer functionality for you.
Also you can that item clicks implemented through OnNavigationItemSelectedListener.onNavigationItemSelected(MenuItem item)
Something is not OK in my code. Normally the activity lifecycle is
- at starting app: onCreate --> onStart --> onResume
- at closing app: onPause --> onStop --> onDestroy
- pressing the home button or the task switch button: onPause --> onStop
- coming back to the already opened app from another app: onStart --> onResume
But for some reason my app also calls onDestroy when I press the home button or the task switch button, and it calls onCreate, when I go back to the already opened app.
My app has 2 Activites:
- LoginActivity, which should appear first, if nobody is logged on, or if the logout button is pressed
- MainActivity to handle the main functions.
Please help me identify what causes this not normal behavior of lifecycle.
Thanks!
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public Helper helper = new Helper(this);
public static final String SP_DATA = "SP_DATA";
public static final String FB_LOGIN_STATUS = "FB_LOGIN_STATUS";
public static final String FLRT = "FLRT";
public SharedPreferences sharedPreferences;
public FragmentManager fragmentManager = getFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(FLRT, "onCreate");
helper.makeToast("onCreate");
sharedPreferences = getSharedPreferences(SP_DATA, MODE_PRIVATE);
boolean bAlreadyLoggedIn = sharedPreferences.getBoolean(FB_LOGIN_STATUS, false);
if (bAlreadyLoggedIn) {
Log.d(FLRT, "Already logged in");
}
else {
Log.d(FLRT, "Not logged in");
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
showFragment(new FirstFragment(),"FirstFragment");
Button btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
showActivity(MainActivity.this, LoginActivity.class);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
}
private void showActivity(Context context_fromActivity, Class<?> class_toActivty){
Intent intent = new Intent(context_fromActivity, class_toActivty);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
MainActivity.this.finish();
}
private void logout() {
Log.d(FLRT, "Logging out...");
sharedPreferences = getSharedPreferences(SP_DATA, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(FB_LOGIN_STATUS, false);
editor.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getFragmentManager().getBackStackEntryCount() > 1 ){
getFragmentManager().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);
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_first_layout:
showFragment(new FirstFragment(), "FirstFragment");
break;
case R.id.nav_second_layout:
showFragment(new SecondFragment(), "SecondFragment");
break;
case R.id.nav_third_layout:
showFragment(new ThirdFragment(), "ThirdFragment");
break;
case R.id.nav_share:
break;
case R.id.nav_send:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void showFragment(Fragment fragment, String sFragmentTAG) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.findFragmentByTag(sFragmentTAG) != null) {
Log.d(FLRT, "Fragment found, using existing one: " + sFragmentTAG);
fragment = fragmentManager.findFragmentByTag(sFragmentTAG);
}
fragmentTransaction.replace(R.id.fragmentContainer, fragment, sFragmentTAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
protected void onStart() {
super.onStart();
Log.d(FLRT, "onStart");
helper.makeToast("onStart");
}
#Override
protected void onResume() {
super.onResume();
Log.d(FLRT, "onResume");
helper.makeToast("onResume");
}
#Override
protected void onPause() {
super.onPause();
Log.d(FLRT, "onPause");
helper.makeToast("onPause");
}
#Override
protected void onStop() {
super.onStop();
Log.d(FLRT, "onStop");
helper.makeToast("onStop");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(FLRT, "onDestroy");
helper.makeToast("onDestroy");
}
}
LoginActivity:
public class LoginActivity extends AppCompatActivity {
public static final String SP_DATA = "SP_DATA";
public static final String FB_LOGIN_STATUS = "FB_LOGIN_STATUS";
public static final String FLRT = "FLRT";
public SharedPreferences sharedPreferences;
private Button btn_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_start = (Button) findViewById(R.id.btn_start);
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
showActivity(LoginActivity.this, MainActivity.class);;
}
});
}
private void showActivity(Context context_fromActivity, Class<?> class_toActivty){
Intent intent = new Intent(context_fromActivity, class_toActivty);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
LoginActivity.this.finish();
}
private void login() {
Log.d(FLRT, "Logging in...");
sharedPreferences = getSharedPreferences(SP_DATA, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(FB_LOGIN_STATUS, true);
editor.commit();
}
}
Nothing surprising here,
The behavior of onDestroy() method is
In some situations System simply kill the activity's hosting process without calling this method. OR System can directly destroy your app If its getting into low memory situations even your app is in onStop() event, And another thing to notice is onStop() method also may not be called, in low memory situations.
See onDestroy() method in details.
Ok, when you call MainActivity.this.finish(); or LoginActivity.this.finish(); the activity is distroyed. try not call finish() if you don't want destroy needed activity
I found the problem: in the mainfest file android:noHistory="true"
was set for both activities. Now the activity lifecycle is working fine.
However now from the Login screen I can simply can go back to the Main screen with pressing the Back button... and that's not ok. :)
So i start on one screen that is for building an image. my build mode
When i click on stencil i go into a new activity that looks like this stencil picker
While in my stencil picker i have an onclick method for the pictures using a switch case. what i need to do is remember what image i clicked on and apply that image to the previous page. I need to also be able to save the images that are added to the build mode so they can stack ontop of each other (but that is a secondary problem).
here is my code for the build page
public class BuildMode extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemSelectedListener {
private Button mStencilButton;
//private Button mColorButton;
private Button mUndoButton;
private Button mRedoButton;
private Spinner mColorSpinner;
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_build_mode);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//bit map to get stencil selected and place into build mode
// Bundle extras = getIntent().getExtras();
// byte[] byteArray = extras.getByteArray("picture");
// Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
// ImageView image = (ImageView) findViewById(R.id.egg_image);
// image.setImageBitmap(bmp);
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);
mStencilButton = (Button) findViewById(R.id.stencil_button);
// mColorButton = (Button) findViewById(R.id.color_button);
mUndoButton = (Button) findViewById(R.id.undo_button);
mRedoButton = (Button) findViewById(R.id.redo_button);
mColorSpinner = (Spinner) findViewById(R.id.colors_spinner);
mColorSpinner.setOnItemSelectedListener(this);
mStencilButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BuildMode.this, StencilList.class);
startActivity(intent);
}
});
mUndoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mRedoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mColorSpinner = (Spinner) findViewById(R.id.colors_spinner);
mColorSpinner.setOnItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.build_mode, menu);
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();
//noinspection SimplifiableIfStatement
if (id == R.id.about_us) {
return true;
}
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_manage_build) {
// Handle the camera action
} else if (id == R.id.nav_gallery_build) {
Intent intent = new Intent(BuildMode.this, PreviewMode.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
// mImageView.setBackgroundColor(Color.WHITE);
break;
case 1:
// mImageView.setBackgroundColor(Color.YELLOW);
break;
case 2:
// mImageView.setBackgroundColor(Color.GREEN);
break;
case 3:
// mImageView.setBackgroundColor(Color.BLUE);
break;
case 4:
// mImageView.setBackgroundColor(Color.RED);
break;
case 5:
// mImageView.setBackgroundColor(Color.BLACK);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
and my code for the stencil page
public class StencilList extends AppCompatActivity {
private ImageView mStencil1;
private Bitmap bmp;
private byte[] byteArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stencil_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void useStencil(View view) {
// Intent intent = new Intent(this, BuildMode.class);
switch (view.getId()) {
case R.id.stencil_image_1:
// intent.putExtra("picture", byteArray);
// startActivity(intent);
break;
case R.id.stencil_image_2:
break;
case R.id.stencil_image_3:
break;
case R.id.stencil_image_4:
break;
case R.id.stencil_image_5:
break;
case R.id.stencil_image_6:
break;
case R.id.stencil_image_7:
break;
case R.id.stencil_image_8:
break;
case R.id.stencil_image_9:
break;
case R.id.stencil_image_10:
break;
case R.id.stencil_image_11:
break;
case R.id.stencil_image_12:
break;
case R.id.stencil_image_13:
break;
case R.id.stencil_image_14:
break;
}
}
private void imageClicked()
{
}
}
I would try this:
When you click on the stencil option, you need a way to know the position clicked by the user
Perhaps, you can easily create a variable to set when a stencil is clicked then pass that as an Extra to your previous activity
Once you are in the other activity, keep a simple integer array of your image drawables.
Finally, get the corresponding image from using the index you received through the intent. That should work!
I hope this helps!