Passing String Values between Activities using intents - java

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

Related

How to pass a parameter out of an onClick

New to Android Studio. I'm creating an app project for practice and I am trying to create a Menu Activity. I want to test to see if I can mute sounds and hide the display of text (score) via a Menu UI. I get that I can use Intent to pass values back and forth between activities and that I can use those values to turn features on and off across the app.
I cannot figure out with a button and onClick how to get a variable to change so that I can pass it via Intent. I've only seen it done INSIDE the onClick. I'm trying to change the variable OUTSIDE the onClick.
Example Code:
public class Menu extends AppCompatActivity {
private boolean soundOn = true;
private Button isSoundOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
isSoundOn = findViewById(R.id.isSoundOn_button);
isSoundOn.setOnClickListener(v -> {
soundOn = false;
});
Now when I attempt to access the soundOn parameter and pass it on via Intent to another activity the value remains true, it never changes after the button is clicked.
I did figure out one trick, I can use intent and pass the value to the same activity, like so:
soundOff.setOnClickListener(v -> {
Intent intent = new Intent(Menu.this, Menu.class);
intent.putExtra("soundOn", false);
startActivity(intent);
This reloads the Activity after the button is clicked, it makes it appear as though a glitch happened as it is run, but I think that issue could be resolved via altering the transition animation...I think. However, this seems like a clumsy approach, especially in a Menu Activity that could have numerous settings to edit (sound, score, language, timer, color, background, etc.).
I get that I can have the onClick go back to the original Activity with the change, but I want to create a menu where I can have multiple selections made and then pass them all back to the original Activity.
I hope this makes sense, I know this is rather basic, but I'm new to this and my searching hasn't been able to yield a solution. Thanks.
If you are doing an intent to the same Activity you should retreive your intent on the onCreate method:
isSoundOn = intent.getBooleanExtra("soundOn", true) //true is the default parameter in case intent does not contain that key;
That way you are always checking your intent in case you need it.
You also need to use your variable in the intent; right now you are always setting it to false:
soundOff.setOnClickListener(v -> {
Intent intent = new Intent(Menu.this, Menu.class);
intent.putExtra("soundOn", soundOn);
startActivity(intent);
}
There are other solutions, for example: you can use SharedPreferences for persisting your values and then call this.recreate to recreate Activity again and avoid using intents. Then you can retreive your SharedPreferencesvalues on the onCreate method to do whatever you want.
Now when I attempt to access the soundOn parameter and pass it on via
Intent to another activity the value remains true, it never changes
after the button is clicked.
Lets start with keeping track of soundOn
When Menu activity is first launched soundOn = true
When isSound button is clicked soundOn = false
Intent intent = new Intent(Menu.this, Menu.class);
intent.putExtra("soundOn", soundOn); // false is the value that is extra.
startActivity(intent);
When MenuActivity is again launched due to the intent soundOn = true this is because of this line
private boolean soundOn = true; //<---
You are passing Extra in intent but you arent storing the intents extra value in soundOn
Thats why it is true always
to solve this use need to Get the Intent Extra that you have passed and we do it in onCreate method
private boolean soundOn = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Intent intent = getIntent();
if(intent != null) { // we need to get this cause when we first start our app we dont start it with any intents
soundOn = intent.getExtra("soundOn");
}
}

Bundle is null from third activity

hi im using bundle to pass a string from my MainActivity to my second activity which is sub genre. but i also need the same string in my third activity.
i use my code like this in my main acitvity
Bundle getGenre_Bundle = new Bundle();
if (genre.equals(selector.Crime)) {
Intent i = new Intent(getBaseContext(),Crime.class);
getGenre_Bundle.putString("crime",selector.Crime);
i.putExtras(getGenre_Bundle);
startActivity(i);
then i call it in my second Activity using
Bundle p = getIntent().getExtras();
Genre = p.getString("crime");
this works great but if i try to call it on my third activity it returns an error in my log that my firebase child(Genre)cant be null.
Ive fixed the problem by making a new bundle in my second activity that recollects the String to pass to my third activity. but it seams a bit of a messy way of doing it. is there an easier/better way to pass strings to any activity?
You can fetch entire bundle from your previous activity in second activity and simply set in intent with putExtras()
Bundle old = getIntent().getExtras();
Intent thirdActivity = new Intent(this,thirdActivity.class);
thirdActivity.putExtras(p);

Passing values from Activity2 to Activity1 without visiting Activity1

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
}

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();
}
}

Take the information inside a ListItem and send it to the next Activity

I am relatively new to the Eclipse & ADT plugin world, so any answers can you please explain what it's doing? It would be very helpful.
Basically, I have a list in one activity that will be populated by a HTTP request from a database API, this I am still working on. However, what I wish to know, is am I able to take the string in the ListItem and give that to a TextView in the next activity?
So for example, I tap 'Record 1' and it takes 'Record 1' and puts it inside a variable, then sends the user to the next screen, and inserts the variable into a TextView. Is this possible?
Thank you.
Get what you want from the adapter, then put that into the Intent that starts the new activity:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String string = parent.getAdapter().getItem(position);
Intent intent = new Intent(this, nextActivity.class);
intent.putExtra("text", string);
startActivity(intent);
}
});
In the new Activity you then get the Intent that started the new Activity and get the String you put into it:
String data = getIntent().getStringExtra("text");
Implement the setOnItemClickListener() for the listItem where you will capture the listItem clicked and the String you require and then using intent.putExtra(String id, STRING_VALUE) you can pass your string to the next activity.
Yes, it is possible.
You can send information to another activity using Extra. See this code below:
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT);
You use putExtra to put your data do you want to send to the activity. In the example NotesDbAdapter.KEY_ROWID is the name you give to access the data and id is the data itself.
And, this is how you can get the data from the activity:
Bundle extras = getIntent().getExtras();
mRowId = (extras == null) ? null : extras.getLong(NotesDbAdapter.KEY_ROWID);

Categories

Resources