Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android全局变量getApplicationContext和ClassCastException_Android_Variables_Global_Classcastexception - Fatal编程技术网

android全局变量getApplicationContext和ClassCastException

android全局变量getApplicationContext和ClassCastException,android,variables,global,classcastexception,Android,Variables,Global,Classcastexception,按照Stack Overflow问答的建议,我创建了一个类(常量),并尝试声明它并将其用作全局变量,但它未能强制转换,无法找到关于此问题的任何好答案,我尝试在清单文件中定义“常量”或“.Constant”,但任何定义都不起作用 请帮帮我 Constant con = ((Constant)getApplicationContext()); // failed to cast here con.setClientid(Integer.parseInt(clientid)); import an

按照Stack Overflow问答的建议,我创建了一个类(常量),并尝试声明它并将其用作全局变量,但它未能强制转换,无法找到关于此问题的任何好答案,我尝试在清单文件中定义“常量”或“.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">


用getApplication()替换getApplicationContext(),您应该能够强制转换一个类扩展应用程序。

正确的Syntax应该是常量con=(常量)this.getApplication();在你的活动中。

我知道我在回复一篇旧帖子, 但仅仅是对于那些仍然面临类似问题的人来说

我认为他的问题是他的一部分

<application android:name=".Constant" android:icon="@drawable/icon">

我的问题是通过包含类的整个特定路径而不是“.Constant”来解决的。
例如,“com.example.Constant”

您试图将类型为Context的getApplicationContext强制转换为类型为Application的常量类。它不能从一个转换到另一个。我尝试了不同的组合,getApplicationContext或getApplication(),删除(),将名称从“.Constant”更改为“Constant”,但仍然存在相同的问题。它肯定是getApplication()。关于舱单声明。尝试通过清单接口声明它。可能你没有正确申报。除了使用getApplication()方法外,您的代码还可以。唯一剩下的就是将其正确地声明到清单中。
<application android:name=".Constant" android:icon="@drawable/icon">