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

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

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();
}
})
;
}
}

How can I limit interstitial ad opening?

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

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.

How to allow multiple windows on webview to get facebook login working?

I'm creating an app for my website and need to when you click on external links like facebook and google login you get a new window tab that closes after login.
I`ve added mWebView.getSettings().setSupportMultipleWindows(true); but now when I click on the link nothing happens
MainFragment.java
public class MainFragment extends TaskFragment implements SwipeRefreshLayout.OnRefreshListener, AdvancedWebView.Listener {
private static final String ARGUMENT_URL = "url";
private static final String ARGUMENT_SHARE = "share";
private static final int REQUEST_FILE_PICKER = 1;
private boolean mProgress = false;
private View mRootView;
private StatefulLayout mStatefulLayout;
private AdvancedWebView mWebView;
private String mUrl = "about:blank";
private String mShare;
private boolean mLocal = false;
private ValueCallback<Uri> mFilePathCallback4;
private ValueCallback<Uri[]> mFilePathCallback5;
private int mStoredActivityRequestCode;
private int mStoredActivityResultCode;
private Intent mStoredActivityResultIntent;
public static MainFragment newInstance(String url, String share) {
MainFragment fragment = new MainFragment();
// arguments
Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_URL, url);
arguments.putString(ARGUMENT_SHARE, share);
fragment.setArguments(arguments);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
// handle fragment arguments
Bundle arguments = getArguments();
if (arguments != null) {
handleArguments(arguments);
}
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.DISABLED ? R.layout.fragment_main : R.layout.fragment_main_swipeable;
mRootView = inflater.inflate(layout, container, false);
mWebView = mRootView.findViewById(R.id.main_webview);
return mRootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// restore webview state
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
// setup webview
setupView();
// pull to refresh
setupSwipeRefreshLayout();
// setup stateful layout
setupStatefulLayout(savedInstanceState);
// load data
if (mStatefulLayout.getState() == StatefulLayout.EMPTY) loadData();
// progress popup
showProgress(mProgress);
// check permissions
if (WebViewAppConfig.GEOLOCATION) {
PermissionUtility.checkPermissionAccessLocation(this);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mWebView.onResume();
}
#Override
public void onPause() {
super.onPause();
mWebView.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mRootView = null;
}
#Override
public void onDestroy() {
super.onDestroy();
mWebView.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(this)) {
// permitted
mWebView.onActivityResult(requestCode, resultCode, intent);
} else {
// not permitted
mStoredActivityRequestCode = requestCode;
mStoredActivityResultCode = resultCode;
mStoredActivityResultIntent = intent;
}
//handleFilePickerActivityResult(requestCode, resultCode, intent); // not used, used advanced webview instead
}
#Override
public void onSaveInstanceState(Bundle outState) {
// save current instance state
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
// stateful layout state
if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState);
// save webview state
mWebView.saveState(outState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// action bar menu
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_main, menu);
// show or hide share button
MenuItem share = menu.findItem(R.id.menu_main_share);
share.setVisible(mShare != null && !mShare.trim().equals(""));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// action bar menu behavior
switch (item.getItemId()) {
case R.id.menu_main_share:
IntentUtility.startShareActivity(getContext(), getString(R.string.app_name), getShareText(mShare));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA:
case PermissionUtility.REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE:
case PermissionUtility.REQUEST_PERMISSION_ACCESS_LOCATION: {
// if request is cancelled, the result arrays are empty
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
// permission granted
if (requestCode == PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA) {
// continue with activity result handling
if (mStoredActivityResultIntent != null) {
mWebView.onActivityResult(mStoredActivityRequestCode, mStoredActivityResultCode, mStoredActivityResultIntent);
mStoredActivityRequestCode = 0;
mStoredActivityResultCode = 0;
mStoredActivityResultIntent = null;
}
}
} else {
// permission denied
}
}
} else {
// all permissions denied
}
break;
}
}
}
#Override
public void onRefresh() {
runTaskCallback(new Runnable() {
#Override
public void run() {
refreshData();
}
});
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
Logcat.d("");
}
#Override
public void onPageFinished(String url) {
Logcat.d("");
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
Logcat.d("");
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
Logcat.d("");
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
}
}
#Override
public void onExternalPageRequest(String url) {
Logcat.d("");
}
public void refreshData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress popup
showProgress(true);
// load web url
String url = mWebView.getUrl();
if (url == null || url.equals("")) url = mUrl;
mWebView.loadUrl(url);
} else {
showProgress(false);
Toast.makeText(getActivity(), R.string.global_network_offline, Toast.LENGTH_LONG).show();
}
}
private void handleArguments(Bundle arguments) {
if (arguments.containsKey(ARGUMENT_URL)) {
mUrl = arguments.getString(ARGUMENT_URL);
mLocal = mUrl.contains("file://");
}
if (arguments.containsKey(ARGUMENT_SHARE)) {
mShare = arguments.getString(ARGUMENT_SHARE);
}
}
// not used, used advanced webview instead
private void handleFilePickerActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_FILE_PICKER) {
if (mFilePathCallback4 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback4.onReceiveValue(uri);
} else {
mFilePathCallback4.onReceiveValue(null);
}
}
if (mFilePathCallback5 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback5.onReceiveValue(new Uri[]{uri});
} else {
mFilePathCallback5.onReceiveValue(null);
}
}
mFilePathCallback4 = null;
mFilePathCallback5 = null;
}
}
private void loadData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress
if (WebViewAppConfig.PROGRESS_PLACEHOLDER) {
mStatefulLayout.showProgress();
} else {
mStatefulLayout.showContent();
}
// load web url
mWebView.loadUrl(mUrl);
} else {
mStatefulLayout.showOffline();
}
}
private void showProgress(boolean visible) {
// show pull to refresh progress bar
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (contentSwipeRefreshLayout != null) contentSwipeRefreshLayout.setRefreshing(visible);
if (offlineSwipeRefreshLayout != null) offlineSwipeRefreshLayout.setRefreshing(visible);
if (emptySwipeRefreshLayout != null) emptySwipeRefreshLayout.setRefreshing(visible);
mProgress = visible;
}
private void showContent(final long delay) {
final Handler timerHandler = new Handler();
final Runnable timerRunnable = new Runnable() {
#Override
public void run() {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mRootView != null) {
Logcat.d("timer");
mStatefulLayout.showContent();
}
}
});
}
};
timerHandler.postDelayed(timerRunnable, delay);
}
private void setupView() {
// webview settings
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath());
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
// user agent
if (WebViewAppConfig.WEBVIEW_USER_AGENT != null && !WebViewAppConfig.WEBVIEW_USER_AGENT.equals("")) {
mWebView.getSettings().setUserAgentString(WebViewAppConfig.WEBVIEW_USER_AGENT);
}
// advanced webview settings
mWebView.setListener(getActivity(), this);
mWebView.setGeolocationEnabled(true);
// webview style
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // fixes scrollbar on Froyo
// webview hardware acceleration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// webview chrome client
View nonVideoLayout = getActivity().findViewById(R.id.main_non_video_layout);
ViewGroup videoLayout = getActivity().findViewById(R.id.main_video_layout);
View progressView = getActivity().getLayoutInflater().inflate(R.layout.placeholder_progress, null);
VideoEnabledWebChromeClient webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, progressView, (VideoEnabledWebView) mWebView);
webChromeClient.setOnToggledFullscreen(new MyToggledFullscreenCallback());
mWebView.setWebChromeClient(webChromeClient);
//mWebView.setWebChromeClient(new MyWebChromeClient()); // not used, used advanced webview instead
// webview client
mWebView.setWebViewClient(new MyWebViewClient());
// webview key listener
mWebView.setOnKeyListener(new WebViewOnKeyListener((DrawerStateListener) getActivity()));
// webview touch listener
mWebView.requestFocus(View.FOCUS_DOWN); // http://android24hours.blogspot.cz/2011/12/android-soft-keyboard-not-showing-on.html
mWebView.setOnTouchListener(new WebViewOnTouchListener());
// webview scroll listener
//((RoboWebView) mWebView).setOnScrollListener(new WebViewOnScrollListener()); // not used
// admob
setupBannerView();
}
private void setupBannerView() {
if (WebViewAppConfig.ADMOB_UNIT_ID_BANNER != null && !WebViewAppConfig.ADMOB_UNIT_ID_BANNER.equals("") && NetworkUtility.isOnline(getActivity())) {
ViewGroup contentLayout = mRootView.findViewById(R.id.container_content);
AdMobUtility.createAdView(getActivity(), WebViewAppConfig.ADMOB_UNIT_ID_BANNER, AdSize.BANNER, contentLayout);
}
}
private void controlBack() {
if (mWebView.canGoBack()) mWebView.goBack();
}
private void controlForward() {
if (mWebView.canGoForward()) mWebView.goForward();
}
private void controlStop() {
mWebView.stopLoading();
}
private void controlReload() {
mWebView.reload();
}
private void setupStatefulLayout(Bundle savedInstanceState) {
// reference
mStatefulLayout = (StatefulLayout) mRootView;
// state change listener
mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() {
#Override
public void onStateChange(View view, #StatefulLayout.State int state) {
Logcat.d(String.valueOf(state));
// do nothing
}
});
// restore state
mStatefulLayout.restoreInstanceState(savedInstanceState);
}
private void setupSwipeRefreshLayout() {
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.ENABLED) {
contentSwipeRefreshLayout.setOnRefreshListener(this);
offlineSwipeRefreshLayout.setOnRefreshListener(this);
emptySwipeRefreshLayout.setOnRefreshListener(this);
} else if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.PROGRESS) {
contentSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
offlineSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
emptySwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
}
}
private String getShareText(String text) {
if (mWebView != null) {
if (mWebView.getTitle() != null) {
text = text.replaceAll("\\{TITLE\\}", mWebView.getTitle());
}
if (mWebView.getUrl() != null) {
text = text.replaceAll("\\{URL\\}", mWebView.getUrl());
}
}
return text;
}
private boolean isLinkExternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_EXTERNAL_BROWSER) {
if (url.contains(rule)) return true;
}
return false;
}
private boolean isLinkInternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_INTERNAL_WEBVIEW) {
if (url.contains(rule)) return true;
}
return false;
}
// not used, used advanced webview instead
private class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback5 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
return true;
}
return false;
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
public void openFileChooser(ValueCallback<Uri> filePathCallback) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
}
private class MyToggledFullscreenCallback implements VideoEnabledWebChromeClient.ToggledFullscreenCallback {
#Override
public void toggledFullscreen(boolean fullscreen) {
if (fullscreen) {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
} else {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
}
private class MyWebViewClient extends WebViewClient {
private boolean mSuccess = true;
#Override
public void onPageFinished(final WebView view, final String url) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mSuccess) {
showContent(500); // hide progress bar with delay to show webview content smoothly
showProgress(false);
if (WebViewAppConfig.ACTION_BAR_HTML_TITLE) {
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(view.getTitle());
}
CookieSyncManager.getInstance().sync(); // save cookies
}
mSuccess = true;
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null) {
mSuccess = false;
mStatefulLayout.showEmpty();
showProgress(false);
}
}
});
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
// forward to deprecated method
onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString());
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (DownloadFileUtility.isDownloadableFile(url)) {
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
return true;
}
return true;
} else if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
// determine for opening the link externally or internally
boolean external = isLinkExternal(url);
boolean internal = isLinkInternal(url);
if (!external && !internal) {
external = WebViewAppConfig.OPEN_LINKS_IN_EXTERNAL_BROWSER;
}
// open the link
if (external) {
IntentUtility.startWebActivity(getContext(), url);
return true;
} else {
showProgress(true);
return false;
}
} else if (url != null && url.startsWith("file://")) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
return false;
} else {
return IntentUtility.startIntentActivity(getContext(), url);
}
}
}
}

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