Android back navigation leads to crash on activity based on intent [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an android app with three activities A, B, and C. B starts with a necessary intent form A and from B I can startActivity C. But when I use the back button on the action bar to go back from C to B, the app crashes because B received no intent. How to solve this.
Code for Activity B, getting intent from Activity A. It is important to have this intent for the activity B to function.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parking_spot);
getSupportActionBar().hide();
spot = getIntent().getParcelableExtra("spot");
init();
}
private void init() {
days = findViewById(R.id.spot_days);
rate = findViewById(R.id.spot_rate);
timing = findViewById(R.id.spot_timing);
name = findViewById(R.id.spot_name);
address = findViewById(R.id.spot_address);
spots = findViewById(R.id.spot_spots);
// This is where null pointer exception is thrown on accessing spot variable
name.setText(spot.getName());
address.setText(spot.getAddress());
timing.setText(spot.getTiming());
String temp = getResources().getString(R.string.rs) + " " + spot.getRate() + "/HR";
rate.setText(temp);
temp = spot.getDays();
for (int i = 0; i < temp.length(); i++) {
if (temp.charAt(i) == 'T') {
setDay(i);
}
}
FirebaseDatabase.getInstance().getReference(spot.getPath()).child("spots").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long total = dataSnapshot.getChildrenCount(), free = 0;
for (DataSnapshot shot : dataSnapshot.getChildren()) {
Log.v("Spot", shot.child("status").getValue(Integer.class) + "");
if (shot.child("status").getValue(Integer.class) == 0) {
free++;
}
}
String temp = free + "/" + total;
spots.setText(temp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
findViewById(R.id.navigate_spot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + spot);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
});
findViewById(R.id.book_now).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ParkingSpotActivity.this, BookingActivity.class);
intent.putExtra("spot", spot);
startActivity(intent);
}
});
setupSlider();
}
Going to C from B
confirm.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), CheckoutActivity.class);
intent.putExtra("spot", parkingSpot);
intent.putExtra("pos", pos);
startActivity(intent);
});
Now app has opened activity C. Clicking on the back arrow icon in Activity B to C leads to an error as B loses its intent data
Erro from debugger when i press back button
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mobile.solutions.parking, PID: 26598
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobile.solutions.parking/com.mobile.solutions.parking.activity.ParkingSpotActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mobile.solutions.parking.model.ParkingSpot.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3374)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mobile.solutions.parking.model.ParkingSpot.getName()' on a null object reference
at com.mobile.solutions.parking.activity.ParkingSpotActivity.init(ParkingSpotActivity.java:59)
at com.mobile.solutions.parking.activity.ParkingSpotActivity.onCreate(ParkingSpotActivity.java:47)
at android.app.Activity.performCreate(Activity.java:7815)
at android.app.Activity.performCreate(Activity.java:7804)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)
The only point is that B to C works fine but not vice versa. This I think is because B doesn't retain its intent data

In the OnCreate method add this:
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Then add this method:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}

You can use MVVM, Moxy MVP structure or savedInstance to store your data and use it. When you back from C to B it will use one of this data store algorithm and you will not get crashed. So, check every time
if (savedInstance != null ){
spot = savedInstance.getParcelable("spot");
} else {
spot = getIntent().getParcelableExtra("spot");
}

Related

how to set data into dialog-fragment from mapActivity

