I created TabActivity having two tabs with two activities.
one is login tab another is welcome tab.
user should not go welcome tab unless login successfully.if he tries to select welcome tab he throws to login tab.i use tabHost.setcurrenttab(index).
But when i click direct welcome tab it works fine for first time. When i again click tab rapidly it opens welcome tab.
Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_list);
SharedPreferences mPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
username = mPreference.getBoolean("valid", false);
Toast.makeText(this, "In Create", Toast.LENGTH_SHORT).show();
//login sucessful
tabActivity.switchTab(0);
}
on onResume, i repeat the same code.
Try this in your TabActivity. This is to prevent user to switch tab if he is not logged in.(I have no time to check it now,please let me know if any issue is there with the code):
SharedPreferences mPreference;
....onCreate(){
...
mPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
username = mPreference.getBoolean("valid", false);
if(user is logged in){
tabHost.setcurrenttab(0);//welcome page
}
else{
tabHost.setcurrenttab(1);//login page
}
}
});
...
}
Related
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();
}
});
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 put a webview in an activity .
the webview loads TelegramWeb's page.
when i login to the telegram account it works fine.
but when i rotate screen or reopen the app it forgets all data and needs relogin to telegram account.
so i need to save some data like coockies and other necessary files.
i used setJavaScriptEnabled=true and some other setting below:
#SuppressLint("SetJavaScriptEnabled") public class SubActivity extends Activity {
private WebView wv1;
protected void onSaveInstanceState(Bundle outState) {
wv1.saveState(outState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
Button b1=(Button) findViewById(R.id.btnSave);
wv1=(WebView)findViewById(R.id.webView1);
WebSettings ws=wv1.getSettings();
ws.setAllowContentAccess(true);
ws.setAppCacheEnabled(true);
ws.setSaveFormData(true);
wv1.setWebViewClient(new Webview());
wv1.getSettings().getCacheMode();
wv1.getSettings().getAllowContentAccess();
wv1.getSettings().getSaveFormData();
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv1.getSettings().setAllowFileAccess(true);
wv1.getSettings().setDomStorageEnabled(true);
wv1.setSaveEnabled(true);
if (savedInstanceState != null)
wv1.restoreState(savedInstanceState);
else
wv1.loadUrl("https://web.telegram.org/#/im");
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getBaseContext(), wv1.getUrl().toString(), Toast.LENGTH_LONG).show();
}
});
}
}
but still it needs re-login to account.
better to know that SubActivity Class start from MainActivity after checking a password.
------
note:
i added this code after wf1.loadUrl and it works on screen rotation.
wv1.saveState(savedInstanceState);
but still not works when close app and reopen it. so i have to re-login.
i think i have to save the InstanceState some where.
how can i do?
If you don't want to use database for saving data you can use Shared Preferences where you save key-value pairs. More in documentation.
Try the below, it might works for cache issue,
wv1.getSettings().setDomStorageEnabled(true);
wv1.getSettings().setAppCacheEnabled(true);
The below works for device rotation and configuration changes
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
After this edit AndroidManifest.xml file like below
android:configChanges="orientation|screenSize|keyboardHidden"
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.
I'm writing a flash card app in Android, and I tried to add the ability to add a word to a review list by having a checkbox. When the user goes to the next word, I see whether the checkbox is checked. If it is, I add the word to the review list, and if it isn't, I remove the word. When I tested it on my phone and the emulator, I got a forced close every time I try to go to the next word or to the home page when the checkbox is checked. I don't know what's causing the error because in the LogCat page, it doesn't show the line number or what error happened.
I can flip through the words without a problem when I don't have them checked; checking it and going to another word is what causes a problem, so I'm guessing it has to do with the SharedPreferences.
Here are the important methods I have:
public void onCreate(Bundle savedInstanceState)
{
//other code
reviewCheckBox = (CheckBox) findViewById(R.id.reviewCheckBox);
prefs = getPreferences(MODE_PRIVATE);
editor = prefs.edit();
reviewCards = prefs.getAll().keySet();
}
public void home(View v)
{
if (flashCardPage.getVisibility() == View.VISIBLE)
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
updateReviewCards();
}
//other code
}
public void nextWord(View v)
{
currentPosition++;
if (currentPosition == flashCards.size())
{
home(wordTV);
}
else
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
//other code
if (reviewCards.contains(currentCard.getTerm()))
reviewCheckBox.setChecked(true);
else
reviewCheckBox.setChecked(false);
}
}
public void previousWord(View v)
{
if (currentPosition > 0)
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
//other code
if (reviewCards.contains(currentCard.getTerm()))
reviewCheckBox.setChecked(true);
else
reviewCheckBox.setChecked(false);
}
}
public void updateReviewCards()
{
editor.clear();
for (String card : reviewCards)
editor.putString(card, card);
editor.commit();
}
The set returned by getPreferences().getAll().keySet() does not support adding.