我想通過在android.app.Application中創建一個子類在我的應用程序中創建全局變量。我在互聯網上跟着一些教程,但我似乎無法得到它的工作。 Eclipse不給我任何錯誤,但是當我啓動應用程序時,出現以下錯誤:不幸的是,應用程序已停止。Android - 全局變量 - 應用程序錯誤
另一個人對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>
登錄貓(shortend)
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
盡我所知,它並不真正涉及到你的問題......你確定你想這樣做嗎?代碼中有幾個相當大的漏洞,其中包括通過發送一個字符串作爲參數來獲取變量。此外,讓本地和全局範圍的變量具有相同的名稱(您是否意識到,只要您爲其指定值,Cookie就會超出範圍?) – HaemEternal