Placing "Native Advanced Ads" inside popup close - java

I try to put advanced ads inside the dialog box when you close the application, but when you open a dialog box does not load the ad for the first time. ... I am worried that I load the ad inside the application
without appearing and at closing I put it in the dialog box for fear that the agent considers it a google violation to download the ad without its appearance
Constant code from android developer
public class MainActivity extends AppCompatActivity {
private static final String ADMOB_AD_UNIT_ID = "ca-app-pub-3940256099942544/2247696110";
private static final String ADMOB_APP_ID = "ca-app-pub-3940256099942544~3347511713";
AdLoader.Builder builder;
UnifiedNativeAdView adView;
private Button refresh;
private CheckBox startVideoAdsMuted;
private TextView videoStatus;
private UnifiedNativeAd nativeAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this, ADMOB_APP_ID);
refresh = findViewById(R.id.btn_refresh);
startVideoAdsMuted = findViewById(R.id.cb_start_muted);
videoStatus = findViewById(R.id.tv_video_status);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View unusedView) {
refreshAd();
}
});
refreshAd();
}
/**
* Populates a {#link UnifiedNativeAdView} object with data from a given
* {#link UnifiedNativeAd}.
*
* #param nativeAd the object containing the ad's assets
* #param adView the view to be populated
*/
private void populateUnifiedNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdView adView) {
// Set the media view. Media content will be automatically populated in the media view once
// adView.setNativeAd() is called.
MediaView mediaView = adView.findViewById(R.id.ad_media);
adView.setMediaView(mediaView);
// Set other ad assets.
adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
adView.setBodyView(adView.findViewById(R.id.ad_body));
adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
adView.setIconView(adView.findViewById(R.id.ad_app_icon));
adView.setPriceView(adView.findViewById(R.id.ad_price));
adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
adView.setStoreView(adView.findViewById(R.id.ad_store));
adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));
// The headline is guaranteed to be in every UnifiedNativeAd.
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
if (nativeAd.getBody() == null) {
adView.getBodyView().setVisibility(View.INVISIBLE);
} else {
adView.getBodyView().setVisibility(View.VISIBLE);
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
}
if (nativeAd.getCallToAction() == null) {
adView.getCallToActionView().setVisibility(View.INVISIBLE);
} else {
adView.getCallToActionView().setVisibility(View.VISIBLE);
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
}
if (nativeAd.getIcon() == null) {
adView.getIconView().setVisibility(View.GONE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(
nativeAd.getIcon().getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (nativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
}
if (nativeAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAd.getStore());
}
if (nativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView())
.setRating(nativeAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
if (nativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
adView.getAdvertiserView().setVisibility(View.VISIBLE);
}
// This method tells the Google Mobile Ads SDK that you have finished populating your
// native ad view with this native ad. The SDK will populate the adView's MediaView
// with the media content from this native ad.
adView.setNativeAd(nativeAd);
// Get the video controller for the ad. One will always be provided, even if the ad doesn't
// have a video asset.
VideoController vc = nativeAd.getVideoController();
// Updates the UI to say whether or not this ad has a video asset.
if (vc.hasVideoContent()) {
videoStatus.setText(String.format(Locale.getDefault(),
"Video status: Ad contains a %.2f:1 video asset.",
vc.getAspectRatio()));
// Create a new VideoLifecycleCallbacks object and pass it to the VideoController. The
// VideoController will call methods on this object when events occur in the video
// lifecycle.
vc.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
#Override
public void onVideoEnd() {
// Publishers should allow native ads to complete video playback before
// refreshing or replacing them with another ad in the same UI location.
refresh.setEnabled(true);
videoStatus.setText("Video status: Video playback has ended.");
super.onVideoEnd();
}
});
} else {
videoStatus.setText("Video status: Ad does not contain a video asset.");
refresh.setEnabled(true);
}
}
/**
* Creates a request for a new native ad based on the boolean parameters and calls the
* corresponding "populate" method when one is successfully returned.
*
*/
private void refreshAd() {
refresh.setEnabled(false);
builder = new AdLoader.Builder(this, ADMOB_AD_UNIT_ID);
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
// OnUnifiedNativeAdLoadedListener implementation.
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
if (nativeAd != null) {
nativeAd.destroy();
}
nativeAd = unifiedNativeAd;
FrameLayout frameLayout =
findViewById(R.id.fl_adplaceholder);
adView = (UnifiedNativeAdView) getLayoutInflater()
.inflate(R.layout.ad_unified, null);
populateUnifiedNativeAdView(unifiedNativeAd, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
});
VideoOptions videoOptions = new VideoOptions.Builder()
.setStartMuted(startVideoAdsMuted.isChecked())
.build();
NativeAdOptions adOptions = new NativeAdOptions.Builder()
.setVideoOptions(videoOptions)
.build();
builder.withNativeAdOptions(adOptions);
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
refresh.setEnabled(true);
Toast.makeText(MainActivity.this, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
videoStatus.setText("");
}
Now I'm trying to put the code refresh method insaid dialog box instead of refresh method
public void showdilog(){
builder = new AdLoader.Builder(this, ADMOB_AD_UNIT_ID);
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
// OnUnifiedNativeAdLoadedListener implementation.
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
if (nativeAd != null) {
nativeAd.destroy();
}
nativeAd = unifiedNativeAd;
FrameLayout frameLayout =
findViewById(R.id.fl_adplaceholder);
adView = (UnifiedNativeAdView) getLayoutInflater()
.inflate(R.layout.ad_unified, null);
populateUnifiedNativeAdView(unifiedNativeAd, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
});
VideoOptions videoOptions = new VideoOptions.Builder()
.setStartMuted(startVideoAdsMuted.isChecked())
.build();
NativeAdOptions adOptions = new NativeAdOptions.Builder()
.setVideoOptions(videoOptions)
.build();
builder.withNativeAdOptions(adOptions);
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
refresh.setEnabled(true);
Toast.makeText(MainActivity.this, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
bulider.setView(adView);
builder.setMessage(R.string.onfirm_exit)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}

