【问题标题】:Illegal access exception while sharing Global data共享全局数据时出现非法访问异常
【发布时间】:2012-03-22 02:11:16
【问题描述】:

我想跨活动分享全球数据,我已经关注了

this link

。但我不知道如何在我的清单中声明它。我正在发布我的清单代码,我以不同的方式尝试过,但仍然出现错误。请告诉我如何解决它。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.helloandroid"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />

<application android:icon="@drawable/icon" android:label="@string/app_name"
     android:name=".Myapp">
    <activity android:name=".AndroidtestActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

这是我的主要活动

公共类 AndroidtestActivity 扩展 Activity
{

    /** Called when the activity is first created. */


  public static final String PREFS_NAME = "MyPrefsFile";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    EditText et = (EditText) findViewById(R.id.text1);

    Myapp appState = ((Myapp)getApplicationContext());

   String s= appState.getState();


    et.setText(s);


}

}

我的 Myapp 课程是

类 Myapp 扩展应用程序 {

  private String myState;

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

我在行中遇到错误 Myapp appState = ((Myapp)getApplicationContext());

非法访问异常,请告诉我如何解决这个问题

请帮帮我。

【问题讨论】:

  • 你真正想做的,我想跨活动共享全球数据。你能更具体地分享你想分享的内容吗
  • 我想在活动之间共享一个字符串变量,为此我正在使用上面的链接,但我仍然不知道如何准确地声明它。那是我的问题
  • 你想做什么发布你的代码,这样回复会很快。
  • 请有人帮我解决这个问题。我需要它尽快
  • 我发现了错误,我必须使用 Public Myapp extends application 是我的错,我没有这样做。

标签: android


【解决方案1】:

合并应用程序标签(即将 android:name 放在第一个并删除其余部分):

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

    <activity android:name=".AndroidtestActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


</application>

然后使用getApplication() 而不是getApplicationContext()

【讨论】:

  • 感谢您的帮助 stefan,但我仍然遇到非法类访问异常。我该如何解决它,请告诉我。请看我编辑的清单帖子
  • Myapp appState = ((Myapp)getApplication()); // 不是 ... getApplicationContext()!
猜你喜欢
  • 2011-09-29
  • 2012-11-03
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
相关资源
最近更新 更多