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!
Related
I am a newbie in the developing section, recently I'm trying to edit the source code of the web view application. But the problem is every time of "backpress" interstitial ad appears. Which is huge disturbing. Tried to change back press code but after doing that ads totally diseapred. Now I'm confused that how can I solve this problem. Because if a web view app show ads every back press, probably google will not approve it on play store even if accepts then people will not use this app.
I've tried to limit but cannot understand, please help me.
If this is possible the ad shows only one time of back press or at least a limited backpress.
Thanks in advance <3 <3
mainactivity.java
//Views
public Toolbar mToolbar;
public View mHeaderView;
public TabLayout mSlidingTabLayout;
public SwipeableViewPager mViewPager;
//App Navigation Structure
private NavigationAdapter mAdapter;
private NavigationView navigationView;
private SimpleMenu menu;
private WebFragment CurrentAnimatingFragment = null;
private int CurrentAnimation = 0;
//Identify toolbar state
private static int NO = 0;
private static int HIDING = 1;
private static int SHOWING = 2;
//Keep track of the interstitials we show
private int interstitialCount = -1;
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeUtils.setTheme(this);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mHeaderView = (View) findViewById(R.id.header_container);
mSlidingTabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (SwipeableViewPager) findViewById(R.id.pager);
setSupportActionBar(mToolbar);
mAdapter = new NavigationAdapter(getSupportFragmentManager(), this);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
String data = intent.getDataString();
((App) getApplication()).setPushUrl(data);
}
//Hiding ActionBar/Toolbar
if (Config.HIDE_ACTIONBAR)
getSupportActionBar().hide();
if (getHideTabs())
mSlidingTabLayout.setVisibility(View.GONE);
hasPermissionToDo(this, Config.PERMISSIONS_REQUIRED);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
if ((Config.HIDE_ACTIONBAR && getHideTabs()) || ((Config.HIDE_ACTIONBAR || getHideTabs()) && getCollapsingActionBar())){
lp.topMargin = 0;
} else if ((Config.HIDE_ACTIONBAR || getHideTabs()) || (!Config.HIDE_ACTIONBAR && !getHideTabs() && getCollapsingActionBar())){
lp.topMargin = getActionBarHeight();
} else if (!Config.HIDE_ACTIONBAR && !getHideTabs()){
lp.topMargin = getActionBarHeight() * 2;
}
mViewPager.setLayoutParams(lp);
//Tabs
mViewPager.setAdapter(mAdapter);
mViewPager.setOffscreenPageLimit(mViewPager.getAdapter().getCount() - 1);
mSlidingTabLayout.setupWithViewPager(mViewPager);
mSlidingTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (getCollapsingActionBar()) {
showToolbar(getFragment());
}
mViewPager.setCurrentItem(tab.getPosition());
showInterstitial();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
for (int i = 0; i < mSlidingTabLayout.getTabCount(); i++) {
if (Config.ICONS.length > i && Config.ICONS[i] != 0) {
mSlidingTabLayout.getTabAt(i).setIcon(Config.ICONS[i]);
}
}
//Drawer
if (Config.USE_DRAWER) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DrawerLayout drawer = ((DrawerLayout) findViewById(R.id.drawer_layout));
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, 0, 0);
drawer.addDrawerListener(toggle);
toggle.syncState();
//Menu items
navigationView = (NavigationView) findViewById(R.id.nav_view);
menu = new SimpleMenu(navigationView.getMenu(), this);
configureMenu(menu);
if (Config.HIDE_DRAWER_HEADER) {
navigationView.getHeaderView(0).setVisibility(View.GONE);
navigationView.setFitsSystemWindows(false);
} else {
if (Config.DRAWER_ICON != R.mipmap.ic_launcher)
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.drawer_icon)).setImageResource(Config.DRAWER_ICON);
else {
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.launcher_icon)).setVisibility(View.VISIBLE);
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.drawer_icon)).setVisibility(View.INVISIBLE);
}
}
} else {
((DrawerLayout) findViewById(R.id.drawer_layout)).setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//Admob
if (!getResources().getString(R.string.ad_banner_id).equals("")) {
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
adView.loadAd(adRequest);
} else {
AdView adView = (AdView) findViewById(R.id.adView);
adView.setVisibility(View.GONE);
}
if (getResources().getString(R.string.ad_interstitial_id).length() > 0 && Config.INTERSTITIAL_INTERVAL > 0){
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ad_interstitial_id));
AdRequest adRequestInter = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
mInterstitialAd.loadAd(adRequestInter);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build());
}
});
}
//Application rating
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.rate_title))
.setMessage(String.format(getString(R.string.rate_message), getString(R.string.app_name)))
.setPositiveButton(getString(R.string.rate_yes), null)
.setNegativeButton(getString(R.string.rate_never), null)
.setNeutralButton(getString(R.string.rate_later), null);
new AppRate(this)
.setShowIfAppHasCrashed(false)
.setMinDaysUntilPrompt(2)
.setMinLaunchesUntilPrompt(2)
.setCustomDialog(builder)
.init();
//Showing the splash screen
if (Config.SPLASH) {
findViewById(R.id.imageLoading1).setVisibility(View.VISIBLE);
//getFragment().browser.setVisibility(View.GONE);
}
//Toolbar styling
if (Config.TOOLBAR_ICON != 0) {
getSupportActionBar().setTitle("");
ImageView imageView = findViewById(R.id.toolbar_icon);
imageView.setImageResource(Config.TOOLBAR_ICON);
imageView.setVisibility(View.VISIBLE);
if (!Config.USE_DRAWER){
imageView.setScaleType(ImageView.ScaleType.FIT_START);
}
}
}
// using the back button of the device
#Override
public void onBackPressed() {
View customView = null;
WebChromeClient.CustomViewCallback customViewCallback = null;
if (getFragment().chromeClient != null) {
customView = getFragment().chromeClient.getCustomView();
customViewCallback = getFragment().chromeClient.getCustomViewCallback();
}
if ((customView == null)
&& getFragment().browser.canGoBack()) {
getFragment().browser.goBack();
} else if (customView != null
&& customViewCallback != null) {
customViewCallback.onCustomViewHidden();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
//Adjust menu item visibility/availability based on settings
if (Config.HIDE_MENU_SHARE) {
menu.findItem(R.id.share).setVisible(false);
}
if (Config.HIDE_MENU_HOME) {
menu.findItem(R.id.home).setVisible(false);
}
if (Config.HIDE_MENU_NAVIGATION){
menu.findItem(R.id.previous).setVisible(false);
menu.findItem(R.id.next).setVisible(false);
}
if (!Config.SHOW_NOTIFICATION_SETTINGS || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
menu.findItem(R.id.notification_settings).setVisible(false);
}
ThemeUtils.tintAllIcons(menu, this);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
WebView browser = getFragment().browser;
if (item.getItemId() == (R.id.next)) {
browser.goForward();
return true;
} else if (item.getItemId() == R.id.previous) {
browser.goBack();
return true;
} else if (item.getItemId() == R.id.share) {
getFragment().shareURL();
return true;
} else if (item.getItemId() == R.id.about) {
AboutDialog();
return true;
} else if (item.getItemId() == R.id.home) {
browser.loadUrl(getFragment().mainUrl);
return true;
} else if (item.getItemId() == R.id.close) {
finish();
Toast.makeText(getApplicationContext(),
getText(R.string.exit_message), Toast.LENGTH_SHORT).show();
return true;
} else if (item.getItemId() == R.id.notification_settings){
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
/**
* Showing the About Dialog
*/
private void AboutDialog() {
// setting the dialogs text, and making the links clickable
final TextView message = new TextView(this);
// i.e.: R.string.dialog_message =>
final SpannableString s = new SpannableString(
this.getText(R.string.dialog_about));
Linkify.addLinks(s, Linkify.WEB_URLS);
message.setTextSize(15f);
int padding = Math.round(20 * getResources().getDisplayMetrics().density);
message.setPadding(padding, 15, padding, 15);
message.setText(Html.fromHtml(getString(R.string.dialog_about)));
message.setMovementMethod(LinkMovementMethod.getInstance());
// creating the actual dialog
AlertDialog.Builder AlertDialog = new AlertDialog.Builder(this);
AlertDialog.setTitle(Html.fromHtml(getString(R.string.about)))
// .setTitle(R.string.about)
.setCancelable(true)
// .setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton("ok", null).setView(message).create().show();
}
/**
* Set the ActionBar Title
* #param title title
*/
public void setTitle(String title) {
if (mAdapter != null && mAdapter.getCount() == 1 && !Config.USE_DRAWER && !Config.STATIC_TOOLBAR_TITLE)
getSupportActionBar().setTitle(title);
}
/**
* #return the Current WebFragment
*/
public WebFragment getFragment(){
return (WebFragment) mAdapter.getCurrentFragment();
}
/**
* Hide the Splash Screen
*/
public void hideSplash() {
if (Config.SPLASH) {
if (findViewById(R.id.imageLoading1).getVisibility() == View.VISIBLE) {
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
public void run() {
// hide splash image
findViewById(R.id.imageLoading1).setVisibility(
View.GONE);
}
// set a delay before splashscreen is hidden
}, Config.SPLASH_SCREEN_DELAY);
}
}
}
/**
* Hide the toolbar
*/
public void hideToolbar() {
if (CurrentAnimation != HIDING) {
CurrentAnimation = HIDING;
AnimatorSet animSetXY = new AnimatorSet();
ObjectAnimator animY = ObjectAnimator.ofFloat(getFragment().rl, "y", 0);
ObjectAnimator animY1 = ObjectAnimator.ofFloat(mHeaderView, "y", -getActionBarHeight());
animSetXY.playTogether(animY, animY1);
animSetXY.start();
animSetXY.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
CurrentAnimation = NO;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
/**
* Show the toolbar
* #param fragment for which to show the toolbar
*/
public void showToolbar(WebFragment fragment) {
if (CurrentAnimation != SHOWING || fragment != CurrentAnimatingFragment) {
CurrentAnimation = SHOWING;
CurrentAnimatingFragment = fragment;
AnimatorSet animSetXY = new AnimatorSet();
ObjectAnimator animY = ObjectAnimator.ofFloat(fragment.rl, "y", getActionBarHeight());
ObjectAnimator animY1 = ObjectAnimator.ofFloat(mHeaderView, "y", 0);
animSetXY.playTogether(animY, animY1);
animSetXY.start();
animSetXY.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
CurrentAnimation = NO;
CurrentAnimatingFragment = null;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
public int getActionBarHeight() {
int mHeight = mToolbar.getHeight();
//Just in case we get a unreliable result, get it from metrics
if (mHeight == 0){
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
mHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
}
return mHeight;
}
boolean getHideTabs(){
if (mAdapter.getCount() == 1 || Config.USE_DRAWER){
return true;
} else {
return Config.HIDE_TABS;
}
}
public static boolean getCollapsingActionBar(){
if (Config.COLLAPSING_ACTIONBAR && !Config.HIDE_ACTIONBAR){
return true;
} else {
return false;
}
}
/**
* Check permissions on app start
* #param context
* #param permissions Permissions to check
* #return if the permissions are available
*/
private static boolean hasPermissionToDo(final Activity context, final String[] permissions) {
boolean oneDenied = false;
for (String permission : permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ContextCompat.checkSelfPermission(context, permission)
!= PackageManager.PERMISSION_GRANTED)
oneDenied = true;
}
if (!oneDenied) return true;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.common_permission_explaination);
builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
context.requestPermissions(permissions,1);
}
});
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
/**
* Show an interstitial ad
*/
public void showInterstitial(){
if (interstitialCount == (Config.INTERSTITIAL_INTERVAL - 1)) {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
interstitialCount = 0;
} else {
interstitialCount++;
}
}
/**
* Configure the navigationView
* #param menu to modify
*/
public void configureMenu(SimpleMenu menu){
for (int i = 0; i < Config.TITLES.length; i++) {
//The title
String title = null;
Object titleObj = Config.TITLES[i];
if (titleObj instanceof Integer && !titleObj.equals(0)) {
title = getResources().getString((int) titleObj);
} else {
title = (String) titleObj;
}
//The icon
int icon = 0;
if (Config.ICONS.length > i)
icon = Config.ICONS[i];
menu.add((String) Config.TITLES[i], icon, new Action(title, Config.URLS[i]));
}
menuItemClicked(menu.getFirstMenuItem().getValue(), menu.getFirstMenuItem().getKey());
}
#Override
public void menuItemClicked(Action action, MenuItem item) {
if (WebToAppWebClient.urlShouldOpenExternally(action.url)){
//Load url outside WebView
try {
startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url)));
} catch(ActivityNotFoundException e) {
if (action.url.startsWith("intent://")) {
startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url.replace("intent://", "http://"))));
} else {
Toast.makeText(this, getResources().getString(R.string.no_app_message), Toast.LENGTH_LONG).show();
}
}
} else {
//Uncheck all other items, check the current item
for (MenuItem menuItem : menu.getMenuItems())
menuItem.setChecked(false);
item.setChecked(true);
//Close the drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
//Load the url
if (getFragment() == null) return;
getFragment().browser.loadUrl("about:blank");
getFragment().setBaseUrl(action.url);
//Show intersitial if applicable
showInterstitial();
Log.v("INFO", "Drawer Item Selected");
}
}
}
This is not comprehensive solution for sure, but I just implement these kind of features for my own app.
If you just want to limit the frequency of the ads showing, in AdMob, you can set limit how often per time unit the add can be shown. AdMob help for setting frequency capping
Another way of limiting the ads could be achieved using probability.
Add proper probability value for your case like this to make ad to shown only every once in a while:
private void showInterstitial(Boolean AdsEnabled) {
final int random = new Random().nextInt(101);
if(random > 95 && AdsEnabled){
if (mInterstitialAd != null && mInterstitialAd.isLoaded() ) {
mInterstitialAd.show();
Log.i("ads","Interstiade ad shown");
} else {
//Do something else
Log.i("ads","Interstiade ad was not loaded");
}
}
}
You can tune your ads to show up more natural using both of these features.
And for why you don't see any ads right now. I might be too beginner my self too, to see why this is the case. But I would add this kind of loader for each backspace press to make sure the ad is loaded. At least I have seen, that sometimes ads fails to load, and this works for me. I have this piece of code used every time I try to show the add.
if (!mInterstitialAd.isLoading() && !mInterstitialAd.isLoaded()) {
Log.i("ads", "Loading new add, because there was no ad ready");
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
}
It sees to me, that you load the ad when you initialise the ad, and at ad close. But if the ad fails to load at oncreate, do you have the ad close events at all to reload the ad?
I also wonder this
public void showInterstitial(){
if (interstitialCount == (Config.INTERSTITIAL_INTERVAL - 1)) {
this shows the ad only when these values are equal. So are you sure that Config.INTERSTITIAL_INTERVAL is at least 1? I think you should change "==" to ">=" to make sure you show the ads even if the INTERSTITIAL_INTERVAL is zero or negative. Or get rid of the minus 1 and keep Config.INTERSTITIAL_INTERVAL positive integer. You have interstitialCount initialised -1 at beginning so this should so the first ad one click later than the next ads, but again, I'm not sure why the ads are not shown right now.
I hope these answers helped you. But as I said, I'm still beginner my self.
-Jussi
I use tablayout and viewpager to display 2 feature, first tab there's a button to check either the serial number in barcode is valid or not then if the number is also valid it will execute top up process and the second tab is just to check if the serial number is already used or not. The problem is, when the activity is running and I click nothing but the scanner from second tab is always scanning if there is a barcode close to the camera
I try to add condition when second tab is clicked then I execute what's in second tab process do it is checking either serial number is valid or not but it doesn't work.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
mScannerView = new ZXingScannerView(getActivity());
viewModel = ViewModelProviders.of(getActivity()).get(VmRegistrasiSp.class);
if(state != null) {
mFlash = state.getBoolean(FLASH_STATE, false);
mAutoFocus = state.getBoolean(AUTO_FOCUS_STATE, true);
mSelectedIndices = state.getIntegerArrayList(SELECTED_FORMATS);
mCameraId = state.getInt(CAMERA_ID, -1);
statusCam = false;
} else {
mFlash = false;
mAutoFocus = true;
mSelectedIndices = null;
mCameraId = -1;
statusCam = true;
}
setupFormats();
return mScannerView;
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuItem menuItem;
if(mFlash) {
menuItem = menu.add(Menu.NONE, R.id.menu_flash, 0, R.string.flash_on);
} else {
menuItem = menu.add(Menu.NONE, R.id.menu_flash, 0, R.string.flash_off);
}
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_NEVER);
if(mAutoFocus) {
menuItem = menu.add(Menu.NONE, R.id.menu_auto_focus, 0, R.string.auto_focus_on);
} else {
menuItem = menu.add(Menu.NONE, R.id.menu_auto_focus, 0, R.string.auto_focus_off);
}
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_NEVER);
menuItem = menu.add(Menu.NONE, R.id.menu_formats, 0, R.string.formats);
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_NEVER);
menuItem = menu.add(Menu.NONE, R.id.menu_camera_selector, 0, R.string.select_camera);
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_NEVER);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.menu_flash:
mFlash = !mFlash;
if(mFlash) {
item.setTitle(R.string.flash_on);
} else {
item.setTitle(R.string.flash_off);
}
mScannerView.setFlash(mFlash);
return true;
case R.id.menu_auto_focus:
mAutoFocus = !mAutoFocus;
if(mAutoFocus) {
item.setTitle(R.string.auto_focus_on);
} else {
item.setTitle(R.string.auto_focus_off);
}
mScannerView.setAutoFocus(mAutoFocus);
return true;
case R.id.menu_formats:
DialogFragment fragment = FormatSelectorDialogFragment.newInstance(this, mSelectedIndices);
fragment.show(getActivity().getSupportFragmentManager(), "format_selector");
return true;
case R.id.menu_camera_selector:
mScannerView.stopCamera();
DialogFragment cFragment = CameraSelectorDialogFragment.newInstance(this, mCameraId);
cFragment.show(getActivity().getSupportFragmentManager(), "camera_selector");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(FLASH_STATE, mFlash);
outState.putBoolean(AUTO_FOCUS_STATE, mAutoFocus);
outState.putIntegerArrayList(SELECTED_FORMATS, mSelectedIndices);
outState.putInt(CAMERA_ID, mCameraId);
}
#Override
public void handleResult(Result rawResult) {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(Objects.requireNonNull(getActivity()).getApplicationContext(), notification);
r.play();
} catch (Exception ignored) {}
Intent sendData = new Intent(getActivity(), ActRegistrasVoucher.class);
sendData.putExtra("dataBarcodeCheck",rawResult.getText());
sendData.putExtra("flagPager", 2);
startActivity(sendData);
Objects.requireNonNull(getActivity()).finish();
}
public void closeMessageDialog() {
closeDialog("scan_results");
}
public void closeFormatsDialog() {
closeDialog("format_selector");
}
public void closeDialog(String dialogName) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
DialogFragment fragment = (DialogFragment) fragmentManager.findFragmentByTag(dialogName);
if(fragment != null) {
fragment.dismiss();
}
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
// Resume the camera
mScannerView.resumeCameraPreview(this);
}
#Override
public void onFormatsSaved(ArrayList<Integer> selectedIndices) {
mSelectedIndices = selectedIndices;
setupFormats();
}
#Override
public void onCameraSelected(int cameraId) {
mCameraId = cameraId;
mScannerView.startCamera(mCameraId);
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
}
public void setupFormats() {
if(statusCam){
mScannerView.stopCamera();
}else {
List<BarcodeFormat> formats = new ArrayList<BarcodeFormat>();
if (mSelectedIndices == null || mSelectedIndices.isEmpty()) {
mSelectedIndices = new ArrayList<Integer>();
for (int i = 0; i < ZXingScannerView.ALL_FORMATS.size(); i++) {
mSelectedIndices.add(i);
}
}
for (int index : mSelectedIndices) {
formats.add(ZXingScannerView.ALL_FORMATS.get(index));
}
if (mScannerView != null) {
mScannerView.setFormats(formats);
}
}
}
There is no error messages but the process doesn't resulting desired output. I expect that barcode scanner in second tab only work when the tab is active
Realm class
public class RealmManager
private static Realm mRealm;
public static Realm open() {
mRealm = Realm.getDefaultInstance();
return mRealm;
}
public static void close() {
if (mRealm != null) {
mRealm.close();
}
}
public static RecordsDao recordsDao() {
checkForOpenRealm();
return new RecordsDao(mRealm);
}
private static void checkForOpenRealm() {
if (mRealm == null || mRealm.isClosed()) {
throw new IllegalStateException("RealmManager: Realm is closed, call open() method first");
}
}
}
When I call RealmManager.open(); my app crashes with error
Unable to open a realm at path
'/data/data/com.apphoctienganhpro.firstapp/files/default.realm':
Unsupported Realm file format version. in
/Users/cm/Realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_SharedRealm.cpp
line 92 Kind: ACCESS_ERROR
Activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
ButterKnife.bind(this);
RealmManager.open();
NestedScrollView scrollView = findViewById(R.id.nest_scrollview);
scrollView.setFillViewport(true);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = findViewById(R.id.appbar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = true;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
isShow = true;
} else if (isShow) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
isShow = false;
}
}
});
arrayListCategory = Utility.getAppcon().getSession().arrayListCategory;
arrayListGoal = Utility.getAppcon().getSession().arrayListGoal;
arrayList = new ArrayList<>();
arrayList = Utility.getAppcon().getSession().arrayListCategory;
if (arrayListGoal.size() > 0) {
goal_id = arrayListGoal.get(0).getSingleGoalId();
}else{
if(!arrayList.get(0).getCategory_description().equals("")) {
if(!Utility.getAppcon().getSession().screen_name.equals("lessson_complete")) {
displayDialog();
}
}
}
collapsingToolbarLayout.setTitle(arrayListCategory.get(0).getCategoryName());
layoutManager = new LinearLayoutManager(this);
recycler_view.setLayoutManager(layoutManager);
apiservice = ApiServiceCreator.createService("latest");
sessionManager = new SessionManager(this);
getCategoryLesson();
}
private void displayDialog() {
dialog = new Dialog(LessonActivity.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_detail);
dialog.setCancelable(true);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_main_d = dialog.findViewById(R.id.img_main_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
img_play_d.setVisibility(View.GONE);
Picasso.with(LessonActivity.this).load(ApiConstants.IMAGE_URL + arrayList.get(0).getCategoryImage())
.noFade()
.fit()
.placeholder(R.drawable.icon_no_image)
.into(img_main_d);
txt_title_d.setText(arrayList.get(0).getCategoryName());
txt_description_d.setText(Html.fromHtml(arrayList.get(0).getCategory_description().replaceAll("\\\\", "")));
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_close.setOnClickListener(view -> dialog.dismiss());
}
private void getCategoryLesson() {
pDialog = new ProgressDialog(LessonActivity.this);
pDialog.setTitle("Checking Data");
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Observable<LessonResponse> responseObservable = apiservice.getCategoryLesson(
sessionManager.getKeyEmail(),
arrayListCategory.get(0).getCategoryId(),
goal_id,
sessionManager.getUserData().get(0).getUserId(),
sessionManager.getKeyToken());
responseObservable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(throwable -> {
if (throwable instanceof retrofit2.HttpException) {
retrofit2.HttpException ex = (retrofit2.HttpException) throwable;
Log.e("error", ex.getLocalizedMessage());
}
return Observable.empty();
})
.subscribe(new Observer<LessonResponse>() {
#Override
public void onCompleted() {
pDialog.dismiss();
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(LessonResponse lessonResponse) {
if (lessonResponse.getData().size() > 9) {
txt_total_lesson.setText(String.valueOf(lessonResponse.getData().size()));
} else {
txt_total_lesson.setText(String.valueOf("0" + lessonResponse.getData().size()));
}
if (lessonResponse.getStatusCode() == 200) {
adapter = new LessonAdapter(lessonResponse.getData(), LessonActivity.this);
recycler_view.setAdapter(adapter);
} else {
Utility.displayToast(getApplicationContext(), lessonResponse.getMessage());
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onClickFavButton(int position, boolean toggle) {
}
public boolean isFavourate(String LessionId,String UserId){
if (arrayList!=null){
for (int i=0;i<arrayList.size();i++)
if (favarrayList.get(1).getLessonId().equals(LessionId) && favarrayList.get(0).getUserID().equals(UserId)){
return true;
}
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
RealmManager.close();
}
}
Adapter Class
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_lesson, parent, false);
return new LessonAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
dialog = new Dialog(context);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_audio);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
frm_header = dialog.findViewById(R.id.frm_header);
img_back_d = dialog.findViewById(R.id.img_back_d);
holder.txt_lesson_title.setText(arrayList.get(position).getLessonName());
holder.btn_view.setOnClickListener(view -> {
txt_title_d.setText(arrayList.get(position).getLessonName());
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_description_d.setText(Html.fromHtml(arrayList.get(position).getLessonDescription().replaceAll("\\\\", "")));
displayDialog(holder.getAdapterPosition());
});
holder.btn_go.setOnClickListener(view -> {
Utility.getAppcon().getSession().arrayListLesson = new ArrayList<>();
Utility.getAppcon().getSession().arrayListLesson.add(arrayList.get(position));
Intent intent = new Intent(context, LessonCompleteActivity.class);
context.startActivity(intent);
});
if (arrayList.get(position).isFavourate())
holder.favCheck.setChecked(true);
else
holder.favCheck.setChecked(false);
holder.favCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
if (checkBox.isChecked()) {
RealmManager.recordsDao().saveToFavorites(arrayList.get(position));
} else {
RealmManager.recordsDao().removeFromFavorites(arrayList.get(position));
}
}
});
}
private void displayDialog(int Position) {
final MediaPlayer mediaPlayer = new MediaPlayer();
String url = ApiConstants.IMAGE_URL + arrayList.get(Position).getLesson_audio_url();
//String url = "http://208.91.198.96/~diestechnologyco/apphoctienganhpro/uploads/mp3/mp3_1.mp3"; // your URL here
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare(); // might take long! (for buffering, etc)
} catch (IOException e) {
e.printStackTrace();
}
img_play_d.setOnClickListener(view -> {
if (audio_flag == 0) {
mediaPlayer.start();
audio_flag = 1;
img_play_d.setImageResource(R.mipmap.pause_circle);
} else {
mediaPlayer.pause();
audio_flag = 0;
img_play_d.setImageResource(R.mipmap.icon_play);
}
});
//img_play_d.setOnClickListener(view -> mediaPlayer.start());
txt_close.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
img_back_d.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.txt_lesson_title)
TextView txt_lesson_title;
#BindView(R.id.txt_lesson_type)
TextView txt_lesson_type;
#BindView(R.id.btn_view)
Button btn_view;
#BindView(R.id.btn_go)
Button btn_go;
#BindView(R.id.image_favborder)
CheckBox favCheck;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
//RealmManager.open();
}
}
public void getdata(){
}
public void addFavourate(String LessonId,String UserId) {
if (mRealm != null) {
mRealm.beginTransaction();
favList_model = mRealm.createObject(FavList_model.class);
favList_model.setLessonId(LessonId);
favList_model.setUserID(UserId);
mRealm.commitTransaction();
mRealm.close();
}
}
}
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 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.