Finish Activity not close in Android (Xamarin) - android

I have Two Activity one is InventoryActivity and Second is StoneDetailActivity. In my InventoryActivity have RecycleView In RecycleView Button Click I start the StoneDetailActivity using StartActivityForResult below code.
Intent stonedetailIntent = new Intent(context, typeof(StoneDetailActivity));
stonedetailIntent.PutExtra("SearchitemObject", stoneJson);
stonedetailIntent.PutExtra("position", position);
context.StartActivityForResult(stonedetailIntent, 1000);
context.OverridePendingTransition(Resource.Animation.Slide_in_right, Resource.Animation.Fade_back);
In StoneDetailActivity Button click I use this code to Finish the current Activity and go to OnBackPressed().
public override void OnBackPressed()
{
Intent intent = new Intent();
intent.PutExtra("BoolCheck", postflag);
intent.PutExtra("Position", position);
SetResult(Result.Ok, intent);
Finish();
}
and In InventoryActivity I have set this code.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
bool checkflag = data.GetBooleanExtra("BoolCheck", false);
int position = data.GetIntExtra("Position", -1);
if (checkflag && position > -1)
{
searchItems.RemoveAt(position);
inventAdapter.NotifyDataSetChanged();
txt_totalStone.Text = searchItems.Count.ToString();
txt_totalCarat.Text = searchItems.Sum(c => c.Weight.Value).ToString();
txt_totalAmount.Text = searchItems.Sum(c => c.Rate.Value).ToString();
mainActivityBool = true;
badgeCounttextView.Text = BizApplication.BADGE_COUNT.ToString();
}
}
}
Button Click code :
add_to_cart_button.Click += async (sender, e) =>
{
ProgressDialog pdialog = new ProgressDialog(this);
pdialog.SetMessage("Please Wait...");
pdialog.Show();
cartItem = new CartItem();
cartItem.StoneId = searchItem.PacketId;
cartItem.UserId = BizApplication.getCredential().Id;
cartItem.Amount = searchItem.Rate.Value;
cartItem.Discount = searchItem.Discount;
postflag = await InventoryService.AddToCart(cartItem);
if (postflag)
{
OnBackPressed();
BizApplication.BADGE_COUNT += 1;
}
pdialog.Dismiss();
};
this code work fine for first Time. But Again if I do the same process, the StoneDetailActivity set open eventhough if I click finish.
UpDate :
When I full debug my code and i found that when I click on Second time OnBackPressed(). and Finish it my debug again start the OnCreate activity that's why it happening. But I am not starting Again then Why is Happening.
What happen I don't understand. Any Help be Appreciated.

As per this Post the Problem was that inside ListView or RecycleView if we are perform some task like OnclickListener then we have check is OnclickListener like below way other it will fire multiple event.
if (!button.HasOnClickListeners)
{
button.Click += this.clickHandler;
}
Then the code is working fine.
For more detail visit this :
https://forums.xamarin.com/discussion/9244/single-click-on-button-invoking-multiple-clicks

try by adding flag Intent
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);

Related

onActivityResult never called from widget launched activity

I'm new here. I discover how StackOverflow works.
I'm creating a new android homescreen widget. My widget has a button. When pressed, it starts an activity (it's not a configure Activity, just a standard activity). In this activity, I have a test button. My purpose is to create a text file after pressing this test button.
In onCreate function, I have this code to handle the button :
final Button testButton = findViewById(R.id.button_test);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(WidgetActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
Utils.MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
String fileName = "test.txt";
Intent exportIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
exportIntent.addCategory(Intent.CATEGORY_OPENABLE);
exportIntent.setType("text/plain");
exportIntent.putExtra(Intent.EXTRA_TITLE, fileName);
startActivityForResult(exportIntent, FILE_EXPORT_REQUEST_CODE);
}
});
And I have this function :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case FILE_EXPORT_REQUEST_CODE:
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Context c = WidgetActivity.this;
ParcelFileDescriptor pfd = null;
try {
pfd = c.getContentResolver().openFileDescriptor(uri, "w");
Preferences.export(mAppWidgetId, pfd.getFileDescriptor(), WidgetActivity.this);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
break;
}
}
onActivityResult is never called.
I put this code in my MainActivity, and it works very well.
I don't know how to achieve this...
It's seems to be impossible.
The way I achieve this :
My widget starts its activity (not the MainActivity), as usual, and one feature offer the possibility to create a file.
The button in this activity create a new intent with action code, and launch MainActivity.
MainActivity use action code to decide what to do : execute code to create the file.
MainActivity have a onActivityResult called when user choose a file name and a directory.

