I have a web social network (located on a webserver) which has an API, and I'm trying to develop an adroid app for it. Now I've already can sign (send 'user and pass' and authenticate) on t开发者_运维技巧his API. For this I have a method sendLogin(String user,String pass) that returns me a user object.
My question is:
After this steps, I wanna go to other screen(main menu, for example). How is the best way to persist the user obect on my app?
For example:
- Login screen: sign in on API
- API: athenticate data
- Login screen: create a user object
- Login screen: calls the main Menu
- User: wanna see her data (name,email, gender, age)
- Profile screen: show this data
The user object was created on Login.java but it should persist on many screen (all application's life cycle).
I've used this. But with this solution I'll do this in many place, I will terrible to change and maintain.
public void loginSucceed(User user){
Intent intent = new Intent();
intent.setClass(Login.this, MainMenu.class);
//passa parametros de uma activity pra outra
intent.putExtra("id",user.getId());
intent.putExtra("user",user.getUsername());
intent.putExtra("email",user.getEmail());
startActivity(intent);
}
I there a best way?
Intents are a good way for this but if you don't want to use that you can override the Application class and put the user class in there so you can retrieve it in any activity.
Looking at your intent code your user class doesn't implement parcelable as you are retrieving it field by field. If you make the class implement parcelable you just can do intent.putParcelable(group)
http://developer.android.com/reference/android/os/Parcelable.html
This might be one way to do it. Store an HttpContext in the application object and as you go from activity to activity and need to access your social website, you can access the cookies stored in CookieStore (in the application object associated with the HttpContext) and use that to access your website.
Here is some code on using HttpContext
Read this thread on creating and working with the Application object
Android Application Object
This is very similar to what you'd be doing with a web application so you can transfer your web knowledge to this problem.
The best way to keep your application light weighted and dynamic you should use java beans
class CommonBean implements Serializable
{
String name,gender;
int age;
// generate getter and setter for the variables.
}
精彩评论