我试图通过在 android.app.Application 中创建一个子类来在我的应用程序中创建全局变量。我已经按照互联网上的一些教程,但我似乎无法让它工作。Eclipse 没有给我任何错误,但是当我启动应用程序时出现以下错误:不幸的是,应用程序已停止。
另一个人在Stackoverflow上问了同样的问题,但这个解决方案似乎对我不起作用。
这是我的应用程序文件,任何帮助将不胜感激!
MainActivity.java
package com.app.app;
import org.apache.http.cookie.Cookie;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView mTxtvName;
String cookie;
String username;
Cookie theRealCookie;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overzichttablayout);
mTxtvName = (TextView) findViewById(R.id.txtvName);
Globals global = (Globals)getApplication();
String username = global.getVariable("globUsername");
String cookie = global.getVariable("globCookie");
mTxtvName.setText(username);
}
}
Globals.java
package com.app.app;
import android.app.Application;
public class Globals extends Application {
private String globCookie = "null";
private String globUsername = "null";
public String getVariable(String someName) {
if(someName == "globCookie")
{
return globCookie;
}
else if(someName == "globUsername")
{
return globUsername;
}
else
{
return null;
}
}
public void setVariable(String someName, String someVariable) {
if(someName == "globCookie")
{
this.globCookie = someVariable;
}
else if(someName == "globUsername")
{
this.globUsername = someVariable;
}
}
}
应用清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="11" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Light.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="OverviewActivity" android:theme="@android:style/Theme.Light.NoTitleBar"></activity>
</application>
<application android:name="Globals" android:icon="@drawable/ic_launcher" android:label="@string/app_name" />
</manifest>
原木猫(缩短)
08:51:53.783: D/AndroidRuntime(1650): Shutting down VM
08:51:53.783: W/dalvikvm(1650): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
08:51:53.863: E/AndroidRuntime(1650): FATAL EXCEPTION: main