Starting multiple activities and getting result before starting the next one

I am making a quiz app, my MainActivity(main menu) launches QuestionActivity using startActivityForResult, in QuestionActivity (Question text and answer buttons). After the user has answered the question, I want to send a boolean back a to MainActivity to update the score which then can be pushed into the next intent, in the Question Activity, I display the score in the Actionbar.
The problem is when I answer one question, setResult and Finish Runs but onActivityResult does not, after I answer all questions then OnActivityResult runs 10 times.
How can I get onActivityResult to run after I answer each question, not at the end?
Do I need to use intent flags?
Extra Info
In MainActivity, when the user starts the quiz:
//Called when user clicks quiz
//Creates the list of questions and then asks them.
public void makeQuiz(View view) {
//Pick the questions for the quiz
question[] quiz = new question[10]; //A quiz with 10 questions
for (int i = 0; i < quiz.length; i++) {
quiz[i] = myDBHelper.pickQuestion();
askQuestion(view, quiz[i],i,qscore);
Log.d("Asked question", Integer.toString(i));
}
}
Ask Question is used to start the QuestionActivity:
//Creates a question and then passes it though to the question view.
public boolean askQuestion(View view, question q, int questionNum, int qscore){
question q1 = q;
Log.d("Correct Ans",q.CorrectAns);
Intent question = new Intent(this, QuestionActivity.class);
Bundle extras = new Bundle();
extras.putString("QUESTION", q.QuestionText);
extras.putString("MODULE", q.Module);
extras.putString("CORRECT_ANS",q.CorrectAns);
extras.putString("ANS1", q.WAns[0]);
extras.putString("ANS2", q.WAns[1]);
extras.putString("ANS3", q.WAns[2]);
extras.putInt("qscore",qscore);
question.putExtras(extras); //Passing the question to the QuestionActivity
startActivityForResult(question,1);
return true;
}
In QuestionActivity, When the user answers the question correctly:
//Pass back that we got the correct answer
resultIntent = new Intent();
resultIntent.putExtra("ANSWER",true);
setResult(1, resultIntent);
Log.d("True", "Set result has been called");
finish();
Back in MainActivity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
//Check which event we are responding to
Log.d("onActivityResult", "called"); //This never runs
if(resultCode == 1){
//Do something with the intent
//if q is correct, update the score in shared prefrences,
Boolean result = data.getBooleanExtra("ANSWER",false);
Log.d("ANSWER IS ", Boolean.toString(result));
qscore += result ? 1:0; //This updated score is then pushed into the next intent so it can be displayed in the next question activity.
}
}
Alright so this is your problem you start the activity for result with:
startActivityForResult(question,questionNum);
so questionNum is your requestCode
but when you finish the QuestionActivity you finish it like this:
setResult(Activity.RESULT_OK, resultIntent);
so here your request code is the value of Activity.RESULT_OK
you need them to be equal.
Edit:
for your request in the comment look at this:
private static final int REQUEST_CODE = 123131;
private Stack<Intent> intentStack = new Stack<>();
//Called when user clicks quiz
//Creates the list of questions and then asks them.
public void makeQuiz(View view) {
//Pick the questions for the quiz
question[] quiz = new question[10]; //A quiz with 10 questions
for (int i = 0; i < quiz.length; i++) {
quiz[i] = myDBHelper.pickQuestion();
askQuestion(view, quiz[i], i, qscore);
Log.d("Asked question", Integer.toString(i));
}
startActivityForResult(intentStack.pop(), REQUEST_CODE);
}
//Creates a question and then passes it though to the question view.
public boolean askQuestion(View view, question q, int questionNum, int qscore) {
question q1 = q;
Log.d("Correct Ans", q.CorrectAns);
Intent question = new Intent(this, QuestionActivity.class);
Bundle extras = new Bundle();
extras.putString("QUESTION", q.QuestionText);
extras.putString("MODULE", q.Module);
extras.putString("CORRECT_ANS", q.CorrectAns);
extras.putString("ANS1", q.WAns[0]);
extras.putString("ANS2", q.WAns[1]);
extras.putString("ANS3", q.WAns[2]);
extras.putInt("qscore", qscore);
question.putExtras(extras); //Passing the question to the QuestionActivity
intentStack.push(question);
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check which event we are responding to
if (resultCode == RESULT_OK) {
//Do something with the intent
//if q is correct, update the score in shared prefrences,
Boolean result = data.getBooleanExtra("ANSWER", false);
Log.d("ANSWER IS ", Boolean.toString(result));
qscore += result ? 1 : 0;
if(!intentStack.isEmpty()){
startActivityForResult(intentStack.pop(), REQUEST_CODE);
}
}
}

