我正在尝试在Android项目中进行登录验证。我想将cookie从活动传递给activity.To传递cookie,我创建了一个应用程序类。这是应用程序类;
public class TestApplication extends Application{
public Cookie tempClass;
public TestApplication () {
// TODO Auto-generated constructor stub
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
public Cookie getTempClass() {
return tempClass;
}
public void setTempClass(Cookie tempClass) {
this.tempClass = tempClass;
}
}
我试图在这里的活动中使用;
public void run() {
// TODO Auto-generated method stub
//String sessionId="";
Cookie userCookie=null;
List<Cookie> cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
//System.out.println("-Cokkkiiieee " + cookies.get(i).toString());
userCookie =cookies.get(i);
}
testAppObj = (TestApplication)getApplication();
testAppObj.setTempClass(userCookie);
Intent menu = new Intent("android.intent.action.MENU");
startActivity(menu);
}
}
};
(new Thread(runnable)).start();
显示LogCat:
FATAL EXCEPTİON : Thread-9
java.lang.ClassCastException : android.app.Application
at com.example.example.MainActivity$2.run(MainActivity.java:176)
at java.lang.Thread.Run(Thread.java:1096)
答案 0 :(得分:0)
您可以使用Application类跨多个活动访问同一个对象。
public class TestApplication extends Application {
//Object declaration
public TestApplication () {
// TODO Auto-generated constructor stub
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
//setter getter for object
}
现在进入您的活动:
//after setContentView
TestApplication testAppObj = (TestApplication) getApplication();
testAppObj.setSomeObj(myObj);
//retrieve as:
someObj = testAppObj.getterMethodOfObj();
希望这有帮助。
P.S:
您必须在清单文件中注册Application类,就像注册活动一样:
<application
android:name="com.pkg.test.TestApplication " />