How to remove an activity from a backstack? startActivityForResult - java

I have a problem with my simple login app using SharingPreferences.
Imagine,that user logs in to application. He has "Log out" button inside his personal account. When user already logged in then he shouldn't return to login activity when he clicks "Back" button on his smartphone, he should return only then he clicks log out button and then he may fill fields with other data(other login,other password).
So, I can't finish() my first activity,because it is possible to return back.
Doesn't work ( it is impossible to return back to login (MainActivity) when I click LOG OUT button.
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferencesEditor.putString("user_login",login.getText().toString());
sharedPreferencesEditor.putString("user_password",password.getText().toString());
sharedPreferencesEditor.apply();
Log.d("MyLog_name",sharedPreferences.getString("user_login",""));
Log.d("MyLog_pw",sharedPreferences.getString("user_password",""));
Log.d("MyTag",login.getText().toString());
Log.d("MyTag",password.getText().toString());
if(login.getText().toString().equals(getString(R.string.user_name)) && password.getText().toString().equals(getString(R.string.user_pw))){
Intent intent = new Intent(MainActivity.this, SuccessActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent,1);
finish();
} else {
Toast.makeText(getApplicationContext(),"Wrong data(очищаю пароль)",Toast.LENGTH_SHORT).show();
password.setText("");
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data!=null){
String savedUser = data.getStringExtra("username");
Toast.makeText(getApplicationContext(),"Farewell, " + savedUser,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Error(Back button was pressed, no prohibition of back stack)",Toast.LENGTH_SHORT).show();
}
}
SuccessActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_success);
welcome = (TextView)findViewById(R.id.welcome);
logOut = (Button) findViewById(R.id.logOut);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
savedUserName = sharedPreferences.getString("user_login","");
welcome.setText("Welcome, " + savedUserName);
logOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("username",savedUserName);
setResult(RESULT_OK, intent);
finish();
}
});
}

Don't finish activity when you are using startActivityForResult() method just put your code ->
/////////
Intent intent = new Intent();
intent.putExtra("username",savedUserName);
setResult(RESULT_OK, intent);
finish();
///////////
in logOut click and on back pressed to get back to the Log In Activity

You will have to finish the LoginActivity while going for SuccessActivity and while clicking on Logout button you can start the LoginActivity once again Over there you can pass the data from SuccessActivity to LoginActivity and do needfull by checking if getIntent.getExtras() are null or not or you can check getIntent.hasExtra()

Related

Why does MainActivity pops up before FirebaseUi gets displayed

I have built a small chat app using firebase. I have also implemented firebaseui for logging in. The problem I am facing is, if the user has not signed up. Whenever the app launches it should take me directly to FirebaseUi signup options but what is happening with current code is for a milli second it shows the layout of main activity and then goes to FirebaseUi.
Also when I am pressing back button before exiting it again shows me the layout of main activity. I want the activity to get destroyed and take me to home (android) but it shows me main activity for a millisecond and then the app exits.
Why is this happening?
public class MainActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 1;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private TextView mUserNameTextView;
private Button mSignOutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUserNameTextView = (TextView) findViewById(R.id.user_name_text_view);
mSignOutButton = (Button) findViewById(R.id.sign_out_button);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
mUserNameTextView.setText(user.getDisplayName());
} else {
// User is signed out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()))
.build(),
RC_SIGN_IN);
}
}
};
mSignOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
}
});
}
private void signOut() {
FirebaseAuth.getInstance().signOut();
mUserNameTextView.setText("");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
// when app is paused remove the state listener
mAuth.removeAuthStateListener(mAuthStateListener);
}
}
#Override
protected void onResume() {
super.onResume();
// adding the state listener
mAuth.addAuthStateListener(mAuthStateListener);
}
}
I believe you won't be able to make the Main Activity not display for a millisecond upon app start, since you are first opening the Main Activity and then you redirect it (if I understood correctly).
I can however help you with your problem when you press the back button.
Add this to your FirebaseUi code as a normal method:
#Override
public void onBackPressed() {
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
//replace "CurrentActivity" and "NextActivity" with your activity names
startActivity(intent);
}
This will open the activity you want when the back button is pressed.
When you start new activity after logged in using FirebaseUI then you need to finish(will remove the activity from backstack) the Login Activity when you start activity.
Intent intent = new Intent(ActivityA.this, NextActivity.class);
startActivity(intent);
finish();

Start activity for result not work, between different activities