What you're doing is that you're building and showing your dialog box at the same time. So, at the time you show your dialog box you're also loading your native ad.
You should BUILD your dialog box in advance, and don't call alert.show() in your build function.
So, call your buildDialog() in MainActivity in advance.
In your onBackPressed function call alert.show().
Hope it helps.

Related

How to keep the MediaRouter running in background activity?

please I need your help after searching a lot without issues.
I have an demostration app to use an second screen attached to my device.
I have the source code of the app, they use the Mediarouter class and an class named LauncherSecondScreen extended from the Presentation class
I have tried to make the app as an service to keep runnig the app in background, but the mediarouter callback seems running only on the princpal thread ( I'm not sure I am just a beginner in android dev).
I have the full code of the app : there is two layout activity one showed on the princpal screen and the other on the second screen:
public class MainActivity extends Activity {
private final String TAG = "PresentationWithMediaRouterActivity";
private MediaRouter mMediaRouter;
private LauncherSecondScreen mPresentation;
private boolean mPaused;
/**
* Initialization of the Activity after it is first created. Must at least
* call {#link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// Get the media router service.
mMediaRouter = (MediaRouter)getSystemService(Context.MEDIA_ROUTER_SERVICE);
// See assets/res/any/layout/presentation_with_media_router_activity.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
// Be sure to call the super class.
super.onResume();
// Listen for changes to media routes.
mMediaRouter.addCallback(MediaRouter.ROUTE_TYPE_LIVE_VIDEO, mMediaRouterCallback);
// Update the presentation based on the currently selected route.
mPaused = false;
updatePresentation();
}
private void updatePresentation() {
// Get the current route and its presentation display.
MediaRouter.RouteInfo route = mMediaRouter.getSelectedRoute(
MediaRouter.ROUTE_TYPE_LIVE_VIDEO);
Display presentationDisplay = route != null ? route.getPresentationDisplay() : null;
// Dismiss the current presentation if the display has changed.
if (mPresentation != null && mPresentation.getDisplay() != presentationDisplay) {
Log.i(TAG, "Dismissing presentation because the current route no longer "
+ "has a presentation display.");
mPresentation.dismiss();
mPresentation = null;
}
// Show a new presentation if needed.
if (mPresentation == null && presentationDisplay != null) {
Log.i(TAG, "Showing presentation on display: " + presentationDisplay);
mPresentation = new LauncherSecondScreen(this, presentationDisplay);
mPresentation.setOnDismissListener(mOnDismissListener);
try {
mPresentation.show();
} catch (WindowManager.InvalidDisplayException ex) {
Log.w(TAG, "Couldn't show presentation! Display was removed in "
+ "the meantime.", ex);
mPresentation = null;
}
}
// Update the contents playing in this activity.
updateContents();
}
private void updateContents() {
// Show either the content in the main activity or the content in the presentation
// along with some descriptive text about what is happening.
if (mPresentation != null) {
if (mPaused) {
mPresentation.dismiss();//getSurfaceView().onPause();
} else {
mPresentation.show();//getSurfaceView().onResume();
}
} else {
/* mInfoTextView.setText("presentation_with_media_router_now_playing_locally");
mSurfaceView.setVisibility(View.VISIBLE);
if (mPaused) {
mSurfaceView.onPause();
} else {
mSurfaceView.onResume();
}*/
}
}
private final MediaRouter.SimpleCallback mMediaRouterCallback =
new MediaRouter.SimpleCallback() {
#Override
public void onRouteSelected(MediaRouter router, int type, RouteInfo info) {
Log.d(TAG, "onRouteSelected: type=" + type + ", info=" + info);
updatePresentation();
}
#Override
public void onRouteUnselected(MediaRouter router, int type, RouteInfo info) {
Log.d(TAG, "onRouteUnselected: type=" + type + ", info=" + info);
updatePresentation();
}
#Override
public void onRoutePresentationDisplayChanged(MediaRouter router, RouteInfo info) {
Log.d(TAG, "onRoutePresentationDisplayChanged: info=" + info);
updatePresentation();
}
};
/**
* Listens for when presentations are dismissed.
*/
private final DialogInterface.OnDismissListener mOnDismissListener =
new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if (dialog == mPresentation) {
Log.i(TAG, "Presentation was dismissed.");
mPresentation = null;
updateContents();
}
}
};
#SuppressLint({"NewApi"})
public class LauncherSecondScreen extends Presentation
{
public LauncherSecondScreen(Context paramContext, Display paramDisplay)
{
super(paramContext, paramDisplay/*,android.R.style.Theme_Holo_Light_Dialog_NoActionBar*/);
}
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.dialog_second_screen_content);
//// this.iv_secondScreen_banner = ((ImageView)findViewById(R.id.titleImage));
}
}
}
the app is well, it make one view in the princpale screen and a second view in the second screen , but when i resume the app to background the second screen take the same view of the first screen.
I want to keep the second view showing in the second screen even i resume the app to use another app