Correctly load data in listview from startactivityforresult

GOAL
What I am trying to do:
Click on my search button and my database is queried with the results passed in. If nothing is found, we are taken to an activity which says so, but if results are found they are loaded into a list.
What I have done
When I click on the search button I call startActivityForResult then this intent calls an activity (whose layout consist of a list_view). The search button also pass along my parameters and query my database.
if there are no results then an activity saying "No Records" is displayed"
and if there are records the else condition is true and the records are loaded in the list
PROBLEM
The problem I am experiencing is, when the list is loaded, if I want to go back to my search form, I must press the back button a total of three times. I am not entirely sure but I believe this strange behavior is stemming from me not returning a result to the started activity when the else clause is invoked.
I have placed what I think is the important part of my code below, would appreciate any assistance
Main Activity
private void startStudentQuery() {
Intent intent = new Intent(getBaseContext(), retrieveStudentData.class);
intent.putExtra("firstname", firstname);
intent.putExtra("lastname", lastname);
//startActivity(intent);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
Intent X = new Intent();
X.setClass(getBaseContext(),NotFound.class);
startActivity(X);
}
}
retrieveStudent Activity
//this activity is a listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_student)
}
//Left out some code, just showing the main parts
public class StudentAsynTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//return result to show Activity if no records are found
if (jsonArray.length() == 0) {
Intent intent=new Intent();
setResult(2,intent);
finish();
} else {//Show list if records are found
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jRealObject = jsonArray.getJSONObject(i);
Student student = new Student ();
student.setFirstname(jRealObject.getString("f_name"));
student.setLastname(jRealObject.getString("l_name"));
student.setImage(jRealObject.getString("image"));
studentList.add(student);
}
}
In startStudentQuery, you should call startActivityForResult only, but now you have called retrieveStudentData twice.

Error: Activity result fragment index out of range: 0x2fffe

When im trying to delete a show with an AsyncTask. I want to call finish() after the AsyncTask has been completed and return an Intent with the result.
from the activity:
new DeleteShowTask().execute();
Intent intent = new Intent(SeasonActivity.this, FragmentShows.class); // I'm not sure if this works
intent.putExtra("tvdbid", tvdbId);
setResult(DELETECODE, intent);
finish();
then in the fragment i have this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("RESULTCODE", resultCode + "");
Log.d("REQUEST CODE", requestCode +"");
if (resultCode == SeasonActivity.DELETECODE)
{
if (requestCode == SeasonActivity.SHOW)
{
String tvdbid = data.getStringExtra("tvdbid");
for (int i = 0; i < adapter.getCount(); i++) {
SickbeardSerie serie = adapter.getItem(i);
if (serie.getTvdbId().equals(tvdbid))
{
adapter.remove(serie);
adapter.notifyDataSetChanged();
}
}
}
}
}
But it seems like it doenst run through this onAcitivityResult().
I have logged the onActivityResult() as you see but i dont get any logs.
Only thing i get is: 10-19 16:21:44.631: W/FragmentActivity(27672): Activity result fragment index out of range: 0x2fffe
I fixed it for now by using a work around.
I now reload my AsyncTask in the onResume() instead of just removing an item from the arraylist and calling adapter.notifyDataSetChanged(). But its not the best solution.
if you using a Fragment in a another Fragment. You should be call
getParentFragment().startActivityForResult(i, SELECT_PICTURE);

OnCreate method keeps getting called repeatedly

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.

Categories

Resources