android - 全局变量类不起作用

标签 android

我正在尝试设置和全局变量,但在将以下行添加到我的 AndroidManifest.xml 后,我的应用程序失败了

<application android:name=".MyApp"
              android:icon="@drawable/icon" 
              android:label="@string/app_name">

我也使用以下代码:

类别: 包 com.mynamecompany.datahelp;

import android.app.Application;

class MyApp extends Application {

      private String myState;

      public String getState(){
        return myState;
      }
      public void setState(String s){
        myState = s;
      }
    }

用法:

MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
Toast.makeText(getApplicationContext(), "My Value-" + state, Toast.LENGTH_SHORT).show();
appState.setState("Test");
Toast.makeText(getApplicationContext(), "My Value-" + appState.getState(), Toast.LENGTH_SHORT).show();

程序启动并立即在启动屏幕上出现错误,然后才能在程序中的不同 Activity 上进一步调用使用代码。

有什么想法吗?

最佳答案

您正在尝试从 Context 转换到您的类(class)。您必须调用getApplication .

关于android - 全局变量类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3494265/

相关文章:

java - 错误: “Method getText() must be called from the UI thread, currently inferred thread is worker.”

android - 通过在 qt 中从 C++ JNI 发送字符串在 Android 中显示 Toast

android - GetMaxAmplitude 的取值范围

android - 警告/Activity 管理器 (5038) : Permission denied: checkComponentPermission

android - 在Android中的数据库中一次保存多个数据

android - Android 7.0 不支持通话录音问题?

android - 在 Canvas 上平铺位图

java - 过滤数组中的差异

android - android中的语言支持

android - 模拟器 : emulator: ERROR: Missing initial data partition file: