Google Developer Console indicates me that my app got java.lang.ClassCastException error on 2 different devices (P10 (HWVTR)-Android 7.0 and LG G3 (g3) - Android 6.0) at the same lane. I don't know what's the problem, I have tested it on Samsung Galaxy A3 2014 & 2017 and Huawei P9 Lite and works great.
Here is the code:
SharedPreferences prefs = this.getSharedPreferences(
"toast", Context.MODE_PRIVATE);
final int hasVisited = prefs.getInt("HAS_VISISTED_BEFORE", 0);
if(hasVisited == 0) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("My Text")
.setMessage("My Text, dsajh jghjsahjhsda dsa dsa")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.show();
prefs.edit().putInt("HAS_VISISTED_BEFORE", 1).apply();
}
The error is here final int hasVisited = prefs.getInt("HAS_VISISTED_BEFORE", 0);
I want to display this AlertDialog only once when the app if run for the first time.
Error log:
Caused by: java.lang.ClassCastException:
at android.app.SharedPreferencesImpl.getInt (SharedPreferencesImpl.java:242)
at com.doggedness_dev.pubgcratessimulator.MenuActivity.onCreate (MenuActivity.java:40)
at android.app.Activity.performCreate (Activity.java:6272)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2387)
It is possible that my SharedPreferences with the key HAS_VISISTED_BEFORE to interfere with another app that has the same key?
Every application has their own shared preferences location, so there is no way to interfere with another app that has the same key.
If your application's older versions have the same key with HAS_VISISTED_BEFORE and its value is not integer, you will have this problem. Because you have already have the value for this key and types are just different.
You can use try-catch like below, for this exception.
try {
}catch (ClassCastException ex){
ex.printStackTrace();
}
Remove this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
and write below line;
builder = new AlertDialog.Builder(MainActivity.this);
Related
I'm trying to add Layout with this code:
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE);
mYouTubePlayerLayout = (ConstraintLayoutKeyDispatchWrapper) layoutInflater.inflate(R.layout.background_player_layout, null, false);
mYouTubePlayerLayout.setOnDispatchKeyEventListener(this);
mWindowManager = (WindowManager) activity.getSystemService(WINDOW_SERVICE);
createWindowParams(true);
mWindowManager.addView(mYouTubePlayerLayout, mWindowParams);
I understand that I need to get permissions from the user for 23 version and above, so I'm asking the user for the permission with this code:
if (Build.VERSION.SDK_INT >= 23 && !Settings.canDrawOverlays(this)) {
isAppPlayStorePermission = true;
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setCancelable(false);
dialog.setIcon(R.drawable.ic_launcher);
dialog.setTitle(R.string.dialog_need_playstore_permissions_title);
dialog.setMessage(R.string.dialog_need_playstore_permissions_description);
dialog.setPositiveButton(R.string.button_exit, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
AndroidUtils.exitApp(activity);
}
});
dialog.setNegativeButton(R.string.button_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 0);
}
});
dialog.show();
}
but now I'm getting a crash from Fabric:
Fatal Exception: java.lang.RuntimeException
Unable to create service ***: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W#c7450fc -- permission denied for this window type
The crash is only for users with Android OS of 7 and below.
Any idea what is the problem?
I am creating a code that checks for the current location, however, when I check for the current location, it crashes. I looked into Stack Trace and saw this. I read other forums but I am not familiar with their solutions. I am also a beginner in Java. I used an Amazon Fire Tablet to download this app. When I tried testing it on the emulator, the app did not crash.
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.settings.LOCALE_SETTINGS }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1797)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:3761)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:3722)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:4032)
at android.app.Activity.startActivity(Activity.java:4000)
at com.example.calculatorandlocationfinderfinal.MainActivity$7.onClick(MainActivity.java:181)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5491)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:984)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Below is the code where it happened.
private void onGPS() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCALE_SETTINGS));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
Always use this method to start intents other than your app's -
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
if(intent.resolveActivity(context.getPackageManager()) != null){
startActivity(intent);
}else{
//handle activity not found
}
this way you won't get ActivityNotFoundException.
You can also use try catch as -
try {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
} catch (e: ActivityNotFoundException) {
//handle activity not found
}
I suppose you want to navigate to GPS settings screen.
try this.
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
The phone/device might be missing locale settings screen altogether which leads to the crash.
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //This line solve my issue
startActivity(viewIntent);
I am trying to get URL from string using JAVA. but my variable not working in "Uri.parse" section (no value in variable). please consider i am beginner in coding
Error is : " Cannot assign a value to final variable 'result' "
My code:
showResultDialogue(result.getContents());
..
public void showResultDialogue(final String result) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
Pattern p = Pattern.compile("[\\w\\.]+\\.(?:com|cc|net|ru|in)[^,\\s]*");
Matcher m = p.matcher(result);
builder.setTitle("Example Title")
.setMessage("Text is " + result);
if(m.matches()) {
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(result) // here is problem
);
startActivity(browserIntent);
}
});
}
Since you have provided no information of why it does not work, I am just gonna assume the URL is missing http since you're regex does not match that, in that case I would just do this
Edit: do you really need your regex? Android has a built in way of matching URLS.
You can find the docs here https://developer.android.com/reference/android/util/Patterns
Patterns.WEB_URL.matcher(result).matches();
so your code is gonna look like this
if (Patterns.WEB_URL.matcher(result).matches()) {
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(!result.startsWith("http://") && !result.startsWith("https://") ? "http://" + result : result)
);
startActivity(browserIntent);
}
});
}
I don't know if this question was asked, but I couldn't find it.
I want alert dialog to show every 10 or more times app is launched.
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity.this);
a_builder.setMessage("Please take time and rate our application")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
}
}
}).setNegativeButton("Not Now",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}) ;
AlertDialog alert = a_builder.create();
alert.setTitle("Rate Us !");
alert.show();
Set a sharedPreferences and increment the count every time by the value stored in it. When the values reaches the count, Just show alert and reset the sharedpreferences.
You can store an integer value in the shared preference to keep count of how many times your app has been launched.
You can increment the value in OnCreate() method of launch activity or in any other activity that is an entry point to your app(like from notification).
You should reset the value after displaying the dialog every time.
Here's a small piece of code -
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
int appLaunchCount = pref.getInt("appLaunchCount",-1);
if(appLaunchCount==10){
// code to show dialog
// reset
appLaunchCount=0;
} else {
// increment count
appLaunchCount = appLaunchCount+1;
}
SharedPreferences.Editor editor = pref.edit();
editor.putInt("appLaunchCount", appLaunchCount);
editor.apply();
int count=0;
int prefcount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count++;
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit=pref.edit();
edit.putInt("Count",count);
edit.commit();
prefcount=pref.getInt("Count",-1);
if(prefcount>10){
//show dialog
}
}
}
Hope this will help you.
You can store open count in SharedPreferences
add counter on oncreate activity.
restoredCount ++
editor1.putInt("name", restoredCount);
editor1.commit();
// Get Counter Values
SharedPreferences prefs = getSharedPreferences("user_count", MODE_PRIVATE);
SharedPreferences.Editor editor1 = getSharedPreferences("user_count", MODE_PRIVATE).edit();
int restoredCount = prefs.getInt("name", 0);
if (restoredCount == 10) {
editor1.putInt("name", 0);
editor1.commit();
// Here Show Alert Dialog.
}
I Hope this example is help you.
My code is:
View.OnClickListener menuHandle = new View.OnClickListener() {
public void onClick(View v) {
//inflate menu
final String [] items = new String[] {"Rate This App", "Quit"};
final Integer[] icons = new Integer[] {R.drawable.star, R.drawable.quit};
ListAdapter adapter = new ArrayAdapterWithIcon(MainActivity.this, items, icons);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item ) {
//Toast.makeText(MainActivity.this, "Item Selected: " + item, Toast.LENGTH_SHORT).show();
switch (item) {
case 0:
//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent.setData(Uri.parse("market://details?id=com.test.testing"));
if (MyStartActivity(intent) == false) {
//Market (Google play) app seems not installed, let's try to open a web browser
intent.setData(Uri.parse("https://play.google.com/store/apps/details?com.test.testing"));
if (MyStartActivity(intent) == false) {
//Well if this also fails, we have run out of options, inform the user.
//let the user know nothing was successful
}
}
break;
case 1:
finish();
break;
default:
//do nothing
}
}
});
AlertDialog alert = builder.create();
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alert.getWindow().setGravity(Gravity.BOTTOM);
alert.show();
}
};
I get the following error:
The constructor AlertDialog.Builder(MainActivity, int) is undefined
What do I have to modify to get rid of the error?
Note: My MainActivity class extends Activity and DialogSlideAnim as been initialized in the res/values/styles.xml file
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim) will work only on API level 11 and above.
If you are targeting all the platforms then use following.
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim))
try
new AlertDialog.Builder(v.getContext(), R.style.DialogSlideAnim)
instead of
new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
I think its because the AlertDialog.Builder is inside a inner class(menuHandle.setOnClickListener), try changing to: new AlertDialog.Builder(TheNameOfYourClass.this,R.style.DialogSlideAnim);
Like this way :
public void onClick(View v) {
new AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim);
^^^
....
}
Try to set the Style in your AlertDialog as below:
new AlertDialog.Builder(
new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim)