android 全局变量,getApplicationContext 与 ClassCastException
按照Stack Overflow问答的建议,我创建了一个类(常量),并尝试声明并使用它作为全局变量,但它无法转换,找不到这个问题的任何好的答案,我尝试定义无论是清单文件中的“Constant”还是“.Constant”,这些定义都不起作用。
请帮帮我。
Constant con = ((Constant)getApplicationContext()); // failed to cast here
con.setClientid(Integer.parseInt(clientid));
import android.app.Application;
public class Constant extends Application {
private int gClientid;
public int getClientid() { return gClientid; }
public void setClientid(int cid) { gClientid = cid; }
}
显现
<application android:name=".Constant" android:icon="@drawable/icon">
Follow the advice from Stack Overflow question and answer, I create a class (Constant), and try to declare and use it as the global variable, but it failed to cast, can not find any good answer for this issue, I tried to define either "Constant" or ".Constant" in Manifest file, none of the definition works.
Please help me out.
Constant con = ((Constant)getApplicationContext()); // failed to cast here
con.setClientid(Integer.parseInt(clientid));
import android.app.Application;
public class Constant extends Application {
private int gClientid;
public int getClientid() { return gClientid; }
public void setClientid(int cid) { gClientid = cid; }
}
Manifest
<application android:name=".Constant" android:icon="@drawable/icon">
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正确的语法应该是 Constant con = (Constant) this.getApplication();在你的活动中。
The correct synthax should be Constant con = (Constant) this.getApplication(); inside your activity.
将 getApplicationContext() 替换为 getApplication(),您应该能够转换扩展应用程序的类。
Replace getApplicationContext() with getApplication() and you should be able to cast a class extending application.
我知道我正在回复旧帖子
但只是为了那些仍然遇到类似问题的人。
我认为他的问题是我的问题的一部分
是通过包含类的整个特定路径而不是“.Constant”来解决的。
前任。 “com.example.常量”
I know I'm answering to a old post,
but just for the people still getting similar problem.
I think his problem is the part of
My problem is solved by including whole specific path to the class instead of ".Constant".
ex. "com.example.Constant"