gpt4 book ai didi

android - 如何修复 Android Studio 中的 android 按钮,抛出强制转换异常?

转载 作者:行者123 更新时间:2023-11-29 19:12:36 25 4
gpt4 key购买 nike

我的应用程序运行良好,直到我开始单击一个特定按钮,即 rate-button。每次单击此按钮时,应用程序都会崩溃,并且我会在 log cat 中收到此消息:

22808/com.nileworx.guesstheplace E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nileworx.guesstheplace, PID: 22808
java.lang.ClassCastException: com.nileworx.guesstheplace.GameActivity cannot be cast to com.nileworx.guesstheplace.MainActivity
at com.nileworx.guesstheplace.CustomDialog$11.onClick(CustomDialog.java:283)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-25 06:46:03.423 1642-2032/system_process W/ActivityManager: Force finishing activity com.nileworx.guesstheplace/.GameActivity

我认为 gameactivity 有问题,只有一个错误:

@Override
protected void onResume() {
super.onResume();

if (!mSharedPreferences.getString("placesNum", "0").equals("0")) {
String updatesDlgMsg = String.format(getResources().getString(R.string.updatesDlg), mSharedPreferences.getString("placesNum", "0"));
dialog.showDialog(R.layout.blue_dialog, "updatesDlg", updatesDlgMsg, mSharedPreferences.getString("placesJSON", ""));
e.putString("placesNum", "0");
e.commit();
}
}

第 6 行代码,出现以下消息的问题:

Format string 'updatesDlg' is not a valid format string so it should not be passed to String.format less... (Ctrl+F1) If a string contains a '%' character, then the string may be a formatting string which will be passed to String.format from Java code to replace each '%' occurrence with specific values. This lint warning checks for two related problems: (1) Formatting strings that are invalid, meaning that String.format will throw exceptions at runtime when attempting to use the format string. (2) Strings containing '%' that are not formatting strings getting passed to a String.format call. In this case the '%' will need to be escaped as '%%'. NOTE: Not all Strings which look like formatting strings are intended for use by String.format; for example, they may contain date formats intended for android.text.format.Time#format(). Lint cannot always figure out that a String is a date format, so you may get false warnings in those scenarios. See the suppress help topic for information on how to suppress errors in that case

我不知道如何解决这个问题,我已经尝试了 2 个多小时来解决它。

我的费率按钮代码

private void rateDlg(final Dialog dialog, final String marketLink) {

Button rateBtn = (Button) dialog.findViewById(R.id.rateBtn);
// if button is clicked, close the custom dialog
rateBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sou.playSound(R.raw.buttons);
dialog.dismiss();
MainActivity mainAct = (MainActivity) context;
Intent intent = new Intent(Intent.ACTION_VIEW);



intent.setData(Uri.parse("playstorelink, changed for stackoverflow"));

if (!mainAct.MyStartActivity(intent)) {
// Market (Google play) app seems not
// installed, let's try
// to open a webbrowser
intent.setData(Uri.parse("playstorelink, changed for stackoverflow"));
if (!mainAct.MyStartActivity(intent)) {
// Well if this also fails, we have run
// out of options,
// inform the user.
Toast.makeText(context, "Could not open Android market, please install the market app.", Toast.LENGTH_SHORT).show();
} else {
editor.putInt("usingNum", 100);
editor.commit();
}
} else {
editor.putInt("usingNum", 100);
editor.commit();
}
}
});

Button laterBtn = (Button) dialog.findViewById(R.id.laterBtn);
// if button is clicked, close the custom dialog
laterBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sou.playSound(R.raw.buttons);
editor.putInt("usingNum", 0);
editor.commit();
dialog.dismiss();
}
});
}

最佳答案

首先检查字符串资源文件中是否存在 R.string.updatesDlg

您的另一个问题是由于错误 GameActivity cannot be cast to com.nileworx.guesstheplace.MainActivity 中所述的错误转换造成的,您正在尝试将一个类转换为另一个类。您的按钮对话框代码显示此处...

MainActivity mainAct = (MainActivity) context;

我很确定 context 在这种情况下不是 MainActivity 类型。检查 context 的类型。错误表明它是 GameActivity 类型。

话虽如此,我不明白您为什么需要访问 MainActivity,除非那里发生了特殊情况。您可以创建一个 Helper 类并包含一个方法来检查是否已安装包。您在 Activity 的上下文中传递。像这样:

//MainActivity mainAct = (MainActivity) context;
//Intent intent = new Intent(Intent.ACTION_VIEW);
//intent.setData(Uri.parse("playstorelink, changed for stackoverflow"));

if (!isPackageInstalled(playstorelink)) {
// Market (Google play) app seems not
// installed, let's try
// to open a webbrowser
//intent.setData(Uri.parse("playstorelink, changed for stackoverflow"));
if (!isPackageInstalled(playstorelink)) {
Toast.makeText(context, "Could not open Android market, please install the market app.", Toast.LENGTH_SHORT).show();
} else {
editor.putInt("usingNum", 100);
editor.commit();
}
} else {
editor.putInt("usingNum", 100);
editor.commit();
}

private boolean isPackageInstalled(Context context, String packagename) {
try {
context.packageManager.getPackageInfo(packagename, 0);
return true;
} catch (NameNotFoundException e) {
return false;
}
}

附带说明一下,这行代码让我相信您已将 Activity 的实例保存到静态变量中:

if (!mainAct.MyStartActivity(intent)) {

这太糟糕了!我会引用这个answer -

Don't store the Context in a hard reference, ever. Or you will leak memory. An activity has references to View and a multitude of other things. If you store the Context, you're storing the activity and things go bad from there. Learn to pass the Context around, use the Application Context whenever possible and if you need to pass it around, do it for very good reasons. Most of the time the App context is enough for getting resources, strings, etc. If you're going to store the Context, always store context.getApplicationContext(); Never store a static activity context. You can google this too and StackOverflow has some good answers.

您可以使用事件系统库,例如EventBus,而不是将上下文存储在静态变量中。在 Activity/fragment 之间进行通信。您还可以将上下文从一个地方传递到另一个地方或使用 Intent putExtras 将数据添加到 Intent ,然后在另一个 Activity/对话中接收它......

关于android - 如何修复 Android Studio 中的 android 按钮,抛出强制转换异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44761495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com