How to save an int for another activity? - java

I have one activity where the user writes in an EditText a number, then I am supposed to convert it to a string and then to an int, but I want to save that value because I am going to use it for another activity, it will be the max number of times that a botton can be pressed but I don't know how to save it from the EditText in a activity to an int in another activity.
Here the EditText of the first activity:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/texthome"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Ejemplo:15"
android:layout_weight="1"
android:textSize="20sp" />
Here the textview into int:
EditText conttext = (EditText) findViewById ( R.id.texthome );
String maxicont = conttext.getText().toString();
int maxcont = Integer.parseInt(maxicont);
UPDATE:
i get errors in:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button buttsave = (Button) findViewById(R.id.buttsave);
buttsave.setOnClickListener(new View.OnClickListener"here" {
public void onClick "here" {
Intent intent = new Intent(getApplicationContext(), GuessOne.class);
intent.putExtra("maxNumberPressed", conttext.getText());
startActivity(intent);
}
});
I get errors where i placed the "here" obviously it is not part of the code. It is only to see where the errors are.

You need to use Intents for that. A similar question was answered here:
Passing Values To Another Activity

When starting the other activity, make a bundle.
In the current activity, try:
Intent intent = new Intent(getApplicationContext(), <next activity>.class);
intent.putExtra("maxNumberPressed", editText.getText());
startActivity(intent);
Then in the next activity where you are using it, put this in onCreate method:
Bundle bundle = this.getIntent().getExtras();
String maxPressed = bundle.getString("maxNumberPressed");
Create a button with text as 'save' or something. then do:
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener{
public void onClick() {
Intent intent = new Intent(getApplicationContext(), <next activity>.class);
intent.putExtra("maxNumberPressed", editText.getText());
startActivity(intent);
}
});

How to pass data from an Activity to another can vary a lot, depending on how the Activities are related.
If you are passing data from a parent to a child Activity, you pass the information through an Intent when starting the new child Activity. Here's how you send the information:
itt = new Intent(this, ChildActivityName.class); // Create new Intent
itt.putExtra("MAX", maxcont); // Fill Intent with data
startActivity(itt, SOME_NUMBER_IDENTIFYING_THE_PARENT); // Start Activity
And here's how the receiving child Activity retrieves it:
void onCreate(Bundle savedInstanceState) {
...
Intent itt = getIntent(); // Grab the Intent created with this Activity
int maxcont = itt.getIntExtra("MAX", -1); // Retrieve data, default is -1
}
If you are passing data the other way, from a child to a parent Activity, the simplest way to pass through using startActivityForResult. The parent starts the child activity using this command:
startActivityForResult(itt, SOME_NUMBER_IDENTIFYING_THE_PARENT);
The Child then passes the information back to the parent just before it exits:
Intent itt = new Intent(); // Create new Intent
itt.putExtra("MAX_RETURN", maxcont); // Add data to the Intent
setResult(RESULT_OK, itt); // Signal to parent valid result
finish(); // End this Activity
Once the child calls finish(), the parent's onActivityResult() method will be invoked:
protected void onActivityResult(int requestCode, int resultCode, Intent itt) {
maxcont = data.getIntExtra("MAX_RETURN", -1); // defaults to -1
...
}
The Strings used in putExtra and getIntExtra are identifying keys for associated data, which are used all over the place in Android programming and beyond the scope of this question. Just make sure that the sender and the receiver of the data through the Intents use the EXACT same string!
If you need to pass information between two sibling Activities that are both active, the easiest way is through static public variables in each Activity. That's pretty basic; you should have no problem with these.
If you need to pass information between two sibling Activities that may or may not be Active, then you need to use a Broadcast/Receiver paradigm. But I think that method is overkill for what you are talking about.

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

Transfer data from one screen to another [duplicate]

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

How to pass and manipulate objects between activities using intents