I have the main page where the photo is loaded, depending on what the array on the other page contains, in order to synchronize them I used StartActivityForResult();.
It will works like this: MainActivity has a photo, i press showMore button(open showMoreActivity), at showMoreActivity change text and after i finish showMoreActivity, MainActivity load the new photo depends on new text, but real it doesn`t change photo.
Can you help me? Where the mistake is?
buttonShowMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ShowMore.class);
onStop();
getActivity().startActivityForResult(intent, 1);
}
});
onClick button ShowMore Listener
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {return;}
String dataStringExtra =data.getStringExtra("name1");
Picasso.get().load( dataStringExtra + ".jpg").into(imageViewFirstOfCurrentList);
}
onActivityResult method
Intent intent = new Intent();
intent.putExtra("name1", List.get(0).toString());
setResult(RESULT_OK, intent);
finish();
when close showMore Activity
try removing call to onStop() in your onClick() method

Use onActivityResult to call a function

I have an PopUpActivity which pops up a window and i'm very satisfied with that.
However, I want to be able to return information from the popup window back to the parent activity, but also be able to call a function on the parent activity once the popup window is closed. Could someone help me?
Here is my code in the PopUpActivity:
public void closePopUpAndSendResultBack(){ // and how can i pass data to the previous activity?
//https://developer.android.com/training/basics/intents/result
Intent data = new Intent();
data.putExtra("data", "yo");
//startActivityForResult(data, 1); // gives me the error : android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }
setResult(Activity.RESULT_OK, data);
finish();
}
and here is my parent(MainActivity) function that I want to get called once the popUpWindow is closed:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
nameTextField.setText(""); // how can i get Yo inside here?
showTheButton(); // and how can this function get called?
}
}
}}
Also, here is how I make that window Pop up from my Mainactivity:
theOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pop_up_that_window = new Intent(MainActivity.this,PopActivity.class);
pop_up_that_window.putExtra("first", "Velkommen du der!");
startActivity(pop_up_that_window);
}
});
}
Could someone help me please?
In MainActivity use:
theOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pop_up_that_window = new Intent(MainActivity.this,PopActivity.class);
pop_up_that_window.putExtra("first", "Velkommen du der!");
MainActivity.this.startActivityForResult(pop_up_that_window, 1);
}
});
And still in MainActivity in onActivityResult() use this code:
String yo = data.getStringExtra("data")
nameTextField.setText(yo);

Move data by intent without startActivity

I have 2 Activities. On 2nd activity i have data which i want to move by button "Back" to 1st Activity.
Usually i moving by something like this:
button12.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pass=editText2.getText().toString();
Intent intent = new Intent(FirstActivity.this, MapsActivity.class);
intent.putExtra("pass_value", pass);
startActivity(intent);
}
});
But now i dont want to start Activity, instead of this i want close Activity, so i need to use finish()
Currently i created this, but no working:
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FirstActivity.class);
intent.putExtra("number", numberOfTrue);
finish();
}
});
I need something more in this code, but i dont know what.
Start a new activity with
Intent intent = new Intent(FirstActivity.this, MapsActivity.class);
intent.putExtra("pass_value", pass);
startActivityForResult(intent,1)
You can use setResult method to acheive your desired result
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
get Your result in FirstActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
int num = data.getIntExtra("pass_value");
}
}
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
Intent intent = new Intent(this, FirstActivity.class);
intent.putExtra("number", numberOfTrue); }});
You need to open by function startActivityForResult
startActivityForResult(Intent intent, int requestCode)
And get the data returned in the function
onActivityResult
As an example you can see a face to the camera for a picture

how to handle a getIntent() method with java nullpointerexception

I have 2 activities in my application, Activity1 and Activity2.When the app launches Acitivity1 is the the one that is called.Clicking on a button in Activity1 should take you to Activity2.
In Acivity2,some data processing is done then i send back data to Activity1 using an intent like this:
Intent in=new Intent(getApplicationContext(), Activity1.class);
in.putExtra("data", data);
startActivity(in);
Then getting back to Activity1 i obtain the intent data:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
String data =(getIntent().getExtras().getString("data"));
The problem here is that the first time the app launches it checks for the intent data and it does not exist so i get the nullpointerexception error.how can i make sure it checks for the intent data when Activity2 is the previous class?
You can check if the intent is existing using:
getIntent().hasExtra("data");
This will return you a boolean.
Also if oyu want to return some datas to the first activity, your should start the second one with startActivityForResult
if (extras != null) {
if (extras.containsKey("data")) {
boolean hasData = extras.getBoolean("data", false);
// TODO: Do something with the value of "data".
}
}
put a check over it
if(getIntent().getExtras()!=null){
String data =(getIntent().getExtras().getString("data"));
}
Follow the following steps
1: from your activity1's button click call as follow
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
2: In your Activity2 set the data which you want to return back to Activity1 as follow and if you don't want to return back don't set anything.
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
if you don't want to return data:
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
3: now again in your Activity1 handle the return data as follow
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
EDIT:
and if you strictly want to use your own method as in your question try this:
in your Activity1 you obtain the intent data as:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
String data ="default value";
try{
data =(getIntent().getExtras().getString("data"));
}catch(Exception e){
}
}
use ActvityForResult.
replace these codes.
in ACTVITY1:
put this after onCreate:
#Override
protected void onActivityResult(int requestCode ,int resultCode ,Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
String name =data.getStringExtra("data");
if(resultCode == RESULT_OK){
switch(requestCode){
case 2:
if(resultCode == RESULT_OK){
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
}
}
}
in ACTIVITY2:
Intent intent=new Intent();
intent.putExtra("data",data);
setResult(2,intent);
finish();

Categories

Resources