How can I limit interstitial ad opening? - java

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

Related

why this code isn't working in real-time pleace cheack this code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
this code isn't working in real-time.. it works only whenever I restart/refresh the app. I am using Cloud Firestore. plzz change code am noob help me. & sorry For My bad English
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Category_List_Activity extends BaseActivity {
List<CardModel> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerAdapter adapter;
android.app.AlertDialog dialog;
private static final String TAG = "CategoryListActivity";
FirebaseFirestore db;
String name, id,node,lastid,time;
boolean islast;
SessionManager sessionManager;
LinearLayout banner;
private InterstitialAd interstitial;
TextView settitel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
FirebaseApp.initializeApp(this);
db = FirebaseFirestore.getInstance();
Bundle bundle = getIntent().getExtras();
banner = findViewById(R.id.banner_bottom_main);
sessionManager=new SessionManager(this);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
StartAppAd.showAd(this);
new AdsHelper().createBanner(this, banner, sessionManager.getBanner());
if (bundle != null) {
name = bundle.getString("name");
id = bundle.getString("id");
lastid = bundle.getString("lastid");
node=bundle.getString("node");
islast=bundle.getBoolean("islast");
}
///////////////////////////Action bar custiom//////////////////////////////////////////
ImageView imgFavorite = (ImageView) findViewById(R.id.previous);
imgFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
ImageView imgFavorsite = (ImageView) findViewById(R.id.refrashing);
imgFavorsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getData();
}
});
settitel = findViewById(R.id.event_name);
settitel.setText(name);
///////////////////////Action bar custiom end///////////////////////
recyclerView = findViewById(R.id.rec);
adapter = new RecyclerAdapter(list, this);
recyclerView.setHasFixedSize(true);
AutoFitGridLayoutManager layoutManager = new AutoFitGridLayoutManager(this, 10000);
recyclerView.setLayoutManager(layoutManager);
// recyclerView.setLayoutManager(new GridLayoutManager(this,1));
recyclerView.setAdapter(adapter);
getData();
if(isCastApiAvailable()) {
castContext = CastContext.getSharedInstance(this);
if (castContext.getCastState() == CastState.CONNECTED) {
findViewById(R.id.castMiniController).setVisibility(View.VISIBLE);
}else{
findViewById(R.id.castMiniController).setVisibility(View.GONE);
}
}else{
findViewById(R.id.castMiniController).setVisibility(View.GONE);
}
}
CastContext castContext;
#Override
protected void onResume() {
super.onResume();
try {
if (HelperClass.vpn(this)) {
finish();
}
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(#NonNull Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.refrish){
getData();
return true;
}
else if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
// #Override
// public boolean onOptionsItemSelected(MenuItem item) {
//
// if (item.getItemId() == android.R.id.home) {
// onBackPressed();
// }
//
// return true;
// }
//////////////////sports diglo start///////////////
#Override
public void onDestroy() {
dismissProgressDialog();
super.onDestroy();
}
private void showProgressDialog() {
if (dialog == null) {
dialog = new SpotsDialog.Builder().setContext(this).build();
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
}
dialog.show();
}
private void dismissProgressDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
//////////////////sports diglo end///////////////
private void getData() {
showProgressDialog();
Query query;
if (islast) {
query = db.collection(node)
.document(lastid)
.collection("list")
.document(id)
.collection("list");
} else {
query = db.collection(node)
.document(id)
.collection("list");
}
query.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
dismissProgressDialog();
if (task.isSuccessful()) {
list.clear();
int i = 0;
boolean match = false;
try {
for (DocumentSnapshot snapshot : task.getResult().getDocuments()) {
CardModel mainModel = snapshot.toObject(CardModel.class);
mainModel.setId(snapshot.getId());
if (mainModel.enable) {
boolean onOff=mainModel.cOnOff;
if (mainModel.countries != null
&& mainModel.countries.size() > 0) {
if (!sessionManager.getLocation().isEmpty()) {
if(onOff) {
if (mainModel.countries.contains(sessionManager.getLocation())) {
match = true;
list.add(mainModel);
} else {
list.remove(mainModel);
}
}else{
if (mainModel.countries.contains(sessionManager.getLocation())) {
match = true;
list.remove(mainModel);
} else {
list.add(mainModel);
}
}
} else {
list.add(mainModel);
}
} else {
list.add(mainModel);
}
} else {
list.remove(mainModel);
}
Log.d("view imgs", "data is " + mainModel.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
adapter.notifyDataSetChanged();
dismissProgressDialog();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
dismissProgressDialog();
Toast.makeText(Category_List_Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
;
}
}

Android could not lock surface when puting shared preferences

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!

facing nulls for no reason in android studio [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am facing 2 nulls in my app when I try to use some buttons in it . I have checking and reviewing my codes for 3 days till now but I can not solve the null
logCat shows me that the
null is at ".Question.getCorrectAnswer() /
QuestionFragment.showCorrectAnswer(QuestionFragment.java:175) and
QuestionActivity.onActivityResult(QuestionActivity.java:419)"
and other button shows null at
"AnswerSheetHelperAdapter.notifyDataSetChanged() / at
QuestionActivity.onActivityResult(QuestionActivity.java:436)"
But I'm sure that there are no nulls at all: I need help from expert people maybe they find something I cannot find cause I am a rookie for now.
This is my Question script:
public class ResultGridAdapter extends RecyclerView.Adapter<ResultGridAdapter.MyViewHolder> {
Context context;
List<CurrentQuestion> currentQuestionList;
public ResultGridAdapter(Context context, List<CurrentQuestion> currentQuestionList) {
this.context = context;
this.currentQuestionList = currentQuestionList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(context).inflate(R.layout.layout_result_item, viewGroup, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
Drawable img;
myViewHolder.btn_question.setText(new StringBuilder("Question").append(currentQuestionList.get(i)
.getQuestionIndex() + 1));
if (currentQuestionList.get(i).getType() == Common.ANSWER_TYPE.RIGHT_ANSWER) {
myViewHolder.btn_question.setBackgroundColor(Color.parseColor("#ff99cc00"));
img = context.getResources().getDrawable(R.drawable.ic_check_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
} else if (currentQuestionList.get(i).getType() == Common.ANSWER_TYPE.WRONG_ANSWER) {
myViewHolder.btn_question.setBackgroundColor(Color.parseColor("#ffcc0000"));
img = context.getResources().getDrawable(R.drawable.ic_clear_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
} else {
img = context.getResources().getDrawable(R.drawable.ic_error_outline_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
}
}
#Override
public int getItemCount() {
return currentQuestionList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
Button btn_question;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
btn_question = (Button) itemView.findViewById(R.id.btn_question);
btn_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LocalBroadcastManager.getInstance(context)
.sendBroadcast(new Intent(Common.KEY_BACK_FROM_RESULT).putExtra(Common.KEY_BACK_FROM_RESULT
, currentQuestionList.get(getAdapterPosition()).getQuestionIndex()));
}
});
}
}
}
This is my QuestionFragment:
public class QuestionFragment extends Fragment implements IQuestion {
TextView txt_question_text;
CheckBox ckbA, ckbB, ckbC, ckbD;
FrameLayout layout_image;
ProgressBar progressBar;
Question question;
int questionIndex = -1;
public QuestionFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View itemView = inflater.inflate(R.layout.fragment_question, container, false);
questionIndex = getArguments().getInt("index", -1);
question = Common.questionList.get(questionIndex);
if (question != null) {
layout_image = (FrameLayout) itemView.findViewById(R.id.layout_image);
progressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
if (question.isImageQuestion()) {
ImageView img_question = (ImageView) itemView.findViewById(R.id.img_question);
Picasso.get().load(question.getQuestionImage()).into(img_question, new Callback() {
#Override
public void onSuccess() {
progressBar.setVisibility(View.GONE);
}
#Override
public void onError(Exception e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else
layout_image.setVisibility(View.GONE);
txt_question_text = (TextView) itemView.findViewById(R.id.txt_question_text);
txt_question_text.setText(question.getQuestionText());
ckbA = (CheckBox) itemView.findViewById(R.id.ckbA);
ckbA.setText(question.getAnswerA());
ckbA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbA.getText().toString());
else
Common.selected_values.remove(ckbA.getText().toString());
}
});
ckbB = (CheckBox) itemView.findViewById(R.id.ckbB);
ckbB.setText(question.getAnswerB());
ckbB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbB.getText().toString());
else
Common.selected_values.remove(ckbB.getText().toString());
}
});
ckbC = (CheckBox) itemView.findViewById(R.id.ckbC);
ckbC.setText(question.getAnswerC());
ckbC.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbC.getText().toString());
else
Common.selected_values.remove(ckbC.getText().toString());
}
});
ckbD = (CheckBox) itemView.findViewById(R.id.ckbD);
ckbD.setText(question.getAnswerD());
ckbD.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbD.getText().toString());
else
Common.selected_values.remove(ckbD.getText().toString());
}
});
}
return itemView;
}
#Override
public CurrentQuestion getSelectedAnswer() {
CurrentQuestion currentQuestion = new CurrentQuestion(questionIndex, Common.ANSWER_TYPE.NO_ANSWER);
StringBuilder result = new StringBuilder();
if (Common.selected_values.size() > 1) {
//for multi choices this will make it multi arrays for answer if it has multi value
Object[] arrayAnswer = Common.selected_values.toArray();
for (int i = 0; i < arrayAnswer.length; i++)
if (i < arrayAnswer.length - 1)
result.append(new StringBuilder(((String) arrayAnswer[i]).substring(0, 1)).append(","));
else
result.append(new StringBuilder((String) arrayAnswer[i]).substring(0, 1));
} else if (Common.selected_values.size() == 1) {
Object[] arrayAnswer = Common.selected_values.toArray();
result.append((String) arrayAnswer[0]).substring(0, 1);
}
if (question != null) {
if (!TextUtils.isEmpty(result)) {
if (result.toString().equals(question.getCorrectAnswer()))
currentQuestion.setType(Common.ANSWER_TYPE.RIGHT_ANSWER);
else
currentQuestion.setType(Common.ANSWER_TYPE.WRONG_ANSWER);
} else
currentQuestion.setType(Common.ANSWER_TYPE.NO_ANSWER);
} else {
Toast.makeText(getContext(), "Cannot get Question", Toast.LENGTH_SHORT).show();
currentQuestion.setType(Common.ANSWER_TYPE.NO_ANSWER);
}
Common.selected_values.clear();
return currentQuestion;
}
#Override
public void showCorrectAnswer() {
String[] correctAnswer = question.getCorrectAnswer().split(",");
for (String answer : correctAnswer) {
if (answer.equals("A")) {
ckbA.setTypeface(null, Typeface.BOLD);
ckbA.setTextColor(Color.RED);
} else if (answer.equals("B")) {
ckbB.setTypeface(null, Typeface.BOLD);
ckbB.setTextColor(Color.RED);
} else if (answer.equals("C")) {
ckbC.setTypeface(null, Typeface.BOLD);
ckbC.setTextColor(Color.RED);
} else if (answer.equals("D")) {
ckbD.setTypeface(null, Typeface.BOLD);
ckbD.setTextColor(Color.RED);
}
}
}
#Override
public void disapleAnswer() {
ckbA.setEnabled(false);
ckbB.setEnabled(false);
ckbC.setEnabled(false);
ckbD.setEnabled(false);
}
#Override
public void resetQuestion() {
ckbA.setEnabled(true);
ckbB.setEnabled(true);
ckbC.setEnabled(true);
ckbD.setEnabled(true);
ckbA.setChecked(false);
ckbB.setChecked(false);
ckbC.setChecked(false);
ckbD.setChecked(false);
ckbA.setTypeface(null, Typeface.NORMAL);
ckbA.setTextColor(Color.BLACK);
ckbB.setTypeface(null, Typeface.NORMAL);
ckbB.setTextColor(Color.BLACK);
ckbC.setTypeface(null, Typeface.NORMAL);
ckbC.setTextColor(Color.BLACK);
ckbD.setTypeface(null, Typeface.NORMAL);
ckbD.setTextColor(Color.BLACK);
}
}
This is my QuestionActivity:
public class QuestionActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private static final int CODE_GET_RESULT = 9999;
ActionBarDrawerToggle toggle;
int time_play = Common.TOTAL_TIME;
private static final String time_Format = "%02d:%02d:%02d";
boolean isAnswerModeView = false;
TextView txt_right_answer, txt_timer, txt_wrong_answer;
RecyclerView answer_sheet_view;
AnswerSheetAdapter answerSheetAdapter;
AnswerSheetHelperAdapter answerSheetHelperAdapter;
ViewPager viewPager;
TabLayout tabLayout;
#Override
protected void onDestroy() {
if (Common.countDownTimer != null)
Common.countDownTimer.cancel();
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(Common.selectedCategory.getName());
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//we need to import question from db
takeQuestion();
if (Common.questionList.size() > 0) {
//to show timer and answer
txt_right_answer = (TextView) findViewById(R.id.txt_question_right);
txt_timer = (TextView) findViewById(R.id.txt_timer);
txt_timer.setVisibility(View.VISIBLE);
txt_right_answer.setVisibility(View.VISIBLE);
txt_right_answer.setText(new StringBuilder(String.format("%d/%d", Common.right_answer_count, Common.questionList.size())));
countTimer();
//view
answer_sheet_view = (RecyclerView) findViewById(R.id.grid_answer);
answer_sheet_view.setHasFixedSize(true);
if (Common.questionList.size() > 5)
answer_sheet_view.setLayoutManager(new GridLayoutManager(this, Common.questionList.size() / 2));
answerSheetAdapter = new AnswerSheetAdapter(this, Common.answerSheetList);
answer_sheet_view.setAdapter(answerSheetAdapter);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
genFragmentList();
QuestionFragmentAdapter questionFragmentAdapter = new QuestionFragmentAdapter(getSupportFragmentManager(),
this,
Common.fragmentsList);
viewPager.setAdapter(questionFragmentAdapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int SCROLLING_RIGHT = 0;
int SCROLLING_LEFT = 1;
int SCROLLING_UNDETERMINED = 2;
int currentScrollDirection = 2;
private void setScrollingDirection(float positionOffset) {
if ((1 - positionOffset) >= 0.5)
this.currentScrollDirection = SCROLLING_RIGHT;
else if ((1 - positionOffset) <= 0.5)
this.currentScrollDirection = SCROLLING_LEFT;
}
private boolean isScrolledDirectionUndetermined() {
return currentScrollDirection == SCROLLING_UNDETERMINED;
}
private boolean isScrollingRight() {
return currentScrollDirection == SCROLLING_RIGHT;
}
private boolean isScrollingLeft() {
return currentScrollDirection == SCROLLING_LEFT;
}
#Override
public void onPageScrolled(int i, float v, int i1) {
if (isScrolledDirectionUndetermined())
setScrollingDirection(v);
}
#Override
public void onPageSelected(int i) {
QuestionFragment questionFragment;
int position = 0;
if (i > 0) {
if (isScrollingRight()) {
questionFragment = Common.fragmentsList.get(i - 1);
position = i - 1;
} else if (isScrollingLeft()) {
questionFragment = Common.fragmentsList.get(i + 1);
position = i + 1;
} else {
questionFragment = Common.fragmentsList.get(position);
}
} else {
questionFragment = Common.fragmentsList.get(0);
position = 0;
}
CurrentQuestion question_state = questionFragment.getSelectedAnswer();
Common.answerSheetList.set(position, question_state);
answerSheetAdapter.notifyDataSetChanged();
countCorrectAnswer();
txt_right_answer.setText(new StringBuilder(String.format("%d", Common.right_answer_count))
.append("/")
.append(String.format("%d", Common.questionList.size())).toString());
txt_wrong_answer.setText(String.valueOf(Common.wrong_answer_count));
if (question_state.getType() != Common.ANSWER_TYPE.NO_ANSWER) {
questionFragment.showCorrectAnswer();
questionFragment.disapleAnswer();
}
}
#Override
public void onPageScrollStateChanged(int i) {
if (i == ViewPager.SCROLL_STATE_IDLE)
this.currentScrollDirection = SCROLLING_UNDETERMINED;
}
});
}
}
private void finishGame() {
int position = viewPager.getCurrentItem();
QuestionFragment questionFragment = Common.fragmentsList.get(position);
CurrentQuestion question_state = questionFragment.getSelectedAnswer();
Common.answerSheetList.set(position, question_state);
answerSheetAdapter.notifyDataSetChanged();
countCorrectAnswer();
txt_right_answer.setText(new StringBuilder(String.format("%d", Common.right_answer_count))
.append("/")
.append(String.format("%d", Common.questionList.size())).toString());
txt_wrong_answer.setText(String.valueOf(Common.wrong_answer_count));
if (question_state.getType() != Common.ANSWER_TYPE.NO_ANSWER) {
questionFragment.showCorrectAnswer();
questionFragment.disapleAnswer();
}
Intent intent = new Intent(QuestionActivity.this, ResultActivity.class);
Common.timer = Common.TOTAL_TIME - time_play;
Common.no_answer_count = Common.questionList.size() - (Common.wrong_answer_count + Common.right_answer_count);
Common.data_question = new StringBuilder(new Gson().toJson(Common.answerSheetList));
startActivityForResult(intent, CODE_GET_RESULT);
}
private void countCorrectAnswer() {
Common.right_answer_count = Common.wrong_answer_count = 0;
for (CurrentQuestion item : Common.answerSheetList)
if (item.getType() == Common.ANSWER_TYPE.RIGHT_ANSWER)
Common.right_answer_count++;
else if (item.getType() == Common.ANSWER_TYPE.WRONG_ANSWER)
Common.wrong_answer_count++;
}
private void genFragmentList() {
for (int i = 0; i < Common.questionList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putInt("index", i);
QuestionFragment fragment = new QuestionFragment();
fragment.setArguments(bundle);
Common.fragmentsList.add(fragment);
}
}
private void countTimer() {
if (Common.countDownTimer == null) {
Common.countDownTimer = new CountDownTimer(Common.TOTAL_TIME, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txt_timer.setText(String.format(time_Format,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
#Override
public void onFinish() {
//finish the game :]
finishGame();
}
}.start();
} else {
Common.countDownTimer.cancel();
Common.countDownTimer = new CountDownTimer(Common.TOTAL_TIME, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txt_timer.setText(String.format(time_Format,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
#Override
public void onFinish() {
//finish the game :]
}
}.start();
}
}
private void takeQuestion() {
Common.questionList = DBHelper.getInstance(this).getQuestionByCategory(Common.selectedCategory.getId());
if (Common.questionList.size() == 0) {
//this one in case category is empty
new MaterialStyledDialog.Builder(this)
.setTitle("Coming Soon !")
.setIcon(R.drawable.ic_sentiment_very_dissatisfied_black_24dp)
.setDescription("The content is coming soon waite for " + Common.selectedCategory.getName() + " category ")
.setPositiveText("ok")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
finish();
}
}).show();
} else {
if (Common.answerSheetList.size() > 0)
Common.answerSheetList.clear();
//gen answers from answersheet each question will has online 1 answer sheet content
for (int i = 0; i < Common.questionList.size(); i++) {
Common.answerSheetList.add(new CurrentQuestion(i, Common.ANSWER_TYPE.NO_ANSWER)); //no answer is default
}
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.menu_wrong_answer);
ConstraintLayout constraintLayout = (ConstraintLayout) item.getActionView();
txt_wrong_answer = (TextView) constraintLayout.findViewById(R.id.txt_wrong_answer);
txt_wrong_answer.setText(String.valueOf(0));
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.question, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_finish_game) {
if (!isAnswerModeView) {
new MaterialStyledDialog.Builder(this)
.setTitle("Finish ?")
.setIcon(R.drawable.ic_mood_black_24dp)
.setDescription("Do you really want to finish?")
.setNegativeText("NO")
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
}
})
.setPositiveText("YES")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
finishGame();
}
}).show();
} else
finishGame();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_GET_RESULT) {
if (resultCode == Activity.RESULT_OK) {
String action = data.getStringExtra("action");
if (action == null || TextUtils.isEmpty(action)) {
int questionNum = data.getIntExtra(Common.KEY_BACK_FROM_RESULT, -1);
viewPager.setCurrentItem(questionNum);
isAnswerModeView = true;
Common.countDownTimer.cancel();
txt_wrong_answer.setVisibility(View.GONE);
txt_right_answer.setVisibility(View.GONE);
txt_timer.setVisibility(View.GONE);
} else {
if (action.equals("viewquizanswer")) {
viewPager.setCurrentItem(0);
isAnswerModeView = true;
Common.countDownTimer.cancel();
txt_wrong_answer.setVisibility(View.GONE);
txt_right_answer.setVisibility(View.GONE);
txt_timer.setVisibility(View.GONE);
for (int i = 0; i < Common.fragmentsList.size(); i++) {
Common.fragmentsList.get(i).showCorrectAnswer();
Common.fragmentsList.get(i).disapleAnswer();
}
} else if (action.equals("doitagain")) {
viewPager.setCurrentItem(0);
isAnswerModeView = false;
countTimer();
txt_wrong_answer.setVisibility(View.VISIBLE);
txt_right_answer.setVisibility(View.VISIBLE);
txt_timer.setVisibility(View.VISIBLE);
for (CurrentQuestion item : Common.answerSheetList)
item.setType(Common.ANSWER_TYPE.NO_ANSWER);
answerSheetAdapter.notifyDataSetChanged();
answerSheetHelperAdapter.notifyDataSetChanged();
for (int i = 0; i < Common.fragmentsList.size(); i++)
Common.fragmentsList.get(i).resetQuestion();
}
}
}
}
}
}
You're never initializing answerSheetHelperAdapter, so it's null. That's one of your problems.
It's impossible to tell why the other one is null without an actual stack trace and more code, but you're probably setting it to null in
question = Common.questionList.get(questionIndex);
See What is a NullPointerException, and how do I fix it? for more information on how to debug this.