i m fetching lat-lang data on longclick event on my map. the problem is when i pass data in my dialog-fragment's edittext, its getting null,
here is my code of long-click event
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener, View.OnClickListener {
#Override
public void onMapLongClick(LatLng point) {
if(mMap != null) {
mMap.addMarker(new MarkerOptions().position(point).title(point.toString()));
double latitudeNew = point.latitude;
double longitude = point.longitude;
mLatLongArray.add(new double[]{latitudeNew, longitude});
isMarkerClicked = false;
lat = String.valueOf(latitudeNew);
logt = String.valueOf(longitude);
Toast.makeText(getApplicationContext(),lat,Toast.LENGTH_SHORT).show();
}
}
}
and i m going back using using onbackpress in my button click like this.
AddGeofenceFragment.ViewHolder fragment = new AddGeofenceFragment.ViewHolder();
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnBackToFragment) {
String TAG = "com.rockstar.googlemap.AddGeofenceFragment";
onBackPressed();
// getSupportFragmentManager().beginTransaction().replace(R.id.dialogFrgment, new AddGeofenceFragment()).addToBackStack(TAG).commit();
fragment.latitudeEditText.setText(lat);
fragment.longitudeEditText.setText(logt);
}
}
here is my workflow, first i open my dialog-fragment on fab-button click,
and open map for get latitude and logtitude data,
mow when i click on my "goBackTOFragment" button my app unfortunately stop,
i dont understand wht its happening, even i get data on longclick event, i checked using toast, but its not passing to the fragment. it says null pointer exception on this line
fragment.latitudeEditText.setText(lat);
fragment.longitudeEditText.setText(logt);
i want to set both string data lat and logt in my previous dialog-fragment's edittext, i dont know how to pass data in fragment how do i do that. please help me. i really appreciate that.
If you use the map activity just getting lat/lng, it could be started like this
Intent intent = new Intent(this, MapsActivity.class);
startActivityForResult(intent, 1);
And then when you press back button (MapsActivity)
Intent position = new Intent();
position.putExtra("lat", lat);
position.putExtra("lng", lng);
setResult(1, position );
finish();
Again your first activity, you received position from map. U can use dialog fragment's fields. In your case, you losing dialog fragment instance.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == 1){
double lat = intent.getDoubleExtra("lat", -1);
double lng = intent.getDoubleExtra("lng", -1);
}
}
I think, this approach better for your case. Also you can check deeply from here
EDIT
I also saw your latest update on the question post.
AddGeofenceFragment.ViewHolder fragment = new AddGeofenceFragment.ViewHolder();
#Override
public void onClick(View v) {
...
fragment.latitudeEditText.setText(lat);
fragment.longitudeEditText.setText(logt);
}
This wrong, with this usage, you just instantiating, not calling onCreateView method of DialogFragment. Check this below
In first activity, i'm calling AddGeofenceFragment first time. Also keeping fragment instance for later usage.
FragmentManager fm = getSupportFragmentManager();
AddGeofenceFragment dialogInstance = new AddGeofenceFragment();
AddGeofenceFragment.show(fm, "AddGeofenceFragment");
In Maps activity, I choose position.
public void onMapLongClick(LatLng point) {
Intent position = new Intent();
position.putExtra("lat", point.latitude);
position.putExtra("lng", point.longitude);
setResult(1, position );
finish();
}
In first activity, i'm getting the position
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == 1){
double lat = intent.getDoubleExtra("lat", -1);
double lng = intent.getDoubleExtra("lng", -1);
dialogInstance.latitudeEditText.setText(lat);
dialogInstance.longitudeEditText.setText(lng);
}
}
Main activity and fragment should communicate over interface callbacks. They generally has no common memory to share directly. See http://developer.android.com/intl/es/training/basics/fragments/communicating.html

getIntent().getExtras() is some times null in API level 21?

As per some google crash report of my app i am seeing NullPointerException,
"Attempt to invoke virtual method int android.os.Bundle.getInt(java.lang.String) on a null object reference" but i have made sure and cross checked that intent to that activity always some Extras is set. Can some one suggest me what might be wrong, i am suspecting not overriding onNewIntent, is causing problem but my activity is launched with "noHistory =true" flag so onNewIntent is never called?
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_alert_dialog);
mBackToMain = false;
mDoExit = false;
int stringMessageId = getIntent().getExtras().getInt(name);
String stringMessage = getIntent().getExtras().getString(fullName);
initFields(name,fullName);
}
#Override
protected void onNewIntent(Intent intent)
{
mLog.d("WarningActivity","on new Intent triggered "+ intent.getExtras());
super.onNewIntent(intent);
int stringMessageId = getIntent().getExtras().getInt(name);
String stringMessage = getIntent().getExtras().getString(fullName);
initFields(name,fullName);
}
You may be putting extras right and something else goes wrong so make sure that the extras is not null by checking it first like so:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if(extras != null) {
if(extras.containsKey("your key here")) {
int x = extras.getInt("your key here");
}
else {
Log.d("extras", "No Key");
}
} else {
Log.d("extras", "Null Extras");
}
and then check your logcat and you should see what's really going on

