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");
}
}
Related
I'm very new to Android Studio Development and I was wondering how to do this, when I click a button on MainActivity, it will direct me to secondActivity where the text become visible (Originally TextView will not be visible until the button from MainActivity is pressed)
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
String status = "Success!";
intent2.putExtra("Status",status);
startActivity(intent);
}
});
I want to make an if-else statement for this (on SecondActivity page) where if user straight away go to SecondActivity, it will not display any text there. But if pressed the button on MainAcitivty page, the system will go to SecondActivity with the TextView displayed.
Thanks!
Basically, there are several approaches you can do that.
Use intents pass data
Sure you pass a boolean type or whatever you want into this intent, I think this is the approach you are trying to make here. So I can give you an example:
In your first activity you can do something like this,
button.setOnClickListener {
val intent = Intent(this#MainActivity, SecondActivity::class.java).apply {
val status = true
putExtra("Status", status)
}
startActivity(intent)
}
And in your second activity, in your need to override onCreate to parse your intents to decide your text want to display or not.
val status = intent.extras?.getBoolean("Status")
if(status) {
hideText()
} else {
showText()
}
the other approach you can deal with it is try to create singleton class to keep the status in this class, and based this singleton class status, you may choose to hide/show your text. However this solution isn't the recommended way to do it. Because global state is bad for testing and just pollute the code.
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
How to pass an object from one activity to another on Android
(35 answers)
Closed 4 years ago.
I am currently working on a project for my programming class, it is a d&d character creator I've decided to do for my final project. I am nearly finished with it but have run into one problem. I want to take the user's data from a screen where they create a character and store it into a screen where they can view their created characters, but I am not sure how to do this. This is the code from the create a character screen:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_char_screen);
Button btnSave = (Button)findViewById(R.id.btnSaveChar);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkData())
startActivity(new Intent(NewCharScreen.this, HomeScreen.class));
}
});
Button btnEx = (Button)findViewById(R.id.btnExplanation);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NewCharScreen.this, ExplanationScreen.class));
}
});
}
private boolean checkData(){
final EditText charName = (EditText) findViewById(R.id.txtNameInput);
if (charName.getText().toString().isEmpty()){
charName.setError("Enter character name");
charName.requestFocus();
return false;
}
return true;
}
}
If there is a need for the rest of my code or the project itself here is a link to a repository on GitHub:
https://github.com/cbetlinski98/MAD105-final_project
If you want to pass data from one activity to another one, you should pass it inside the Intent object, so intead of creating it inside StartActivity you can create it outside as a normal object, and use putExtra() to put data inside it.
Intent intent = new Intent(getBaseContext(), DestinationActivity.class);
intent.putExtra("OBJECT_PARAM_NAME", your_object);
startActivity(intent);
To recover data on the other activity you can use
String sessionId= getIntent().getStringExtra("OBJECT_PARAM_NAME");
Pass basic types
If you need to pass basic objects like int, float, strings, you can always pass them with putExtra() but to take them in the destination activity there are relative methods like getStringExtra() or getIntExtra() and many others.
Pass your class
If your user is a class defined by you, you can implement Serializable in that class, put it inside the intent with putExtra() and recover it from the other activity with getIntent().getSerializableExtra("OBJECT_PARAM_NAME") and then just cast it to your class before putting it inside an object
In order to pass information across intents:
Intent i = new Intent(this, Character.class);
myIntent.putExtra("paramKey","paramValue1");
startActivity(i);
Then in your activity to obtain the parameters:
Intent i2 = getIntent();
i2.getStringExtra("paramKey");
startActivity(new Intent(CurrentActivity.this, AnotherActivity.class).putExtra(KEY, DATA));
I want to make a one button goes to different activities, I have uploaded an image to show how I planned to do.
The idea is to come from Activity 1 or Activity 2 and find the same Layout and Button and go through it to Activity 7 or Activity 8 according to the Activity I was on.
I hope that I have explained my idea with a good way to be understood.
You need to pass an identifier or key with intent from your 1st part of activities as shown in the image and based on that key identify where the activity came from and where is it supposed to go. You can use if statements inside your button click function
Example
in xml for all your 3 button
<Button
android:name = "#id/button1"
android:onClick = "button1">
define other button and their properties
in java file
public void button1(View v)
{
Intent i = getIntent()
String key = i.getStringExtra("key");
if(key == "activity5")
{
Intent i = new Intent(this, Activity5.class);
startActivity(i);
}
else if (key == "activity6")
{
Intent i = new Intent(this, Activity6.class);
startActivity(i);
}
}
I need to randomly generate a button and then grab elements from it from the activity that the button opens. Specifically the universal ID of a "character" that I have specified in PersistentData. (That whole class works fine, though. The problem is between this activity and the next.) The child activity has multiple activities that can call it. (There are several activities with lists made from different characters from a pool, and each list has these buttons that are shown below, which all point to the same activity that loads information from PersistentData based on the data that its supposed to pull from said button.) The following 1 block of code is in the onCreate method for this activity. (Automatically generated, I just added this in after I called the layouts from the XML file)
for (fID = 0; fID < PersistentData.fName.size(); fID++) {
if (PersistentData.fName.get(fID) != null) {
Button[] Btn = new Button[PersistentData.fName.size()];
Btn[fID].setHeight(200);
Btn[fID].setWidth(200);
Btn[fID].setTextSize(40);
Btn[fID].setText(PersistentData.fName.get(fID));
Btn[fID].setTag(fID);
Layout.addView(Btn[fID]);
Btn[fID].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int btnID = fID;
gotoActivity(v);
}
});
} else continue;
}
Here is gotoActivity(). (In the class, not onCreate)
public void gotoActivity(View view) {
Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);
intent.putExtra("btnClicked", /*IDK WHAT TO PUT RIGHT HERE*/);
}
I have put several things there, actually. Mostly, they have been various ways of declaring a variable on the creation of the button.
Here's the TargetActivity.class
public class Fighter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fighter);
Intent intent = getIntent();
Bundle bundle =
intent.getExtras(); //line ***
**
TextView viewName = (TextView) findViewById(R.id.fighterName);
viewName.setText(PersistentData.fName.get(fID));
}
}
What should I put in the other class that I should get here**? (fID) is the thing that I'm trying to get. I have tried putting and getting fID using the methods as described in the Create an Activity page from Android and it continued to give me a NullPointerException at line *** (I split the line to be precise.)
Any help is appreciated. I would not be surprised if there is a better way to do this, requiring me to scrap all my work and restart. I would prefer not to, though lol. I will be checking this post periodically throughout the day, so if you have any questions or require more detail, just post or message me. Thank you beforehand.
I think the reason you got a NullPointerException because you started the activity before persing the extra.
In the gotoActiviy, make sure the extra(s) method are called before you start the activity. that is
public void gotoActivity(View view) {
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("btnClicked", "Strings");
startActivity(intent);
}
As you can see, a string was the extra, you can put any variable type as the extra just make sure at the activity being called, the same variable type gets the extra.
as an example
String getValue = getIntent().getExtras().getString("btnClicked");
Int getValue = getIntent().getExtras().getInt("btnClicked");
/** If integer was the value activity extra */
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