AdView Not Showing on first load

Ive been working on learning how to make games and Id like to understand how to add Adverts. The advert shows? But only after I close and reopen, "SMART_BANNER" doesnt work either. What am I doing wrong?
public class MainActivity extends FragmentActivity {
public GoogleApiClient apiClient;
private MainActivity main = this;
public GameSurface gameSurface;
RelativeLayout layout;
RelativeLayout adlayout;
private Saver saver;
private static final String HIGHSCORE = "highscore";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiClient = new GoogleApiClient.Builder(this)
.addApi(Games.API)
.addScope(Games.SCOPE_GAMES)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(getBaseContext(), "Connection To Google Games Failed, No App Found Or No Internet", Toast.LENGTH_SHORT).show();
}
}).build();
MobileAds.initialize(this, getString(R.string.adappid));
apiClient.connect();
saver = Saver.getInstance(this);
playerscores();
// fullscreen
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
adView.loadAd(adRequestBuilder.build());
//ads
gameSurface = new GameSurface(this, main);
layout.addView(gameSurface);
layout.addView(adView);
setContentView(layout);
}
// Set No Title
//this.setContentView(new GameSurface(this));
public void playerscores() {
if (apiClient != null && apiClient.isConnected()) {
Games.Leaderboards.loadCurrentPlayerLeaderboardScore(apiClient, "CgkI08DA0-sZEAIQAQ", LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC).setResultCallback(
new ResultCallback<Leaderboards.LoadPlayerScoreResult>() {
#Override
public void onResult(Leaderboards.LoadPlayerScoreResult arg0) {
LeaderboardScore c = arg0.getScore();
String score = c.getDisplayScore();
saver.saveString(HIGHSCORE, score);
}
});
}
}
public void gameover() {
if (apiClient != null && apiClient.isConnected()) {
Games.Leaderboards.submitScore(apiClient, getString(R.string.leaderboard_highscores), GameSurface.HighScore);
}
}
public void showLeaderboard() {
if (apiClient != null && apiClient.isConnected()) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(apiClient, "CgkI08DA0-sZEAIQAQ"), 1);
} else {
apiClient.connect();
}
}
}
Basically I want the advert to show as soon as the app opens. Id Also like it to be fixed to the bottom, I cant find a way to do this, I've tried adding gravity but adview doesn't have this attribute.
Any advice as to what Im doing wrong will be greatly appreciated.
Part Answer I worked out how to get the advert align to the bottom and Center it.
RelativeLayout.LayoutParams viewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);viewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);viewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
adView.setLayoutParams(viewParams);
EDIT [SOLVED]
added an adview listener, reading through admob docs and seeing various listeners gave me an idea!
then just made it redraw its self.
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
adView.setVisibility(View.GONE);
adView.setVisibility(View.VISIBLE);
}
});
you should add the view before loading the ad, if you want to show the ad faster just call setContentView() as soon as possible and then load the ad