Android: Error transfer data after click of buttons

Hi there I am new to Android Programming
I am trying to create an application in which, the user clicks button on the first page
the text color in the buttons change color and the change is reflected in another activity page.
To do this I have
1) one fragment class(BookLockerFragment) which reference to an xml file containing the buttons
2) The parent activity file (TabActivity.java)
3) The activity file to reflect the change ( complainResponse.java)
Here is the code:
LodgeComplaintFragment.java
ArrayList<String>userSelectedOptions = new ArrayList<String>();
if(btnSis.getCurrentTextColor()==Color.BLUE){
userSelectedOptions.add("SIS");
}
Button but = (Button) root.findViewById(R.id.searchButton);
.....
but.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
buttonListener.onMakeBookingButtonPressed(userSelectedOptions);
}
});
TabMainActivity.java
public void onMakeBookingButtonPressed(ArrayList<String> list) {
// TODO Auto-generated method stub
Intent intent = new Intent(TabMainActivity.this,
complainResponse.class);
intent.putStringArrayListExtra("userSelectOptions",list);
startActivity(intent);
}
complainResponse.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
setContentView(R.layout.complainresponse);
userInput = intent.getStringArrayListExtra("userSelectOptions");
// Creates the window used for the UI
if (userInput != null) {
if (userInput.get(0) != null) {
textview1 = (TextView) findViewById(R.id.textView1);
textview1.setText(userInput.get(0));
}
}
}
Error occurs at this line:
if (userInput != null) {
//of complainResponse.java
Logcat:
java.lang.IndexOutOfBoundsException
Please help
There's nothing in the ArrayList that you pass to your activity.
I suspect this bit of code isn't being executed -
if(btnSis.getCurrentTextColor()==Color.BLUE){
userSelectedOptions.add("SIS"); <------------ never gets here
}
To verify this, run the application in debug mode, and place a breakpoint at the if statement
userInput.get(0) != null
this is the cause of error in my opinion, list can be initialized but empty.
instead you should use,
if (!userInput.isEmpty())

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.

Problem with onClickListener

this actually does nothing when i click the button.
The button is like:
Button Confirmar = (Button)findViewById(R.id.btConfirma);
Confirmar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String Login = edLogin.getText().toString();
String Senha = edSenha.getText().toString();
if(Login.length() == 0 || Senha.length() ==0) {
Toast.makeText(getuser.this, "Por favor preencha o login e a senha!", Toast.LENGTH_LONG).show();
return;
}
if (chkKeep.isChecked() && (edLogin.getText().toString() != Settings.getUser() || edSenha.getText().toString() != Settings.getPass())) {
Settings.setUser(edLogin.getText().toString());
Settings.setPass(edSenha.getText().toString());
Settings.setKeepUser(chkKeep.isChecked());
jXML.updateConfigXml();
}
Intent i = getIntent();
Bundle bD = new Bundle();
bD.putStringArray("Login", new String[] {edLogin.getText().toString(), edSenha.getText().toString()});
i.putExtras(bD);
finishActivity(555);
}
});
As asked --> Button XML:
<Button android:layout_width="180dip" android:layout_height="wrap_content" android:id="#+id/btOkLogin" android:text="Confirmar"></Button>
SOLVED: Had to use setResult(ResulCode, Intent) before finish();
Answered by: #Sam-Quest
i guess you have to set the result before calling the finish
...
Intent i = getIntent();
Bundle bD = new Bundle();
bD.putStringArray("Login", new String[] {edLogin.getText().toString(), edSenha.getText().toString()});
i.putExtras(bD);
setResult(RESULT_OK, i);
finishActivity(555);
check this link if you have any doubt. LINK
Put a breakpoint on first line inside onClick listener, run on debug mode and see where it goes on the code.
That's a strange error. I'd try to maybe setOnClickListener(this) and let your activity implement onClick(View). Otherwise you can add android:onClick tag to the xml button object.

Categories

Resources