How can I use shared preference in android studio to achieve this?
On my app, Splash Screen redirects to Activity A.
There is a button on Activity A, When this button on Activity A is clicked, next time when user opens app, Activity A will not show again, Activity B must open next.
The logic here is, Activity A is my welcome screen, after user clicks get started on this activity, I don't want this Activity to open again. Activity B is my Main Activity
NB: I have checked all questions and answers on stackoverflow, they did not help, the ones available where showing activity only on first run and this not a duplicate question, any help provided is appreciated.
You can store boolean by shared preference to do that. Here your AcitivityA class.
public class ActivityA extends AppCompatActivity {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
try {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firsttimeLoad = prefs.getBoolean("first_time_load", true);
if (!firsttimeLoad) {
sendToB();
}
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time_load", false);
editor.commit();
sendToB();
}
});
}
private void sendToB() {
Intent mainIntent = new Intent(ActivityA.this, ActivityB.class);
startActivity(mainIntent);
finish();
}}
This is the code im using for save the sigin details from firebase you can check this out and try this
private fun handleSignInResult(task: Task<GoogleSignInAccount>?) {
try {
if (task!!.isSuccessful) {
val account = task.getResult(ApiException::class.java)
PreferenceHelper.writeBooleanToPreference(KEY_LOGIN_WITH_OAUTH, true)
updatePreference(account!!)
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("UserName", account.displayName)
intent.putExtra("UserEmail", account.email)
intent.putExtra("UserPhoto", account.photoUrl?.toString())
intent.putExtra("uid", account.id)
saveUser(account)
startActivity(intent)
finish()
} else {
Toast.makeText(
this,
"Login Error " + task.exception?.message,
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
}
}
private fun updatePreference(account: GoogleSignInAccount) {
PreferenceHelper.writeBooleanToPreference(KEY_USER_LOGGED_IN, true)
PreferenceHelper.writeStringToPreference(KEY_USER_GOOGLE_ID, account.id)
PreferenceHelper.writeStringToPreference(
KEY_DISPLAY_NAME,
account.displayName
)
PreferenceHelper.writeStringToPreference(
KEY_USER_GOOGLE_GMAIL,
account.email
)
}
When the user selects the button on Activity A, add a value to the shared preferences. What the value is does not really matter. Every time your app is launched, check if this value exists in the shared preferences, if it does launch Activity B, if it doesn't, launch Activiy A.
In onCreate of Activity A
SharedPreferences sharedPref = MainActivity.this.getPreferences(Context.MODE_PRIVATE);
if (sharedPref.contains("notFirstLaunch")) {
// Launch Activity B
}
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("notFirstLaunch", true);
editor.apply();
}
});
Related
I want when the user start the app for the first time, a dialog appears to tell the user that the application will collect some data about his/her usage, and if he/she press accept, the main activity starts, and never ask the user again.
let's break your problem to smaller ones. You will need to activities: MainActivity and PermissionsActivity (add a button with id 'yes' and a button with id 'no'.
A) Launch an activity just one time. We will do so using SharedPreferences and storing a boolean which, if true, means that the dialogue had been previously shown and, otherwise, that it has not been shown.
// In MainActivity.class
String MY_PREFS_NAME = "my_prefs"; // can be changed, but it must be done so everywhere
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Boolean bool = prefs.getBoolean("hasbeenshown", false);
if (!bool){
// Go to the request dialogue activity
Intent myIntent = new Intent(MainActivity.this, PermissionsActivity.class);
startActivity(myIntent);
}
// otherwise, if bool = true, activity has been shown and there is no need to redirect
B) If the user answers, redirect to MainActivity and store the answer.
// In PermissionsActivity.class
String MY_PREFS_NAME = "my_prefs"; // can be changed, but it must be done so everywhere
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
Button yes = (Button) findViewById(R.id.button1);
yes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Do stuff when they accept
// ...
// Store the answer
store(true); // true means that user said yes
}
});
Button no = (Button) findViewById(R.id.button1);
no.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Do stuff when they !accept
// ...
// Store the answer
store(false); // false means that user said no
}
});
void store(Boolean answer){
// Store the answer
editor.putBoolean("answer", answer);
// Don't show the message again
editor.putBoolean("hasbeenshown", true);
// Store the previous edits
editor.commit();
// Redirect to MainActivity
Intent myIntent = new Intent(PermissionsActivity.this, MainActivity.class);
startActivity(myIntent);
}
C) APPENDIX: You can always get what the user answered from any activity with the following code.
String MY_PREFS_NAME = "my_prefs"; // can be changed, but it must be done so everywhere
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Boolean yesorno = prefs.getBoolean("answer", false); // false will be returned if user didn't answer or answered no; true will be returned if user answered yes
In my application I have a booking system which allows users to book tee times for specific times during the day. When a booking has been completed the details are saved to my Firebase and the user can then close the alert dialog. When the alert dialog is then closed the button which was clicked is then made unusable. Problem is that when the user leaves the booking activity and comes back the button is then useable, and if a different user then accesses the page the button is also able to be clicked as well.
How do I solve this problem?
Should I be saving the UID of the user in the 9am child ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
findViewById(R.id.profilebtn).setOnClickListener(this);
findViewById(R.id.booking9am).setOnClickListener(this);
book9am = (Button)findViewById(R.id.booking9am);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.profilebtn:
finish();
startActivity(new Intent(Booking.this, ProfileActivity.class));
break;
case R.id.booking9am:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(Booking.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_booking,null);
final EditText mPlayer1 = (EditText) mView.findViewById(R.id.player1);
final EditText mPlayer2= (EditText) mView.findViewById(R.id.player2);
final EditText mPlayer3 = (EditText) mView.findViewById(R.id.player3);
final EditText mPlayer4 = (EditText) mView.findViewById(R.id.player4);
final EditText mTime = (EditText) mView.findViewById(R.id.timeedit);
final Button mBookingbtn = (Button) mView.findViewById(R.id.bookingbtn);
mBookingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String player1= mPlayer1.getText().toString().trim();
String player2= mPlayer2.getText().toString().trim();
String player4= mPlayer4.getText().toString().trim();
String player3= mPlayer3.getText().toString().trim();
if (player1.isEmpty()) {
mPlayer1.setError("Please enter player 1");
mPlayer1.requestFocus();
return;
}
if (player2.isEmpty()) {
mPlayer2.setError("Please enter player 2");
mPlayer2.requestFocus();
return;
}
if (player3.isEmpty()) {
mPlayer3.setError("Please enter player 2");
mPlayer3.requestFocus();
return;
}if (player2.isEmpty()) {
mPlayer4.setError("Please enter player 2");
mPlayer4.requestFocus();
return;
}
String playerone = mPlayer1.getText().toString();
String playertwo = mPlayer2.getText().toString();
String playerthree = mPlayer3.getText().toString();
String playerfour = mPlayer4.getText().toString();
String teetime= mTime.getText().toString().trim();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Booking").child("9am");
Map newPost = new HashMap();
newPost.put("playerone",playerone);
newPost.put("playertwo",playertwo);
newPost.put("playerthree",playerthree);
newPost.put("playerfour",playerfour);
newPost.put("teetime",teetime);
current_user_db.setValue(newPost);
Toast.makeText(Booking.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
book9am.setClickable(false);
}
});
mBuilder.setNeutralButton("Close ", new DialogInterface.OnClickListener() { // define the 'Cancel' button
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
}
In your onCreate method -
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Booking").child("9am");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
book9am.setClickable(false);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
well there could be multiple approaches to this problem.
One is to set a Boolean variable in local storage Shared preference against every user....
Once your click the button set the value to true and when u come back in app check if variable is true then disable button..
Second solution Store the varible against every user on firebase and check(recommended since user can change phone)
Before showing the activity you will have to make a request to your firebase to check if the booking has been completed and depending on the result make the button enabled or not.
findViewById(R.id.booking9am).setOnClickListener(this) instead of this use:-
book9am = (Button)findViewById(R.id.booking9am);
book9am.setOnClickListener(this);
and instead of book9am.setClickable(false) set book9am.setEnable(false);
OR
If you want button disable on some conditions then it can be managed at server side also.
There are two approaches to your problem, depending on your needs.
First, is saving the button's state locally (on the client side), which means that after removing and re-installing the app for example, the state will be reset as well.
In order to save the button's state "forever", you should save the wanted state on the device, and this is what SharedPreferences is made for.
This is a good example of using it.
Here is how you should implement it in your code:
public static void set_isButtonClickable(Context ctx, Boolean bool) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean("BUTTON_CLICKABLE_STATE", bool);
editor.commit();
}
public static boolean getPrefIsFirstLaunch(Context ctx) {
return getSharedPreferences(ctx).getBoolean("BUTTON_CLICKABLE_STATE",false);
}
Second, is saving the button's state on the server side. Removing and re-installing the app obviously won't change its state. Make each user a variable which called "button_state" and change it as needed:
I am developing my first networking application and have a small problem which I am unable to find a solution for.
On my startscreen, which is my main activity, there is the option to login. If you login, my login class passes data per intent to my main activity so I can update my UI. This is my main acitivity :
// Just to make sure Loginstatus is false on first run
loginstatus = false;
//Get saved data from SharedPreferences
loginstatus = PreferenceData.getUserLoggedInStatus(this);
Log.d("Loginstatus",""+loginstatus);
if (extras != null) {
login = extras.getString("loginy");
idt = extras.getString("id");
name = extras.getString("name");
vorname = extras.getString("vorname");
email = extras.getString("login");
zsm = vorname + " " + name;
}
else {
// Take saved Data instead the Bundle Data form first Login
idt = PreferenceData.getUSERID(this);
name = PreferenceData.getNachname(this);
vorname = PreferenceData.getVorname(this);
email = PreferenceData.getLoggedInEmailUser(this);
}
Obviously extra is NULL on Startup. If login was successful, my login class passes Data and my main activity is called again, so extras is NOT NULL and I can update my UI with that information.In addition, I save my Data in SharedPrefernces if login was true.
The Problem is, I want to save my login state after completley closing my app. So i reopen my App and I want to use my SharedPrefernces data, but somehow extras is still NOT NULL and I cant find a way to fix that.
This is how I handle login. Hope this is helpfully.
Login Activity
Keep one shared preferences value to check login status which default value set to false;
#Override
protected void onResume() {
super.onResume();
if (sharedpreferences.getBoolean("firstRun", true)) {
initializeDatabase();
sharedpreferences.edit().putBoolean("firstRun", false).apply();
sharedpreferences.edit().putBoolean("attendance", false).apply();
sharedpreferences.edit().putBoolean("loginStatus", false).apply();
}
loginCheck();
}
inside loginCheck() check method redirect to menu activity based on login status.
public void loginCheck(){
if(sharedpreferences.getBoolean("loginStatus", true)){
Intent i = new Intent(this, MainMenuActivity.class);
startActivity(i);
this.finish();
}
}
In case of User haven't log previously, after authenticate user successfully add needed data in to shared preference and change login status shared preference value to true so above explained redirect will happen.
if (message.equals("Login successful")) {
String employeeId = responseBody.getString("employee_id");
int userId = responseBody.getInt("user_id");
String employeeName = responseBody.getString("employee_name");
SharedPreferencesReference.get().edit().putString("employee_id", employeeId).apply();
SharedPreferencesReference.get().edit().putInt("user_id", userId).apply();
SharedPreferencesReference.get().edit().putString("employee_name", employeeName).apply();
SharedPreferencesReference.get().edit().putBoolean("loginStatus", true).apply();
Toasty.success(ActivityWeakReference.get(), message, Toast.LENGTH_SHORT, true).show();
Intent i = new Intent(ActivityWeakReference.get(), MainMenuActivity.class);
ActivityWeakReference.get().startActivity(i);
ActivityWeakReference.get().finish();
}
Menu Activity
In menu activity you should have a logout button which allow users to logout by changing shared preference login status value. In My case I had it as a Menu Item.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
sharedpreferences.edit().putBoolean("loginStatus", false).apply();
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
break;
}
return true;
}
I am implementing an app which have MainActivity , onlyFirstRunActivity and alwaysRunActivity . Now i want that on app installtion or on updation of app my app cycle should be like that:
MainActivity -> onlyFirstRunActivity -> alwaysRunActivity
and after installing or on updation my app cycle should be :
MainActivity -> alwaysRunActivity
How can i implement this situation
You can get the update time for your app and save it in a SharedPreference.
Also, you should just make your main activity the always run one.
//In your onCreate for your main activity/.
if(last_update_preference < current_update_time){
Update last update preference to current update time.
Run first activity. (Which will finish and bounce you back);
}
To get the current_update_time:
How to get app install time from android
For last update time, see:
http://developer.android.com/guide/topics/data/data-storage.html#pref
You can try something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App app = (App)getApplication();
if (app.getApi() != null){
super.onBackPressed();
startActivity(new Intent(this, MainActivity.class));
return;
}else showLoginForm();//or do something else.
}
Like this you can make a difference between a new install and a update.
String StoredVersionname = "";
String VersionName;
AlertDialog LoginDialog;
AlertDialog UpdateDialog;
AlertDialog FirstRunDialog;
SharedPreferences prefs;
public static String getVersionName(Context context, Class cls) {
try {
ComponentName comp = new ComponentName(context, cls);
PackageInfo pinfo = context.getPackageManager().getPackageInfo(
comp.getPackageName(), 0);
return "Version: " + pinfo.versionName;
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
return null;
}
}
public void CheckFirstRun() {
VersionName = MyActivity.getVersionName(this, MyActivity.class);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
StoredVersionname = (prefs.getString("versionname", null));
if (StoredVersionname == null || StoredVersionname.length() == 0){
FirstRunDialog = new FirstRunDialog(this);
FirstRunDialog.show();
}else if (StoredVersionname != VersionName) {
UpdateDialog = new UpdateDialog(this);
UpdateDialog.show();
}
prefs.edit().putString("versionname", VersionName).commit();
}
Update: Thank you all for attempting to help me solve this bug. I am still unsure as to the cause, I was able to roll back to a previous commit and continue development from there. This previous commit did show the same bug, however after I commented out button.performClick() it went away. Strangely, this does not work on the most recent commit.
I still do not understand this bug and would appreciate any more assistance in helping determine the root cause. My greatest fear would be to inadvertently re-introduce it.
I have the most crazy error I have ever seen.
The OnCreate method is being called over and over again, freezing my application and giving me a slight flicker. The only solution is then to exit to the home screen and force quit the application from the settings menu.
Here is what is happening in detail:
Application starts (Main Activity)
Main Activity calls the Second Activity
Second Activity calls onCreate, sets up as normal
Second Activity randomly decides to exit onCreate <-- I think this what's happening
Second Activity's onCreate gets called again. It doesn't ever return to the Main Activity.
I have run a debugger, it appears that the second activity successfully completes the onComplete/onResume sequence, then decides to exit and restart.
Has anybody ever heard of this behavior before?
I haven't noticed any exceptions being thrown. Also, in the course of debugging, I did go ahead and check those locations that you see as silent fail. (this is the older code before I littered it with print statements)
UPDATE: When attempting to stop the process, I must turn on airplane mode. This means it has something to do with this code block (Second Activity)
else if (Network.haveNetworkConnection(Login.getContext()) && Login.checkClientId())
{...}
With no internet, it will hit the else statement and does not display this behavior.
CODE:
onResume() of the Main Activity, where I call the Second Activity:
#Override
public void onResume()
{
super.onResume();
//Check If logged in, else go to login page
Login.setContext(getApplicationContext());
//Reset Notification Number
GCMIntentService.cancelNotifications();
/** GO TO LOGIN **/
if(!Login.isLoggedIn())
{
//If user is not logged in, open login page
System.out.println("RESUMING MAIN AND STARTING LOGIN INTENT");
Intent intent = new Intent(ActivityMain.this, ActivityLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else
{
Login.setupStuffOnce();
Event.pullEvents(); //Get New Events
//Update ListView
updateMainFeed();
}
}
This is the Second Activity:
public class ActivityLogin extends Activity
{
private String postData;
//private Context c;
//final Timer timer = new Timer();
//Facebook Stuff
private Facebook facebook = new Facebook(Config.FBAPPID);
private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
//Layout Stuff
EditText username, password;
Button loginButton, signupButton;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Open Database
Login.setContext(getApplicationContext());
Database.open(getApplicationContext());
}
/*
* #Override public void onPause() { s }
*/
#Override
public void onResume()
{
super.onResume();
// shouldn't put here but oh well
init();
//If coming from ActivitySignup
if(Transfer.username != null)
{
username.setText(Transfer.username);
password.setText(Transfer.password);
Transfer.password = null;
Transfer.username = null;
loginButton.performClick();
}
}
public void init()
{
Login.getUserLoggedIn();
if (Login.isLoggedIn())
{
//Do Any Additional Setup
Login.setupStuffOnce();
// If user is logged in, open main
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else if (Network.haveNetworkConnection(Login.getContext()) && Login.checkClientId())
{
// Else, Make User Login
// Inflate Login and Present Website
String clientid = Login.getClientId();
System.out.println("clientid:" + clientid);
//System.exit(0);
postData = "mobile=1&client_id="+Login.getClientId();
// Inflate the view
setContentView(R.layout.activitylogin3);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
//Inflate the Button
loginButton = (Button) findViewById(R.id.loginButton);
signupButton = (Button) findViewById(R.id.signupButton);
signupButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(ActivityLogin.this, ActivitySignup.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int res = Login.sendLogin(username.getText().toString(), password.getText().toString());
if(res == 202)
{
//Login Successful
//Check if facebooked.
if(Login.isFacebooked())
{
//Just go to main
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
//Are these flags necessary?
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else
{
//Go to facebook login page
//Intent intent = new Intent(ActivityLogin.this, ActivityFBLogin.class);
//startActivity(intent);
//Login via Facebook
doFacebook();
}
} else
{
System.out.println("Login Failed: "+res);
if(res == 405)
{
Toast.makeText(getApplicationContext(), "Incorrect Username/Password", Toast.LENGTH_SHORT).show();
password.setText("");
}
else
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show(); //Not entirely true in all cases i think
}
/*Login.getUserLoggedIn();
if(Login.isLoggedIn())
{
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Please Login Above", Toast.LENGTH_SHORT).show();
}*/
}
});
} else
{
// Not Logged In and No Internet Access
setContentView(R.layout.activitylogintext);
EditText text = (EditText) findViewById(R.id.text);
text.setText("No Internet Connection Detected\n requires internet to login");
Button button = (Button) findViewById(R.id.refreshButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Login.getUserLoggedIn();
if(Network.haveNetworkConnection(Login.getContext()))
{
Intent intent = new Intent(ActivityLogin.this, ActivityLogin.class);
//intent.setFlags();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "No Internet Access Detected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public void doFacebook()
{
facebook.authorize(this, Config.facebookPermissions, new DialogListener() {
#Override
public void onComplete(Bundle values) {
/*SharedPreferences.Editor editor = state.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
*/
//Input into database
Login.saveAccessToken(facebook.getAccessToken());
Login.setFB(facebook.getAccessToken());
//Login.sendAccessToken(facebook.getAccessToken());
//Intent into Main Activity
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Error: "+error.getErrorType(), Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e) {
Toast.makeText(getApplicationContext(), "Error: "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {}
});
}
public boolean checkForUserID(Context c)
{
try{
String res = Network.getUrl("www.website.com/mobile.php?got_user=1&client_id="+Login.getClientId());
JSONObject json = JSON.constructObject(res);
if(JSON.handleCode(json))
{
if(json.getString("type").equals("userid"))
{
Login.setLogin(json.getString("data"));
return true;
}
}
} catch(Exception e)
{
//Silent Fail
}
return false;
}
}
I believe that the problem will be resolved if you finish your MainActivity after you call SecondActivity. The problem probably is that the onResume event is immediatelly fired when you resume your MainActivity. That is because the MainActivity was probably destroyed and recreated while it was in background. Another solution would be to save your Activity's state with onSaveInstanceState. See here for more information.
Check this code in your activity:
Button button = (Button) findViewById(R.id.refreshButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(Network.haveNetworkConnection(Login.getContext()))
{
Intent intent = new Intent(ActivityLogin.this, ActivityLogin.class);
//intent.setFlags();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "No Internet Access Detected", Toast.LENGTH_SHORT).show();
}
}
});
Here you are calling ActivityLogin itself.
That's why the onCreate() is being called again and again.
I had a similar problem once. The problem occurred because I made configuration changes without declaring them in the android:configChanges attribute of the <activity> tag (and hence it recreates itself the whole time).
For example, if you change the locale manually you need to add locale to android:configChanges!
It seems to me there is a good chance for endless cycling here if Login is not properly shared between the activities, causing Login.isLoggedIn() to return true in ActivityLogin but false in ActivityMain.
A few critical factors are where your Login object is located, is it static, how is it referenced between Activities? It is entirely possible that ActivityMain is being destroyed while ActivityLogin is active; storing the Login data in SharedPreferences or a database, or otherwise persisting it is important. How does isLoggedIn() resolve (determine its return value?)
Suggestion 1: Consider making use of the Singleton pattern (if you haven't already.)
Suggestion 2: While discouraged, you could store Login at the Application level.
Suggestion 3: You can try using Intent.FLAG_ACTIVITY_SINGLE_TOP to reduce the likelyhood of a new ActivityMain being created - which might not have access to Login, again depending on how you have it stored.
ActivityMain
onResume() {
if(!Login.isLoggedIn()) {
/* Not logged in, launch ActivityLogin! */
Intent intent = new Intent(ActivityMain.this, ActivityLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
ActivityLogin
onResume() { /* ... */ init(); }
init() {
Login.getUserLoggedIn();
if (Login.isLoggedIn()) {
/* Internet - launch ActivityMain! */
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // <--- suggested addition
startActivity(intent);
else if (Network.haveNetworkConnection(Login.getContext()) && Login.checkClientId()) {
/* No internet, the user was unable to login. */
}
I think your main problem is with you onResume function as it gets called each time it comes back into view (eg: you start second activity, finish it, main activity onResume is called again. If you finish your second activity (or it quietly crashes for some reason) you will go back to your mainActivity and call onResume (which will start the cycle all over again).
Now i dont know if you are finishing activity 2 somehow but I would check that.
EDIT:
ALso I would put some logcats here
if (Login.isLoggedIn())
{
//Do Any Additional Setup
Login.setupStuffOnce();
// If user is logged in, open main
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
Log.i("Some Tag", "Starting Main Activity From Activity 2");
startActivity(intent);
}
The above adding of the log.i will allow you to know if this is where the error happens, and you can go from there.
I had similar problem where the activity would be recreated all the time. Re-installing the app wouldn't help, but restarting the phone did the job.