Android - WebView Fullscreen video not working inside viewpager

Webview Fullscreen video not working in viewpager(fragment):
implemented fullscreen view in webview chromeclient but if click fullscreen button, it shows blank screen but audio playing. after change orientation video will appear.
WebViewFragment.java
mWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
if(isAdded() && getActivity()!=null) {
DiapromaActivity activity = (DiapromaActivity) getActivity();
activity.showCustomView(view, callback);
}
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
if(isAdded() && getActivity()!=null) {
DiapromaActivity activity = (DiapromaActivity) getActivity();
activity.hideCustomView();
}
}
});
DiapromaActivity.java
public void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
//If there's already a custom view, this is a duplicate call, and we should
// terminate the new view, then bail out.
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
//Create a reusable set of FrameLayout.LayoutParams
FrameLayout.LayoutParams fullscreenParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
//Save the drawer view into an instance variable, then hide it.
mContentView = findViewById(R.id.root_view);
mContentView.setVisibility(View.GONE);
//Create a new custom view container
mCustomViewContainer = new FrameLayout(this);
mCustomViewContainer.setLayoutParams(fullscreenParams);
mCustomViewContainer.setBackgroundResource(android.R.color.black);
//Set view to instance variable, then add to container.
mCustomView = view;
view.setLayoutParams(fullscreenParams);
mCustomViewContainer.addView(mCustomView);
mCustomViewContainer.setVisibility(View.VISIBLE);
//Save the callback an instance variable.
mCustomViewCallback = callback;
//Hide the action bar
getSupportActionBar().hide();
isFullScreen=true;
//Set the custom view container as the activity's content view.
setContentView(mCustomViewContainer);
}
/**
* Method to mirror onShowCustomView from the WebChrome client, allowing WebViews in a Fragment
* to hide custom views.
*/
public void hideCustomView() {
if (mCustomView == null) {
//Nothing to hide - return.
return;
} else {
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
// Show the ActionBar
getSupportActionBar().show();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
setContentView(mContentView);
isFullScreen=false;
}
}

How should I return to a previous dialog from another one?

