Passing values from Activity2 to Activity1 without visiting Activity1 - java

I have a loginActivity and a MainActivity
I have used SharedPreferences to store some values in some variables in the loginActivity. Now I want to use these values(They're boolean values) in MainActivity without re=opening MainActivity. How do I do this?
Also, the SharedPreferences are in an onClick method for a button .
Thank you!

I'm assuming that MainActivity starts first, and loginActivity is on top of it in the stack. When loginActivity finishes, you can read the SharedPreferences in MainActivity#onResume.
If you mean that you want to do things in MainActivity while it's in the background or backstack, don't. An activity that is not in the foreground should not be doing any work, and in fact cannot be counted on to exist at all.

There are two ways
1.If you have set the values in shared preferences you can access them from any activity with relevant permissions.
2.Pass when moving from one to another activity and close the other one if need.
Intent toMain = new Intent(LoginActivity.this, MainActivity.class);
toMain.putExtra("bool1", "true"); //Optional parameters
LoginActivity.this.startActivity(toMain);
//To prevent go back to login
finish();
then from onCreate of mainActivity
Bundle fromLogin = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("bool1");
//convert this to boolean
}

Related

How to finish the main activity from other Activity

Hello how do you finish Main activity
Assume that there are 3 Activities and 1 Fragment
LoginActivity , MainActivity, infoFrgMent, ChangePwdActivity.
The scenario is when I loggedin in LoginActivitythen MainActivity will show up LoginActivity will finish() then i will go to my info which is 'infoFrgMent' then i want to change my password after i changed my password.
LoginActivity will shows up Again to relogin but whenever i try to press back MainActivity shows up and didn't finished.
You need to remove previous activities form stack
setFlags to intent from MainActivity to LoginActivity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
refer : https://developer.android.com/guide/components/activities/tasks-and-back-stack.html
What you need is to add the Intent.FLAG_CLEAR_TOP. This flag makes sure that all activities above the targeted activity in the stack are finished and that one is shown.
Another thing that you need is the SINGLE_TOP flag. With this one you prevent Android from creating a new activity if there is one already created in the stack.
Just be wary that if the activity was already created, the intent with these flags will be delivered in the method called onNewIntent(intent) (you need to overload it to handle it) in the target activity.
Then in onNewIntent you have a method called restart or something that will call finish() and launch a new intent toward itself, or have a repopulate() method that will set the new data. I prefer the second approach, it is less expensive and you can always extract the onCreate logic into a separate method that you can call for populate.
To finish another Activity you have to create a static method to finish this Like here:
MainActivity.java
private static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
activity = this;
}
public static void finishThis()
{
try
{
if (activity != null)
{
activity.finish();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
And call it like this:
AnotherActivity.java
MainActivity.finishThis();
That's it

Retaining variable value when stopping android activity

I've got two activities, A and B. Activity B can be opened by pressing a button in Activity A.
In activity B I have an integer variable which I would like to keep for when I return to activity B from A. My problem is when I press the back button to go from B to A the activity is destroyed.
I have overwritten the onBackPressed method to:
#Override
public void onBackPressed(){
Intent i = new Intent(this, Game.class);
startActivity(i);
}
I can see from my logs that activity B is in the state onStop() after back button is pressed, however, onRestart() is not being called so the activity must be getting killed for memory reasons.
I have read answers to other posts suggesting I use onSaveInstanceState() but when I try to access the bundle in onCreate() the bundle is null. Method onRestoreInstanceState() does not get called.
protected void onSaveInstanceState(Bundle savedInstanceState){
Log.i(LOG, "instance saving");
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("score", userScore);
}
I have also tried SharedPreferences but this is not useful because I do not want my data to persist when the activity/application is intentionally destroyed.
I think your problem is in understanding the whole Task ecosystem. When you press back button you pop out your activity from the Task, because of that it is destroyed and onDestroyed() is called. To sum-up I think you are just getting every time a brand new activity. onSaveInstanceState() isn't called because activity is killed by user, not by the OS.
Take a deeper look at this developer tutorial.
Also I think those two must be helpful : me and me!
you can store variables in the app class https://developer.android.com/reference/android/app/Application.html or you can make your own singleton class for this
https://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
Starting a Activity - A on onBackPressed will definitely kill the current Activity - B. Instead of starting Activity again just call onBackPressed in Activity - B and add a stage called onResume() which is called when you resume back to Activity B from A
Remove this:
#Override
public void onBackPressed(){
Intent i = new Intent(this, Game.class);
startActivity(i);
}
With this:
#Override
public void onBackPressed(){
super.onBackPressed();
}
When you coming back from A to B, in B #Override stage onResume() and in this you can save the value while coming back from Activity A.
Add this in Activity B:
#Override
protected void onResume() {
super.onResume();
// save values here for resume
}
Look the Activity Life Cycle:

Passing String Values between Activities using intents

I understand how to pass string values from the MainActivity to the SecondaryActivity using intents, but how would you do that Vise Versa. Here is the code that I am using, I just don't know where to put the Recieving classes code.
In my SecondActivity
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
String TimeValue = ("00:00:00");
intent.putExtra("TimeValue", TimeValue);
startActivity(intent)
and This is the code that I am not sure where to put so it doesn't crash when the app starts
String intent = getIntent().getExtras().getString("TimeValue");
TextView timeText = (TextView)findViewById(R.id.timeText);
timeText.setText(intent);
The problem is that MainActivity won't always be created with an intent coming from SecondActivity. It will also be created just when the app is launched.
You need to make sure that extras actually exists before trying to get extras from it! It could be null!
So this should be in your onCreate method, after you inflate the view.
Bundle extras = getIntent().getExtras();
String intentString;
if(extras != null) {
intentString = extras.getString("TimeValue");
} else {
intentString = "Default String";
}
TextView timeText = (TextView)findViewById(R.id.timeText);
timeText.setText(intentString);
I also highly recommend that you change the name of your String to "intentString" instead of "intent." The name "intent" is typically used for actual Intent objects, not the String that you get out of the Intent. So naming it "intentString" makes things more readable for other developers.
If you're trying to pass data back from SecondActivity to the MainActivity, then use startActivityForResult instead.
Once you have launched your SecondActivity and ready to pass the data back to the MainActivity, create a new Intent and use SecondActivity.setResult(resultCode, Intent);. Then call finish, to finish the SecondActivity.
Now, in your MainActivity, you will get a call to onActivityResult() which will give you the Intent you passed in the SecondActivity as a data parameter.
You can look at this link for more info: http://developer.android.com/training/basics/intents/result.html

How to go from second activity to third activity or fourth activity based on first activity data (Radio button clicked)?

I have four activities say java files - activity1.java, activity2.java, activity3.java, activity4.java and xml files - activity_1.xml, activity_2.xml, activity_3.xml, activity_4.xml
Now in activity1 - I have a radio group with two radio buttons and a button to go to activity2
Now in activity2 - I have a button to go to activity3 or activity4 based on which radio button is clicked in activity1.
I can delete activity2 and use if condition in activity1 to go to activity3 or 4 But I definitely need activity2
I am not familiar with bundles, shared preferences
How? Any help in this regard
You can just use an intent and pass on values between activities. In first activity:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("someName", valueOfRadioButton);
startActivity(intent);
In the onCreate of the next activity you can retrieve the value you passed like this (for an Integer):
getIntent().getIntExtra("someName", someDefaultValue);
Now you have a variable to query. Depending on the value, you launch whatever activity you like.
Use
Intent startSecondActivityIntent = new Intent(FirstActivity.this,SecondActivity.java);
Intent.putExtra("nameOfValue",value);
startActivity(startSecondActivityIntent);
Then you can get this value:
getIntent().getIntExtra("nameOfValue",defaultValue);
Or you can use SharedPreferences
SharedPreferences sp = getSharedPreferences("nameOfPreferences",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("nameOfValue",value);
editor.commit();
And get this value in other activity:
SharedPreferences sp = getSharedPreferences("nameOfPreferences",MODE_PRIVATE);
String value = sp.getString("nameOfValue",defaultValue);

How can I persist a variable across Activities?

I have a File object called currentFile. When currentFile has been changed and the user attempts to open a new file without saving first a Save dialog is presented and if Yes is clicked currentFile is saved. The problem I'm having is that when I start a new Activity and press the Android back button, currentFile is set to null so changing the file, attempting to open a new one results in a NullPointerException. How can I persist currentFile across Activities?
There's several ways to do this, depending on what you want to do you should put on a balance what's better for your needs, one way is using extras to pass the variable value to another activity
Bundle extras = new Bundle();
extras.putString(key, value);
Intent intent = new Intent("your.activity");
intent.putExtras(extras);
startActivity(intent);
Another approach is to set a variable in your application context, creating a class that extends from Application and which reference you will be able to get from any activity using
YorApplicationClass app = (YorApplicationClass)getApplication();
app.getYourVariable();
And the last i can think of is using SharedPreferences, storing variables as key/value pairs that can be used for any activity...
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor edit = pref.edit();
edit.putString(key, value);
edit.commit();
//Any activity
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pref.getString(key, defValue);
Regards!
You can do this using Intents & Extras.
String yourFileName = "path/to/your/file";
Intent intent = new Intent(currentActivity, newActivity.class);
intent.putExtra("FileName", yourFileName);
startActivity(intent);
Then in your new activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String file = extras.getString("FileName");
}
Here is some reading on Intents: http://developer.android.com/reference/android/content/Intent.html
You could also do this using the Application class. I find it easier to work with than using bundles and intents.
To access your application class, just call getApplicationContext in any activity, and cast it to your class type which extends Application like so:
public class MyActivity extends Activity{
public void onCreate(Bundle bundle){
MyApplicationClass app = (MyApplicationClass)this.getApplication();
}
}

Categories

Resources