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));
Related
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");
}
}
We have an aspx page with a form in it and we can only process this form in a browser-based environment (ie we cannot create a web service for it.
What we want to do is that we want to process this information in an android application. We want to send some initial data to this page, let the user fill it, submit the form, and then return the results to the calling activity, so we can show a proper message and act accordingly.
let me give an example for this usecase:
We are in activity A and in this activity we have a button that triggers the start of our journey:
//we are in activity A
mOurButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("additional_data_we_need", adittionalData);
startActivityForResult(intent, REQUEST_CODE);
}
});
Now we are in activity B and here, we should comunicate with that webpage that I was talking about, passing it the additionalData that is in this activity's extra bundle (it is acceptable if we do it using query strings or any other way).
After the user fills the form, and hit submit,we do some operation on it and return some results to another (web)page or in the current (web)page's postback (again it is acceptable if we use query strings, post method or any other way; whicever way that works for this senario). We get this returned result in android side and then get the result to ActivityA :
//we are in acitivity B
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
int adittionalData = getIntent().getExtras().getIntExtra("adittional_data_we_nedd");
//this is the first place that I don't know what to do
callTheWebPageAndGiveItTheData(adittionalData);
}
public void SomeListenerOfTheReturnedDataFromTheWebpage(Bundle returnedData //doesn't necessarily need to be of bundle type) {
intent intent = new Intent();
intent.putExtra("return_bundle", returnedData);
setResult(Activity.RESULT_OK, intent);
finish();
}
What can I do to achieve this goal?
Thanks in advance for your kind answers
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 */
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 7 years ago.
how am i going to pass an integer value from the textview to the next activity?
currently im using string as my sharedpreferences and everytime im changing it to int my app force close.
here's my code on mainactivity
int scoreText=50;
public static final String PREFS_COIN= "MyPreferenceFile";
protected void onCreate(Bundle savedInstanceState) {
public void checkAnswer()
{ String answer=answerText.getText().toString();
if(isCorrect(answer))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("What are you a GENIUS?!");
builder.setMessage("Nice one, Genius! You have P10!");
builder.setIcon(android.R.drawable.btn_star);
builder.setPositiveButton("View Trivia",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
scoreText+=10;
scoreNew=scoreText;
scoreTxt.setText(""+ scoreNew);
SharedPreferences settings2=getSharedPreferences(PREFS_COIN, 0);
SharedPreferences.Editor editor2=settings2.edit();
editor2.putString("coins", scoreTxt.getText().toString());
editor2.commit();
Intent intent=new Intent(getApplicationContext(), Luzon1Trivia.class);
startActivity(intent);
overridePendingTransition(R.animator.transition_fade_in, R.animator.transition_fade_out);
//startActivity(new Intent(Luzon1.this, Luzon2.class));
;} });
AlertDialog alert = builder.create();
alert.show(); // Show Alert Dialog
scoreTxt.setVisibility(View.GONE);
//disable all the buttons and textview
answerText.setEnabled(false);
answerButton.setClickable(false);
}
}
everytime the user guessed the correct answer, a +10 coin will be given. the problem is, in the second activity i cannot add/subtract the sharedpreference value since its declared as string. what happens is "60 +10" appears in the textview
here's my code in activity 2
public static final String PREFS_COIN= "MyPreferenceFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.luzon2);
scoreTxt = (TextView)findViewById(R.id.score);
SharedPreferences settings2=getSharedPreferences(PREFS_COIN, 0);
scoreTxt.setText(settings2.getString("coins", ""));
You shouldn't use Shared Preferences to pass information between activities, Shared Preferences is inteded to be used to store persistent information when the Application is destroyed.
To pass information between activities you should use an Intent (the same Intent that is used to start the "destiny" activity)
Intent newActivityIntent = new Intent(originActivity.this, destinyActivity.class);
newActivityIntent.putExtra(KEY_STRING, integerValue);
this.startActivity(newActivityIntent);//Assuming you're starting an activity from another one
Edit: This has been also answered here and here. I would recommend you to search before posting a question.
You have to parse the string and get a float/integer value.
int myNewInt = Integer.parseInt("theString");
in your case you have to do :
int myNewInt = Integer.parseInt(settings2.getString("coins", ""));
And I think you need to set the default value as 0 in your
settings2.getString("coins", "0")
Just use a static variable to hold this. It's much easier to implement since all you have to do is call it instead of passing it around to other intents like a mad man.
public static int coins;
To call it use your class instance name:
MyClass.coins;
So to add:
MyClass.coins+=10;
scoreTxt.setText(Integer.toString(MyClass.coins));
MyClass is your class. If your class is called MainActivity then it will be that (MainActivity).
.coins is the variable inside that class, your just making a reference to that variable.
The nice thing about static is using it as a learning tool. It's a great way to explore instances and references.
Or you can add all of this to every activity, and don't forget about handling device rotations:
Intent i = new Intent(getApplicationContext(), MyClass.class);
i.putExtra("coins","value");
startActivity(i);
To retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
coins = Integer.parseInt(extras.getString("coins"));
}
To set:
coins+=10;
scoreTxt.setText(coins);
Device rotation: Passing Extras and screen rotation
Well I have a main Screen with 5 buttons. Each time a press a button I want to go a new screen. So far I have other 5 classes (each for each screen) and 5 xmls. But Iam sure that there will be a better way beacuse this screen and the xmls are the same, and what I want to do is change some texts and some data I fetch from a database. I am sure that I can ony another class and only one xml and then pass the values that I want as arguments. (Imagine that in its final state my app must have 15 buttons, so I think it is too mych waste of space and unnecessary to have 15 .java files and 15 xml files that look the same and only some values of images and textviews change). My code for main activity is:
public class MyActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main2Theme();}
private void main2Theme() {
setContentView(R.layout.main_new);
Button Button100 = (Button)findViewById(R.id.Button100);
Button113.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(this, OtherScreenName.class);
startActivity(i);
}
}); //and so on for 15 buttons
My OtherScreenName.class is:
public class OtherScreenName extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Theme();
}
#SuppressWarnings("null")
private void Theme() {
Log.d("SnowReportApp","Do first thing");
setContentView(R.layout.otherscreenname); //THIS CHANGES IN EVERY CLASS DEPENDING ON THE ID OF THE BUTTON
String result = "";
InputStream is = null;
StringBuilder sb=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//() before
nameValuePairs.add(new BasicNameValuePair("ski_id","OtherScreenName"));
TextView text1 = (TextView) findViewById(R.id.otherscreenname_1);
//THESE 2 CHANGE DEPERNDING ON THE BUTTON PRESSED
//perform action.....
//AND ALSO HERE I NEED THE ID OF THE BUTTON
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(OtherScreenName.this,MyActivity.class);
startActivity(i);
}
});
Can anyone suggest how to give arguments to my class and what it should be the type of them?
If I understand your question correctly, you want to pass arguments to the activity. Normally it would be done through the class constructor, however, activities can't have user defined constructors, only the default one; they can be instantiated only indirectly via intent creation. If you need to pass data between activities, do it by putting extras to bundles, for example:
bundle.putInt("intName",intValue);
then you can extract the data from bundle by
int intValue = bundle.getInt("intName");
Put extras before starting the activity:
Intent i = new Intent(this, YourActivity.class);
Bundle b = new Bundle();
b.putInt("intName",intValue);
i.putExtras(b);
startActivity(i);
and then read the extras in the onCreate method:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
int intValue;
if (b != null)
{
intValue= b.getInt("intName");
}
}
The same way you can pass other data types as String boolean etc. If this is not sufficient and you need to pass some more complex data, then use Parcelable interface.
You can pass parameters with an Intent by adding extra's to it, something like the following:
Intent i = new Intent(this, MyActivity.class);
i.putExtra("paramName", "value");
startActivity(i);
In your activity you can use the getIntent() method to retrieve the Intent and extract your parameter(s) from it:
Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getString("paramName", "default value");
You can place all the different text and data in your Intent, but you can also decide based on the value of an Intent parameter which data and text to retrieve. If it is a lot of data or text you are probably better off using the second approach.
If you want to pass object instead of simple data, you must use parcelable objects as it´s explained in: [http://developer.android.com/reference/android/os/Parcelable.html][1]
Reading and writing with parcelable objects is very similar to the way with a simple data
Intent intent = new Intent(this ,newthing.class);
Bundle b = new Bundle();
b.putParcelable("results", listOfResults);
intent.putExtras(b);
startActivityForResult(intent,0);
Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getParcelable("results");