I am newbie in Java and Android programming. I just created simple app with login form and registration form. My login form and registration form works right now. I created abstract SignedActivity class which extends from Activity class. I want each activity which is available after login inherits from SignedActivity. If activity inherits from SignedActivity I can be sure that it is available only for signed users.
This is how SignedActivity looks:
public abstract class SignedActivity extends Activity {
public static String LOG_OUT_PATH = "/logOut.php";
private String sessionId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String newSessionId = savedInstanceState.getString("sessionId");
if (newSessionId instanceof String) {
sessionId = newSessionId;
return;
}
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
String newSessionId = extras.getString("sessionId");
if (newSessionId instanceof String) {
sessionId = newSessionId;
return;
}
}
finish();
}
public void startSignedActivity(Intent intent) {
intent.putExtra("sessionId", getSessionId());
this.startActivity(intent);
}
protected String getSessionId() {
return sessionId;
}
private void setSessionId(String newSessionId) {
sessionId = newSessionId;
}
protected void logOut() {
new RequestLogOutTask().execute(SignedActivity.LOG_OUT_PATH);
setSessionId("");
Intent intent = new Intent(this, SignInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("logOut", true);
startActivity(intent);
}
public void onClickLogOut(View v) {
logOut();
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("sessionId", sessionId);
super.onSaveInstanceState(savedInstanceState);
}
class RequestLogOutTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... params) {
(new RESTClient(Constants.REST_URL)).post(params[0], "");
return null;
}
}
}
My problem is that I sometimes need FragmentActivity instead of Activity after login. So I have to create SignedFragmentActivity which extends from FragmentActivity and it is basically the same as SignedActivity (only parent is different). So I have duplicate code - how to avoid it ?
You can move your
SignedActivity
code toActivityHelper
class:Now you can use it in every
Activity
instance (i.e.FragmentActivity
):