This is my first issue with the Android lifecycleand I feel somewhat helpless:
In Activity A there's onCreate. That's the spot where I create an ArrayList called playerNames and ArrayList called moves. Also there's some more stuff happening in oncreate. In A's onStart I create a flag so I know which Activity is running in case I'd like to close all at once. In onDestroy the flag is set back to null.
Eventually I make an intent to get to Activity B where I take the moves list along. Works fine.
Now I'd like to make an intent from B to get back to A. What happens in the lifecycle when I attempt that? Obviously onCreate of A is called and leads to a NullPointerException regrding the playerNames list.
I'd like to store this ArrayList while B is running and get it back when I come back to A. Which method is the right one (onResume? onRestart?) and how do I store it? Do I really need SharedPreferences?
Thanks in advance for your kind help
On Activity A:
-Create an Intent, specifying wich activity you want to start
-Put data on that intent to be received by activity B.
-Start Activity for a result.
-On onActivityResult() verify that you have data to receive and do what you want with it.
On Activity B:
-On the onCreate() receive the data from Activity A;
-Modify the data as you wish;
-Create a new Intent;
-Put the data in the Intent;
-Set the activity result and the intent data.
-Finish activity B
Below is a sample of the steps I describe, what it does is have activity A start an Activity B, and passing it an empty ArrayList. Then on Activity B, the arrayList is populated and sent back to Activity A where the contents of the arrayList, are displayed on screen.
Code:
Activity A:
private static final int REQUEST_LIST = 1;
ArrayList<String> myList;
TextView listText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listText = (TextView) findViewById(R.id.mylist_text);
myList = new ArrayList<String>();
Intent i = new Intent(MainActivity.this, ActivityB.class);
i.putExtra(ActivityB.EXTRA_ARRAY, myList);
startActivityForResult(i, REQUEST_LIST);
}
#Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == REQUEST_LIST) {
myList = (ArrayList<String>) data.getSerializableExtra(ActivityB.EXTRA_ARRAY);
StringBuilder text = new StringBuilder();
for (int j = 0; j < myList.size(); j++) {
text.append(myList.get(j) + " ");
}
listText.setText(text.toString());
}
}
Activty B:
public static final String EXTRA_ARRAY = "com.example.androidtest.mainactivity.array";
ArrayList<String> myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityb_layout);
myList = (ArrayList<String>) getIntent().getSerializableExtra(EXTRA_ARRAY);
for (int i = 0; i < 10; i++) {
myList.add(String.valueOf(i));
}
Intent data = new Intent();
data.putExtra(EXTRA_ARRAY, myList);
setResult(Activity.RESULT_OK, data);
finish();
}
Attention: You cannot forget to declare your Activity B in the manifest File. Also pay attention on how the activities know what data to send and collect, through constants created in the classes, wich must be consistent, so avoid using literal strings, and use defined constants.
From Activity B you can come back to the previous A instance using:
Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
This will clear all current stack and go back to the A instance ( http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP ). As long as your Activity doesn't get destroyed, you'll have all data there.
Anyway, you should consider use Activity's save instance state capability ( http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState%28android.os.Bundle%29 ).

Change class view using buttons

I'm trying to have a program go from one class to another by the press of a button. I know this needs to be done with intent, but I'm not sure exactly what action to use for intent. Also, i would rather not try to use OnClickListener since it seems to me to be a bit excessive for what I need to do. Though I could be wrong and I'm just over thinking it. Here's what I have for the code:
public void loginScreen(View view) {
// Should take user to the next view when button pressed
Intent intent = new Intent(this, LoginActivity.class);
Button login = (Button) findViewById(R.id.button1);
intent.getData(login);
startActivity(intent);
}
I want it to go to the next screen when only button1 is pressed so i don't know if just lines 3 and 6 are the only ones needed, but it won't work if it's just those two. I believe the problem is getData, i don't know what to put there, but i know getData's wrong. I'm probably also missing something else, but I don't know what.
Also, forgive me if this isn't easy to follow, first time trying to ask a question here.
In your XML file you can declare your on click:
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="loginScreen" />
Then in your Activity:
public void loginScreen(View button) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
Here is the onClick View API
Name of the method in this View's context to invoke when the view is
clicked. This name must correspond to a public method that takes
exactly one parameter of type View. For instance, if you specify
android:onClick="sayHello", you must declare a public void
sayHello(View v) method of your context (typically, your Activity).
Note that if you add an onClick to a Fragment layout it will still need to be caught in the Activity.
Without explicitly setting an onClickListener:
<button
...
android:onClick="loginClicked" />
public void loginClicked(View v) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
Also setting an onClickListener explicitly is not overkill.
Your question isn't entirely clear, so let me know if you need more and I'll edit my answer.

Make my class take an argument

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");

Categories

Resources