I have one main activity. It start another sub activities as Tab. On closing sub activities memory isn't released using by sub tab. Memory increases every time on opening other tabs.
After some time my application get crashed:
public class Main extends Activity {
public static Activity activity;
private Bundle saveInstance;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.activity = this;
this.saveInstance = savedInstanceState;
Application app = Application.getSharedInstance();
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onBackPressed()
{
// super.onBackPressed();
AlertUtills.showQuitDialog(Main.this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final TabHost tabHost = (TabHost) this
.findViewById(android.R.id.tabhost);
LocalActivityManager mLocalActivityManager = new LocalActivityManager(
this, false);
mLocalActivityManager.dispatchCreate(saveInstance);
tabHost.setup(mLocalActivityManager);
switch (item.getItemId())
{
case R.id.create_new:
{
if (CommonUtilities.isTabNotExist(tabHost, "NewProject"))
{
TabSpec spec2 = tabHost.newTabSpec("NewProject");
Intent in = new Intent(this, Activity_cretateNew.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
spec2.setContent(in);
spec2.setIndicator("New Project");
tabHost.addTab(spec2);
tabHost.setCurrentTabByTag("NewProject");
}
tabHost.setCurrentTabByTag("NewProject");
}
break;
case R.id.open:
{
OpenDialog dialog = new OpenDialog(this, "Open Project", false,
OpenDialogType.CORELOG_OPEN);
dialog.Show();
}
break;
case R.id.menu_exit:
onBackPressed();
break;
case R.id.import_las:
{
if (isCurrentProjectExist())
{
if (CommonUtilities.isTabNotExist(tabHost, "ImportLas"))
{
TabSpec spec2 = tabHost.newTabSpec("ImportLas");
Intent in = new Intent(this, LASImportWizard.class);
spec2.setContent(in);
spec2.setIndicator("Import Las");
tabHost.addTab(spec2);
}
tabHost.setCurrentTabByTag("ImportLas");
}
}
break;
case R.id.import_coredata:
{
if (isCurrentProjectExist())
{
if (CommonUtilities.isTabNotExist(tabHost, "coredata"))
{
TabSpec spec2 = tabHost.newTabSpec("coredata");
Intent in = new Intent(Main.this,
CoreDataImportWizard.class);
spec2.setContent(in);
spec2.setIndicator("Core Data Import");
tabHost.addTab(spec2);
}
tabHost.setCurrentTabByTag("coredata");
}
}
break;
case R.id.list_Data:
{
if (isProjectHasWell())
{
if (CommonUtilities.isTabNotExist(tabHost, "ListData"))
{
TabSpec spec1 = tabHost.newTabSpec("ListData");
Intent in = new Intent(Main.this, ListDataWindow.class);
// in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
spec1.setContent(in);
spec1.setIndicator("List Data");
tabHost.addTab(spec1);
}
tabHost.setCurrentTabByTag("ListData");
}
}
break;
case R.id.basemap:
{
if (isCurrentProjectExist())
{
if (CommonUtilities.isTabNotExist(tabHost, "BaseMap"))
{
TabSpec spec2 = tabHost.newTabSpec("BaseMap");
Intent inBasemap = new Intent(Main.this, Basemap.class);
spec2.setContent(inBasemap);
spec2.setIndicator("Base Map");
tabHost.addTab(spec2);
}
tabHost.setCurrentTabByTag("BaseMap");
}
}
break;
case R.id.logPlot:
{
if (isProjectHasWell())
{
if (CommonUtilities.isTabNotExist(tabHost, "LogPlot"))
{
TabSpec spec2 = tabHost.newTabSpec("LogPlot");
Intent intentLogPlot = new Intent(Main.this,
Logplot_Activity.class);
spec2.setContent(intentLogPlot);
spec2.setIndicator("Log Plot");
tabHost.addTab(spec2);
}
tabHost.setCurrentTabByTag("LogPlot");
}
}
break;
case R.id.show_hide_project_explorer:
{
FrameLayout frameLayout = (FrameLayout) activity
.findViewById(R.id.explorerFrame);
if (item.isChecked() == true)
{
item.setChecked(false);
frameLayout.setVisibility(View.GONE);
}
else
{
item.setChecked(true);
frameLayout.setVisibility(View.VISIBLE);
}
break;
}
}
return true;
}
private boolean isCurrentProjectExist()
{
return Application.getSharedInstance().getCurrentProject() == null ? false
: true;
}
private boolean isProjectHasWell()
{
return isCurrentProjectExist()
&& Application.getSharedInstance().getCurrentProject()
.getAllWells().length != 0 ? true : false;
}
public static Activity getMainActivity()
{
return activity;
}
}
Run hprof or another similar profiler. If this is happening, the number of objects of your tab activites will increase. See whats holding onto references to them, and then fix them so they don't.
Its kind of hard to debug this kind of thing without those hprofs.
Related
Very strange thing. I found out that when I do spEditor.putBoolean("closePxCmInfo", false).apply(); then an error occurs like that:
2022-01-03 10:47:39.761 3821-3917/? E/ViewRootImpl#6827b15[mierzenieopencv]: Surface is not valid.
2022-01-03 10:47:39.774 3821-3917/? E/ViewRootImpl#f395385[mierzenieopencv]: Surface is not valid.
2022-01-03 10:47:39.792 3821-3917/? E/ViewRootImpl#24f27f5[mierzenieopencv]: Surface is not valid.
2022-01-03 10:47:39.820 13383-13710/pl.jawegiel.mierzenieopencv E/OpenCV/StaticHelper: OpenCV error: Cannot load info library for OpenCV
2022-01-03 10:47:39.824 3335-3449/? E/BufferQueueProducer: [Splash Screen pl.jawegiel.mierzenieopencv[13383]#0] connect: BufferQueue has been abandoned
2022-01-03 10:47:39.824 3821-3917/? E/ViewRootImpl#4fd5d5c[mierzenieopencv]: Could not lock surface
java.lang.IllegalArgumentException
at android.view.Surface.nativeLockCanvas(Native Method)
at android.view.Surface.lockCanvas(Surface.java:345)
at android.view.ViewRootImpl.drawSoftware(ViewRootImpl.java:4018)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:3979)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3721)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3029)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1888)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8511)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
at android.view.Choreographer.doCallbacks(Choreographer.java:761)
at android.view.Choreographer.doFrame(Choreographer.java:696)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.os.HandlerThread.run(HandlerThread.java:65)
at com.android.server.ServiceThread.run(Unknown Source:12)
It has nothing to do with my lauout I tested it out. The problem is with this line that I mentioned about putting shared preference.
Here is my code:
Stages.java
public class Stages extends BaseActivity {
private final Stage0StageFragment stageZeroFragment = new Stage0StageFragment();
private final Stage1StageFragment stageOneFragment = new Stage1StageFragment();
private final Stage2StageFragment stageTwoFragment = new Stage2StageFragment();
private final Stage3StageFragment stageThreeFragment = new Stage3StageFragment();
private BottomNavigationView bottomNavView;
private int startingPosition, newPosition;
OnSwitchFragmentFromStageTwo onSwitchFragmentFromStageTwo;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Util.setThemeBasedOnPrefs(this);
setContentView(R.layout.stages);
spEditor.putBoolean("closePxCmInfo", false).apply(); // HERE IS THE PROBLEM
bottomNavView = findViewById(R.id.bottom_navigation);
bottomNavView.setItemIconTintList(null);
bottomNavView.setOnNavigationItemSelectedListener(item -> {
if (bottomNavView.getSelectedItemId() == R.id.navigation_stage_zero) {
if (!sp.getBoolean("correctionDone", false)) {
AlertDialog alertDialog = Util.createAlertDialog(Stages.this, android.R.drawable.ic_dialog_info, R.string.hide_dialog_title, getString(R.string.stage_zero_confirmation), (dialog, which) -> {
spEditor.putBoolean("correctionDone", true).apply();
bottomNavView.setSelectedItemId(item.getItemId());
showFragment(item.getItemId());
});
alertDialog.setOnShowListener(arg0 -> setAlertDialogButtonsAttributes(alertDialog));
alertDialog.show();
return false;
} else {
showFragment(item.getItemId());
return true;
}
} else if (bottomNavView.getSelectedItemId() == R.id.navigation_stage_two) {
try {
if (onSwitchFragmentFromStageTwo.onSwitchFragmentFromFragmentTwo() <= 0.5 && !sp.contains("closePxCmInfo")) {
AlertDialog ad = Util.createAlertDialog(Stages.this, android.R.drawable.ic_dialog_alert, R.string.hide_dialog_title_alert, getResources().getString(R.string.benchmark_not_drawn), (dialog, which) -> {
spEditor.putBoolean("closePxCmInfo", true).apply();
bottomNavView.setSelectedItemId(item.getItemId());
showFragment(item.getItemId());
});
ad.setOnShowListener(arg0 -> setAlertDialogButtonsAttributes(ad));
ad.show();
return false;
} else {
showFragment(item.getItemId());
return true;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
} else {
showFragment(item.getItemId());
}
return true;
});
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (!sp.getBoolean("correctionDone", false))
ft.replace(R.id.content_frame, stageZeroFragment);
else {
ft.replace(R.id.content_frame, stageOneFragment);
bottomNavView.setSelectedItemId(R.id.navigation_stage_one);
}
ft.commit();
}
#Override
BaseActivity getActivity() {
return this;
}
private void setAlertDialogButtonsAttributes(AlertDialog alertDialog2) {
alertDialog2.getButton(DialogInterface.BUTTON_NEGATIVE).setBackground(AppCompatResources.getDrawable(this, R.drawable.button_selector));
alertDialog2.getButton(DialogInterface.BUTTON_POSITIVE).setBackground(AppCompatResources.getDrawable(this, R.drawable.button_selector));
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1.0f);
params.setMargins(10, 0, 10, 0);
alertDialog2.getButton(DialogInterface.BUTTON_NEGATIVE).setLayoutParams(params);
alertDialog2.getButton(DialogInterface.BUTTON_POSITIVE).setLayoutParams(params);
}
public void showFragment(int viewId) {
Fragment fragment = null;
switch (viewId) {
case R.id.navigation_stage_zero:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_zero) {
fragment = stageZeroFragment;
newPosition = 0;
}
break;
case R.id.navigation_stage_one:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_one) {
fragment = stageOneFragment;
newPosition = 1;
}
break;
case R.id.navigation_stage_two:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_two) {
fragment = stageTwoFragment;
newPosition = 2;
}
break;
case R.id.navigation_stage_three:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_three) {
fragment = stageThreeFragment;
newPosition = 3;
}
break;
}
if (fragment != null) {
if (startingPosition > newPosition) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.content_frame, fragment).commit();
}
if (startingPosition < newPosition) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.replace(R.id.content_frame, fragment).commit();
}
startingPosition = newPosition;
}
}
}
BaseActivity.java
public abstract class BaseActivity extends AppCompatActivity {
SharedPreferences sp;
SharedPreferences.Editor spEditor;
BaseActivity childActivity;
#Override
#SuppressWarnings("CommitPrefEdits")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = PreferenceManager.getDefaultSharedPreferences(BaseActivity.this);
spEditor = sp.edit();
childActivity = getActivity();
if(childActivity instanceof MainActivity)
MobileAds.initialize(this, initializationStatus -> {});
}
#Override
protected void onPause() {
if (childActivity instanceof Stages) {
spEditor.putFloat("px_cm", 0f);
spEditor.putFloat("rozmiar_px", 0f);
spEditor.putFloat("rozmiar_px_x", (float) 0f);
spEditor.putFloat("rozmiar_px_y", (float) 0f);
spEditor.apply();
}
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (childActivity instanceof Stages) {
getMenuInflater().inflate(R.menu.main, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (childActivity instanceof Stages)
return Util.onOptionsItemSelected(this, item);
else
return false;
}
#Override
public void onBackPressed() {
if (childActivity instanceof Stages) {
Intent intent = new Intent(childActivity, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
super.onBackPressed();
}
abstract BaseActivity getActivity();
}
Help me please!
I have a problem with the order in which my Android Activity is intitialized.
Basics:
The Activity contains a ViewPager with contains 3 Fragments. The Activity is opened this way:
Intent foodsActivityIntent = new Intent(getActivity(), FoodsActivity.class);
foodsActivityIntent.putExtra("NavigationPosition", navigationPosition);
foodsActivityIntent.putExtra("SearchQuery", searchQuery);
foodsActivityIntent.putExtra("SelectedDateMillis", _currentDay.toDate().getTime());
startActivityForResult(foodsActivityIntent, 200);
In the onCreate - Method i catch the Intent and do some stuff:
Intent intent = getIntent();
if (intent != null) {
//Some stuff
_foodsPagerAdapter.performSearch();
}
The interesting part here is "_foodsPagerAdapter.performSearch()". With this i want to perform a search in each Fragment.
public void performSearch() {
if (_foodSearchFragment != null)
_foodSearchFragment.performSearch();
if (_foodFavoritesFragment != null)
_foodFavoritesFragment.performSearch();
if (_foodCustomFragment != null)
_foodCustomFragment.performSearch();
}
The Problem:
As you can see, the search method in each Fragment is only called if the Fragment is not null. My problem is that the getItem() - Method(which initializes the Fragments in the Adapter) is called after the onCreate (and onStart) Method finished. So the performSearch - Method for each Fragment is never called.
You can understand this better with this Logcat output:
First performSearch is called and then getItem(). But getItem must be called first for my code to work.
getItem():
#Override
public Fragment getItem(int i) {
Log.i("FoodActivityTest", "call getItem in FragmentPagerAdapter");
Fragment fragment = null;
switch (i) {
case 0:
if (_foodSearchFragment == null)
_foodSearchFragment = new FoodSearchFragment();
fragment = _foodSearchFragment;
break;
case 1:
if (_foodFavoritesFragment == null)
_foodFavoritesFragment = new FoodFavoritesFragment();
fragment = _foodFavoritesFragment;
break;
case 2:
if (_foodCustomFragment == null)
_foodCustomFragment = new FoodCustomFragment();
fragment = _foodCustomFragment;
break;
}
return fragment;
}
What am I doing wrong? Do I need to approach the problem differently?
EDIT 1:
FoodsActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foods);
//Init some views
_viewPager = findViewById(R.id.viewpager_foods);
_foodsPagerAdapter = new FoodsPagerAdapter(getSupportFragmentManager(), this);
_viewPager.setAdapter(_foodsPagerAdapter);
handleOpenIntent();
//do more stuff (show ads etc.)
Log.i("FoodActivityTest", "onCreate finished");
}
#Override
protected void onStart() {
super.onStart();
Log.i("FoodActivityTest", "onStart finished");
}
private void handleOpenIntent() {
Intent intent = getIntent();
if (intent != null) {
int navigationPosition = intent.getExtras().getInt("NavigationPosition");
String searchQuery = intent.getExtras().getString("SearchQuery");
_viewPager.setCurrentItem(navigationPosition);
_foodsPagerAdapter.performSearch(searchQuery);
}
}
EDIT 2:
FoodsPagerAdapter:
public class FoodsPagerAdapter extends FragmentPagerAdapter {
private Context _context;
private FoodSearchFragment _foodSearchFragment;
private FoodFavoritesFragment _foodFavoritesFragment;
private FoodCustomFragment _foodCustomFragment;
public FoodsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
_context = context;
}
#Override
public Fragment getItem(int i) {
Log.i("FoodActivityTest", "call getItem in FragmentPagerAdapter");
Fragment fragment = null;
switch (i) {
case 0:
if (_foodSearchFragment == null)
_foodSearchFragment = new FoodSearchFragment();
fragment = _foodSearchFragment;
break;
case 1:
if (_foodFavoritesFragment == null)
_foodFavoritesFragment = new FoodFavoritesFragment();
fragment = _foodFavoritesFragment;
break;
case 2:
if (_foodCustomFragment == null)
_foodCustomFragment = new FoodCustomFragment();
fragment = _foodCustomFragment;
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return _context.getString(R.string.activity_foods_search);
case 1:
return _context.getString(R.string.activity_foods_favorites);
case 2:
return _context.getString(R.string.activity_foods_customfood);
default:
return "Error";
}
}
public void performSearch(String query) {
Log.i("FoodActivityTest", "call performSearch");
if (_foodSearchFragment != null)
_foodSearchFragment.performSearch(query);
if (_foodFavoritesFragment != null)
_foodFavoritesFragment.performSearch(query);
if (_foodCustomFragment != null)
_foodCustomFragment.performSearch(query);
}
You should be able to pull the values out of your intent before you initialize the other objects. From the looks of it currently, you are trying to populate an view with no data, then assign the data later. To solve, you could either better handle the null in your adapter, or move your data assignment. I would probably do the latter.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foods);
// Added this. Moved part of handleOpenIntent() here, other half is below view init.
String searchQuery = "";
Intent intent = getIntent();
if (intent != null) {
int navigationPosition = intent.getExtras().getInt("NavigationPosition");
searchQuery = intent.getExtras().getString("SearchQuery");
//should probably have some error handling if the SearchQuery is missing or the value is invalid.
}
// End of additions
//Init some views
_viewPager = findViewById(R.id.viewpager_foods);
_foodsPagerAdapter = new FoodsPagerAdapter(getSupportFragmentManager(), this);
_viewPager.setAdapter(_foodsPagerAdapter);
// added this too, moved out of handleOpenIntent()
_viewPager.setCurrentItem(navigationPosition);
_foodsPagerAdapter.performSearch(searchQuery);
// end of additions
//removed
//handleOpenIntent();
//do more stuff (show ads etc.)
Log.i("FoodActivityTest", "onCreate finished");
}
I have created a Firebase application.
Everything so far is working great. I have one issue, however, that I'm unable to fix.
My MainActivity.java is implementing an Interface ProgressDisplay.java
The Interface has two methods:
public interface ProgressDisplay {
public void showProgress();
public void hideProgress();
}
I'm not able to call these 2 methods from sub fragments, I'm unable to set the visibility on and off in the fragments.
ManageAccountFragment.java
package com.company.walt.fragments;
public class ManageAccountFragment extends Fragment {
private EditText mName;
private Button mUpdateBtn;
private ProgressBar mProgressBar;
public ManageAccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_manage_account, container, false);
mName = (EditText)view.findViewById(R.id.input_name);
mUpdateBtn = (Button)view.findViewById(R.id.btn_update);
mUpdateBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view){
if (!isEmpty (mName.getText().toString()))
{
showProgress();
Toast.makeText(getActivity(), "SHOW DIALOG", Toast.LENGTH_SHORT).show();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(mName.getText().toString())
//.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
.build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Log.d(TAG, "onComplete: User Profile updated");
}
}
});
hideProgress();
Toast.makeText(getActivity(), "HIDE DIALOG", Toast.LENGTH_SHORT).show();
}
}
}
});
hideSoftKeyboard();
return view;
}
private boolean isEmpty(String string){
return string.equals("");
}
/**
* Display progressbar
*/
protected void showProgress() {
if (getActivity() instanceof ProgressDisplay) {
((ProgressDisplay) getActivity()).showProgress();
}
}
/**
* Hide progressbar
*/
protected void hideProgress() {
if (getActivity() instanceof ProgressDisplay) {
((ProgressDisplay) getActivity()).hideProgress();
}
}
private void hideSoftKeyboard(){
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
MainActivity.java
package com.company.walt.activities;
public class MainActivity extends AppCompatActivity implements ProgressDisplay {
private static final String TAG = "MainActivity";
private static final int USER_PROFILE = 1;
private static final int PROFILE_MANAGE = 2;
private static final int PROFILE_SETTING = 3;
private Toolbar mainToolbar;
private AccountHeader headerResult = null;
private Drawer result = null;
private ProgressBar mProgressBar;
private ToggleButton switcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) { setTheme(R.style.NightTheme); }
else { setTheme(R.style.LightTheme);}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchAppTheme();
createToolbar();
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
buildHeader(false, savedInstanceState);
createDrawerBuilder();
getUserDetails();
}
#Override
protected void onResume() {
super.onResume();
checkAuthenticationState();
}
/**
* Used to check if user is authenticated or not
*/
private void checkAuthenticationState()
{
Log.d(TAG, "checkAuthenticationState: checking authentication state.");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null){
Log.d(TAG, "checkAuthenticationState: user is null, navigating back to login screen.");
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
else {
Log.d(TAG, "checkAuthenticationState: user is authenticated.");
}
}
/**
* Used to switch between light and dark mode
*/
public void switchAppTheme() {
switcher = (ToggleButton) findViewById(R.id.switcher);
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
switcher.setChecked(true);
}
switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
restartApp();
} else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
restartApp();
}
}
});
}
/**
* Used to create the toolbar on top
*/
private void createToolbar(){
mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle(R.string.app_name);
}
/**
* small helper method to reuse the logic to build the AccountHeader
* this will be used to replace the header of the drawer with a compact/normal header
*
* #param compact
* #param savedInstanceState
*/
private void buildHeader(boolean compact, Bundle savedInstanceState) {
IProfile profile_1;
//IProfile profile_2;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
profile_1 = new ProfileDrawerItem()
.withName(name)
.withEmail(email)
.withIcon(photoUrl);
//profile_2 = new ProfileDrawerItem().withName("Isensei").withEmail("itrade#gmail.com").withIcon(getResources().getDrawable(R.drawable.ic_user_58dp));
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.ip_menu_header_bg)
.withCompactStyle(compact)
.addProfiles(
profile_1,
//profile_2,
new ProfileSettingDrawerItem()
.withName("Manage Account")
.withDescription("Manage your details")
.withIcon(new IconicsDrawable(this,GoogleMaterial.Icon.gmd_settings)
.actionBar().colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_MANAGE),
new ProfileSettingDrawerItem()
.withName("Add Account")
.withDescription("Register new account")
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_person_add)
.actionBar().colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_SETTING)
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
//sample usage of the onProfileChanged listener
//if the clicked item has the identifier 1 add a new profile ;)
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == USER_PROFILE)
{
// Navigate to home fragment
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = new Fragment();
fragment = new HomeFragment();
transaction.replace(R.id.flContent, fragment);
transaction.commit();
}
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_MANAGE)
{
// Navigate to home fragment
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = new Fragment();
fragment = new ManageAccountFragment();
transaction.replace(R.id.flContent, fragment);
transaction.commit();
}
else if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING)
{
Toast.makeText(MainActivity.this, "ACCOUNT", Toast.LENGTH_SHORT).show();
}
/*
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING) {
IProfile newProfile = new ProfileDrawerItem()
.withNameShown(true)
.withName("Kensei")
.withEmail("kensei#gmail.com")
.withIcon(getResources().getDrawable(R.drawable.ic_user_58dp));
if (headerResult.getProfiles() != null) {
//we know that there are 2 setting elements. set the new profile above them ;)
headerResult.addProfile(newProfile, headerResult.getProfiles().size() - 2);
} else {
headerResult.addProfiles(newProfile);
}
}
*/
//false if you have not consumed the event and it should close the drawer
return false;
}
})
.build();
}
}
/**
* Used to create the drawer with all the icons and items
*/
private void createDrawerBuilder(){
//create the drawer and remember the `Drawer` result object
result = new DrawerBuilder()
.withActivity(this)
.withAccountHeader(headerResult)
.withToolbar(mainToolbar)
.addDrawerItems(
new SecondaryDrawerItem().withName(R.string.drawer_services)
.withIdentifier(1)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_device_hub))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_products)
.withIdentifier(2)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_shopping_cart))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_photos)
.withIdentifier(3)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_roll))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_poem)
.withIdentifier(4)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_content_copy))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_archives)
.withIdentifier(5)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_folder_open))
.withTag("Bullhorn"),
new SectionDrawerItem().withName(R.string.drawer_section_header).withEnabled(false),
new SecondaryDrawerItem().withName(R.string.drawer_settings)
.withIdentifier(6)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_settings))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_feedback)
.withIdentifier(7)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_headset_mic))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_pro)
.withIdentifier(8)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_security))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_logout)
.withIdentifier(9)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_power_settings_new))
.withTag("Bullhorn")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
navigateDrawerItem((int)drawerItem.getIdentifier(), drawerItem);
return true;
}
})
.addStickyDrawerItems(
new SecondaryDrawerItem().withName(R.string.drawer_all_right_reserved).withIcon(FontAwesome.Icon.faw_copyright).withEnabled(false)
).build();
}
/**
* Used to navigate to drawer fragment items
*/
public void navigateDrawerItem(int ItemId, IDrawerItem drawerItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(ItemId) {
case 1:
fragmentClass = ServicesFragment.class;
break;
case 2:
fragmentClass = ProductsFragment.class;
break;
case 3:
fragmentClass = PhotosFragment.class;
break;
case 4:
fragmentClass = PoemsFragment.class;
break;
case 5:
fragmentClass = ArchivesFragment.class;
break;
case 6:
fragmentClass = SettingsFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
result.closeDrawer();
}
/*
private void setUserDetails(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName("Jsk Zack")
.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
.build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Log.d(TAG, "onComplete: User Profile updated");
getUserDetails();
}
}
});
}
}
*/
private void getUserDetails(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
String properties =
"uid: " + uid + "\n" +
"name: " + name + "\n" +
"email: " + email + "\n" +
"photoUrl: " + photoUrl;
Log.d(TAG, "getUserDetails: properties: \n" + properties);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
outState = result.saveInstanceState(outState);
//add the values which need to be saved from the accountHeader to the bundle
outState = headerResult.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
}
/**
* Display progressbar
*/
public void showProgress() {
findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
}
/**
* Hide progressbar
*/
public void hideProgress() {
if(mProgressBar.getVisibility() == View.VISIBLE){
findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
}
}
/**
* Used to relaunch the application
*/
public void restartApp() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
I don't know why this is not working, am I doing something wrong?
I think its because of this lines of code
findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
Just instantiate your Progressbar in your main Activity onCreate(){HERE} and use mProgressBar in the Hide and Show functions
public void showProgress() {
mProgressBar .setVisibility(View.VISIBLE);
}
I Hope this helps ;)
I have nine activities. For example, Activity "A" is the main. The user opens from the NavigationDrawer the Activity "B", "ะก", "D" and in "D" he clicks on the "back" button. In this case, need to return to Activity "A" and not pass through the entire stack of recently opened activities.
This code does what I need:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Handler mHandler = new Handler();
drawerLayout.closeDrawers();
switch (item.getItemId()) {
case R.id.A:
if (item.isChecked()) {
break;
} else {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
intent = new Intent(activity, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
activity.startActivity(intent);
}
}, 250);
}
break;
case R.id.B:
if (item.isChecked()) {
break;
} else {
if (activity instanceof A) {
userFlavorsMap.clear();
if (flavorContainer.getChildCount() > 0){
flavorContainer.removeAllViews();
}
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
intent = new Intent(activity, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
activity.startActivity(intent);
}
}, 250);
}
break;
case R.id.C:
if (item.isChecked()) {
break;
} else {
if (activity instanceof A) {
userFlavorsMap.clear();
if (flavorContainer.getChildCount() > 0){
flavorContainer.removeAllViews();
}
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
intent = new Intent(activity, C.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
activity.startActivity(intent);
}
}, 250);
}
break;
case R.id.D:
if (item.isChecked()) {
break;
} else {
if (activity instanceof A) {
userFlavorsMap.clear();
if (flavorContainer.getChildCount() > 0){
flavorContainer.removeAllViews();
}
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
intent = new Intent(activity, D.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
activity.startActivity(intent);
}
}, 250);
}
break;
case R.id.E:
if (item.isChecked()) {
break;
} else {
if (activity instanceof A) {
userFlavorsMap.clear();
if (flavorContainer.getChildCount() > 0){
flavorContainer.removeAllViews();
}
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
intent = new Intent(activity, E.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
activity.startActivity(intent);
}
}, 250);
}
break;
case R.id.F:
File usersCounter = new File("data/data/com.com.com/shared_prefs/file.xml");
if (usersCounter.exists()) {
if (item.isChecked()) {
break;
} else {
if (activity instanceof A) {
userFlavorsMap.clear();
if (flavorContainer.getChildCount() > 0){
flavorContainer.removeAllViews();
}
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
intent = new Intent(activity, F.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
activity.startActivity(intent);
}
}, 250);
}
break;
} else {
if (item.isChecked()) {
break;
} else {
if (activity instanceof A) {
userFlavorsMap.clear();
if (flavorContainer.getChildCount() > 0){
flavorContainer.removeAllViews();
}
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
intent = new Intent(activity, G.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
activity.startActivity(intent);
}
}, 250);
}
break;
}
}
return false;
}
But, if user switched to Activity, for example, "C" and folded the application, then after return to app will open "A". How can I complete the code so that when I return to the application, it open the last opened Activity, but all the recent activities are not going to be in the stack?
In manifect android:launchMode="singleTop"
try this in each activity except MainActivity
#Override
public void onBackPressed() {
super.onBackPressed();
Intent mainIntent = new Intent(YourCurrentActivityName.this,MainActivity.class);
startActivity(mainIntent);
finish();
}
I'm making a custom dialer and everything till now was perfect. Now while testing, I saw that the "#" sign was not working properly. It shows on the dialer but while calling, it goes away. For eg, if I dial *121#, it becomes *121 when the call is being made through the stock dialer. Here is the code for my activity-
public class DialPadActivity extends Activity {
private EditText numberField = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeButtonArrowClickListeners();
}
public void dialButtonClick(View v) {
int buttonId = v.getId();
putNumberToEditText(buttonId);
}
public void buttonPhone_click(View v) {
if (numberField != null) {
String phone = numberField.getText().toString();
String uriString = "tel:" + phone;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uriString));
startActivity(intent);
}
}
public void putNumberToEditText(int buttonId) {
switch (buttonId) {
case R.id.dial_button0:
putNumber("0");
break;
case R.id.dial_button1:
putNumber("1");
break;
case R.id.dial_button2:
putNumber("2");
break;
case R.id.dial_button3:
putNumber("3");
break;
case R.id.dial_button4:
putNumber("4");
break;
case R.id.dial_button5:
putNumber("5");
break;
case R.id.dial_button6:
putNumber("6");
break;
case R.id.dial_button7:
putNumber("7");
break;
case R.id.dial_button8:
putNumber("8");
break;
case R.id.dial_button9:
putNumber("9");
break;
case R.id.dial_button_s:
putNumber("*");
break;
case R.id.dial_button_p:
putNumber("#");
break;
}
}
public void putNumber(String number) {
if (numberField == null) {
numberField = (EditText) findViewById(R.id.phone_number_field);
}
numberField.append(number);
}
private void initializeButtonArrowClickListeners() {
ImageButton buttonArrow = (ImageButton) findViewById(R.id.button_arrow);
buttonArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (numberField != null && numberField.length() > 0) {
String previousNumbers = numberField.getText().toString();
String numbersMinusTheLast = previousNumbers.substring(0,
numberField.length() - 1);
numberField.setText(numbersMinusTheLast);
}
}
});
buttonArrow.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (numberField != null) {
numberField.setText("");
}
return false;
}
});
}
Where am I doing the wrong?
Use URLEncoder.encode(string, "UTF-8");
For example:
String uriString = "tel:" + URLEncoder.encode(phone, "UTF-8");
Replace your # symbol with %23.
That is: *121%2311 instead of *121#11
String uri = "tel:" + "*6133%235345";
Intent intent;
intent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(intent);
the output for this is : *6133#5345