値をグローバル変数として保存するには、Application クラスを使用できると読みました。メインアクティビティからユーザー名とパスワードを取得し、それらをアプリケーションクラス変数に保存して新しいアクティビティを開始し、新しいアクティビティで開始されたサービス内でこれらの値をフェッチするつもりですが、定義したゲッターメソッドを使用するとnull値が得られます私のアプリケーションクラスで。
私のアプリケーションクラス:
public class MyApp extends Application
{
private String uid;
private String upwd;
@Override
public void onCreate()
{
super.onCreate();
}
public void setUID(String value)
{
uid = value;
}
public void setPWD(String value)
{
upwd = value;
}
public String getUID()
{
return uid;
}
public String getPWD()
{
return upwd;
}
}
私の主な活動では:
public void setvalues()
{
unameval = Unametxtfield.getText().toString();
pswrdval = Pswrdtxtfield.getText().toString();
((MyApp)this.getApplicationContext()).setUID(unameval);
((MyApp)this.getApplicationContext()).setPWD(pswrdval);
}
サービス内での私の 2 番目のアクティビティ:
public void fetchvalues()
{
String uname = ((MyApp).getApplicationContext()).getUID();
String upswrd = ((MyApp).getApplicationContext()).getPWD();
}
Android マニフェスト:
<application
android:name="MyApp"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!-- A Service here -->
<service
android:name="Service1"
android:process=":myapp_service1" >
</service>
<!-- A service in which I do the fetching of uname and pswd -->
<service
android:name="Service2"
android:process=":myapp_Service2" >
</service>
<activity
android:name=".Second_Activity"
android:exported="false"
android:label="@string/activityname" >
<intent-filter>
<action android:name="android.intent.action.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="@string/Firstactivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
注:アプリケーションクラスを複数のプロセスで使用している場合(私がやっていると思います)、アプリケーションクラスが機能しないことをどこかで読みましたが、これは本当ですか?