ZXing on the second tab keep scanning and disturb first tab events

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

Update sharedpreference that uses checkbox

I want to update the changes when I uncheck and check the checkbox in the preference activity but when I press the back button it doesn't work. It only works when I close the activity and then open it
Main activity
public class MainActivity extends ActionBarActivity {
private ToggleButton togle;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
private ShakeListener mShaker;
MediaPlayer mp;
ImageView anime;
int p=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anime = (ImageView) findViewById(R.id.Animation);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish(); }
});
alert.show();
return;}
getCamera();
togle = (ToggleButton) findViewById(R.id.ToggleButton01);
togle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean checked = ((ToggleButton) v).isChecked();
if (checked){
turnOffFlash();
}
else{
getCamera();
turnOnFlash();
}
}
});
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake == true ){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake()
{ if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
}
else{
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
} }
});
}
}
private void getCamera() {
// TODO Auto-generated method stub
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
} }
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
getCamera();
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
anime.setImageResource(R.drawable.anim);
anime.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) anime.getDrawable();
frameAnimation.start();
}
});
// changing button/switch image
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
isFlashOn = false;
anime.setImageResource(R.drawable.off);
// changing button/switch image
}
}
private void playSound() {
// TODO Auto-generated method stub
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.off1);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.on1);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, Prefsetting.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Preference activity
public class Prefsetting extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefset);
}
}
You access SharedPreferences in the onCreate() of your MainActivity, which is only called when that activity is created from scratch (i.e. when you first start your app). As you (presumably) navigate to and from your Prefsetting Activity fairly quickly, MainActivity is likely only in a paused or stopped state when it is resumed. Take a look at the diagram here to see what happens to Activity classes as they move into and out of the foreground.
You have a couple of options. Either place this:
#Override
public void onResume() {
super.onResume();
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake) {
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
} else {
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
}
}
});
} else {
if (mShaker != null) {
mShaker.setOnShakeListener(null);
mShaker = null;
}
}
}
Into somewhere like onResume().
Or, use an EventBus like LocalBrodcastManager to update your Preferences when onPause() is called in your PreferenceActivity.
From the code snippet it appears that you never actually commit your changes to the SharedPreferences of the application. Somewhere in the code when that boolean is flipped you need to do something like this:
prefs.put("checkbox", currentBooleanState).commit();

Categories

Resources