Answer the question
In order to leave comments, you need to log in
android how to save state properly?
I dealt with a test project from the course on Android development from e-legion, the lesson itself - https://www.youtube.com/watch?v=cH9UxmZwGO4 , the project from the speaker (Dmitry Kalita) - https://github.com/ rusmonster/signin.
The structure looks like this:
MainActivity.java:
public class SignInActivity extends Activity implements SignInModel.Observer {
private SignInModel mSignInModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
mSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
mSignInModel.signIn(userName, password);
}
});
//Восстановление SignInModel
mSignInModel.registerObserver(this);
}
@Override
protected void onDestroy() {
mSignInModel.unregisterObserver(this);
if (isFinishing()) {
mSignInModel.stopSignIn();
}
}
@Override
public void onSignInStarted(final SignInModel signInModel) {
}
@Override
public void onSignInSucceeded(final SignInModel signInModel) {
}
@Override
public void onSignInFailed(final SignInModel signInModel) {
}
}
public class SignInModel {
private final SignInObservable mObservable = new SignInObservable();
public void signIn(final String userName, final String password) {
if (mIsWorking) {
return;
}
mObservable.notifyStarted();
}
public void registerObserver(final Observer observer) {
mObservable.registerObserver(observer);
if (mIsWorking) {
observer.onSignInStarted(this);
}
}
public void unregisterObserver(final Observer observer) {
mObservable.unregisterObserver(observer);
}
private class SignInObservable extends Observable<Observer> {
public void notifyStarted() {
for (final Observer observer : mObservers) {
observer.onSignInStarted(SignInModel.this);
}
}
public void notifySucceeded() {
for (final Observer observer : mObservers) {
observer.onSignInSucceeded(SignInModel.this);
}
}
public void notifyFailed() {
for (final Observer observer : mObservers) {
observer.onSignInFailed(SignInModel.this);
}
}
}
}
Answer the question
In order to leave comments, you need to log in
It is not necessary to store data of different entities in one model, and there is nothing wrong with using several models in one activity. In the end, you can have a complex ui where each view is represented by a specific data model. But it’s not worth duplicating the code either, try to analyze what the models have in common, and somehow group them through inheritance or composition.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question