I've got an inputDialog, which allows for some text inputs. On clicking save, the inputDialog checks if the entered text is already available (to prevent double entries). If this is the case, a new AlertDialog is created, simply stating "The value you entered already exists", with just an "Ok" button to dismiss this AlertDialog. This all works.
I would like to have the inputDialog pop back up again, after dismissing the AlertDialog, with the values that were entered by the user before still in the editText fields.
I'm not expecting any problems on getting those values back in the editText fields (Store them in a variable on clicking save, if the double entry error occurs, set those variables on the editText's. If I'm doing this in a stupid way, please let me know).
I am however having trouble with getting the first (inputDialog) dialog to come back. The code you see below is the code for my inputDialog fragment (The code is simplified, so if something seems to be missing, it probably is. Let me know, so I can add it back in.)
So, to repeat myself: How can I return to the previous dialog after dismissing the second one?
StuffManagerInputDialogFragment.java:
public class StuffManagerInputDialogFragment extends DialogFragment {
EditText nameInputField;
EditText tagInputField;
DBHandler dbHandler;
StuffManagerFragment f = new StuffManagerFragment();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View v_iew = inflater.inflate(R.layout.fragment_inputdialog, null);
nameInputField = (EditText) v_iew.findViewById(R.id.inputdialogname);
tagInputField = (EditText) v_iew.findViewById(R.id.inputdialogtag);
dbHandler = new DBHandler(getActivity(), null, null, 1);
final MainActivity ma = (MainActivity) getActivity();
final AlertDialog.Builder newLinkDialog = new AlertDialog.Builder(getActivity());
newLinkDialog.setView(v_iew)
.setTitle("New Link")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String nameInputFieldText = nameInputField.getText().toString();
String tagInputFieldText = tagInputField.getText().toString();
ArrayList<String> nameArray = dbHandler.nameArrayMethod();
ArrayList<String> tagArray = dbHandler.tagArrayMethod();
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
if (nameArray.contains(nameInputFieldText) || tagArray.contains(tagInputFieldText)) {
if (nameArray.contains(nameInputFieldText) && tagArray.contains(tagInputFieldText)) {
AlertDialog.Builder errorBoth = new AlertDialog.Builder(getActivity())
.setTitle("Error")
.setMessage("The name and tag you entered are already in use.")
.setIcon(R.drawable.ic_error_black)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Return to previous dialog here
}
});
errorBoth.show();
}
} else {
dbHandler.addLink(nameInputFieldText, tagInputFieldText);
nameArray = dbHandler.nameArrayMethod();
int nameArraySize = (nameArray.size() - 1);
MenuItem item = menu.add(R.id.group1, nameArraySize, 1, nameArray.get(nameArraySize));
Toast.makeText(getContext(), "'" + nameInputFieldText + " - " + tagInputFieldText + "' link saved.", Toast.LENGTH_SHORT).show();
ma.addSMVFFragments();
f.hideDeleteAllButton = false;
getActivity().invalidateOptionsMenu();
}
}
})
.setNegativeButton("Cancel", null);
return newLinkDialog.create();
}
}
A better solution is to have a dialog fragment for your input layout, and that dialog fragment would display an AlertDialog on OK if the text validation fails. The input dialog fragment would not dismiss in this case, it will remain in the background so when you dismiss the alert dialog to tell the user the input is invalid, you return to the input dialog as it was.
To prevent the dialog fragment from dismissing on OK you would override onStart and get a reference to the OK button and set the listener there, like this:
#Override
public void onStart() {
super.onStart();
AlertDialog alertDialog = (AlertDialog) getDialog();
if (alertDialog != null) {
mOKButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
mOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (field OK) {
// save data
dismiss();
} else {
// show error dialog
}
}
});
}
}

Android 6 Marshmallow ListView. Start activity with runtime permissions

I am developing an application for Android Marshmallow (API LEvel 23).
I have an Activity which contains a ListView.
I populate that ListView by using a BaseView Adapter.
I want to start an Activity whenever I push a button inside my ListView.
However, this Activity needs to access the camera which in the latest Android version means that I should ask for the camera permission during runtime.
The camera using Activity will be an ZXing Activity.
Here is the Activity code:
public class ProviderListActivity extends AppCompatActivity {
public boolean can_access_camera = false;
public final int got_camera = PackageManager.PERMISSION_DENIED;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider_list);
ListView listView = (ListView) findViewById(R.id.ProviderListView);
CardsDBHelper dbHelper = new CardsDBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
listView.setAdapter(new ProviderListAdapter(this, db));
}
public void start_scan(){
if (have_camera_permission()){
start_scan_activity();
} else {
Log.d("ProviderListActivity", "I CANNOT ACCESS THE CAMERA");
}
}
public void start_scan_activity(){
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
public boolean have_camera_permission(){
//Check for permissions
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, got_camera);
} else {
can_access_camera = true;
}
return can_access_camera;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case got_camera: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
can_access_camera = true;
} else {
can_access_camera = false;
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
The getView() method in my Adapter is:
public View getView(int position, View convertView, final ViewGroup parent) {
Button grid_button;
if (convertView == null) {
// if it's not recycled, initialize some attributes
grid_button = new Button(mContext);
grid_button.setText("Hello Text");
Drawable d = mContext.getDrawable(R.drawable.circle);
grid_button.setCompoundDrawablesRelativeWithIntrinsicBounds(null,d,null,null);
grid_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What do I need to put inside here?
}
});
} else {
grid_button = (Button) convertView;
}
return grid_button;
}
You may have noticed that the Adapter gets an extra db argument.
This is a SQLite database object which is which is used inside the Adapter, but this is not relevant.
I am not sure how to call my scan Activity by using the onClick override.
I tried passing the parent Activity as an argument in the Adapter and call the scan method, but I get the following exception:
java.lang.IllegalArgumentException: Can only use lower 8 bits for requestCode`
Does anyone have a solution for my problem?
You are getting java.lang.IllegalArgumentException: Can only use lower 8 bits for requestCode Error because you are using -1(PackageManager.PERMISSION_DENIED) as requestCode for requestPermissions method.
To make it work use any requestCode between 1 to 255.
public final int got_camera = 24;

Categories

Resources