Passing the user selection value from one activity to another - android

I am making a small calculation game.
on the main screen there would be a RadioGroup
o Easy o Medium o difficult
Button Continue
then after the user selects this and presses continue then on next page another radio group
o Addition o Subtraction
Button Start
Now I want to display questions depending on the selection of radio buttons from there 2 activities.
How can I do that, for a single radio group I can use changeListener...But here I have to consider values from 2 radio groups simultaneously.
So how to do that. I tried my best to explain this using example and representation too.
Thanks

Use a bundle with Intent extras to pass data between activities.
Intent i = new Intent(getContext(), SecondActivity.class);
Bundle b = new Bundle();
b.putExtra("key", value);
i.putExtras(b);
startActivity(i);
http://developer.android.com/reference/android/content/Intent.html#putExtras(android.os.Bundle)
and in your SecondActivity
getIntent().getStringExtra("key");
http://developer.android.com/reference/android/content/Intent.html#getStringExtra(java.lang.String)

For the apps that I've been involved with I've been using a application object to store state variables that need to be visible in more than one activity. The application object gets created before any activity objects, and is the last thing to be destroyed when the application is closed, so it's a good place to store state variables. You're allowed one application object per app, and the class type needs to be declared in the manifest. It sounds like your difficulty variable and your add/subtract are state variables, so I'd suggest you go down this path.

You may also want to use the SharedPreferences if you want to save the value longer the current instance.
See for more details.
http://developer.android.com/guide/topics/data/data-storage.html#pref

Related

Saving data from Spinners, RadioGroups ,EditText, across several activities to re-use

Being very new to android I have limited experience despite having built several basic apps, so I would be grateful if you could structure any replies with this in mind.
I would like to: after a signup/login section, Collect user selections from spinners, radio buttons and text input over two or three Activities and in a fourth activity display the collected data so that it can be checked going back to make changes if need be.
When correct move on to a fifth activity where the data is structured and emailed to an email address given on the signup section. I have made the basic structure including Spinners with String arrays and have indeed made an app that works as required, passing data with extras to the next activity, however I would like to pass data to the final activity not just the next one in line. I do not really want to use a database if I can avoid it, but possibly so when all the data has been collected and reviewed, and having tried Sharedpreferences when things go wrong and the app crashes I struggle to find out why, so in an attempt to make things clearer I've stripped all that out back to basic structure leaving just working spinners, radiogroups and navigation buttons and here I am.
Being that the app structure I have left has 5 Activities and 5 class files I was hesitant to post the code as I was not sure that was the done thing, however I am willing to be guided on the question.
In your first activity, after collecting the data from the user, you can add them to your Intent using Intent.putExtras(Bundle). This is an example using a username that the user entered in an EditText.
String username = myEditText.getText().toString();
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle extras = new Bundle();
extras.putString("username",username);
intent.putExtras(extras);
startActivity(intent);
In the second activity, you can get the data from the extras in your onCreate like this:
Bundle extras = this.getIntent().getExtras();
String username = extras.getString("username");
When going to the third/fourth... activity, you can do the same steps to carry your data in the Intent you use to open the activity. First get the data from the extras, and then add them to the extras of the next intent.
You would probably want to make the variables global or because you will probably want to use them inside an onClick where they will not be accessible.

Can I send a View to another Activity?

my question is: If for example I have a RelativeLayout in Activity1, can I send that RelativeLayout to Activity2?
In my app I have 3 different RelativeLayout in Activity1, and if the user Clicked on one of those RelativeLayout I would to send it to my next activity. Any ideas on how to do that?
From your comment it appears you need to load a different layout based on user's selection from previous screen. This problem can be tackled in several ways. One of them is to pass the user preference from Activity1 to Activity2. To do this, in Activity1:
int choice = 0; // assuming user made choice 0
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("choice", choice);
startActivity(choice);
Now, you can read the second value in Activity2 and accordingly load your layout (i.e. different view) as (within onCreate()):
int choice = getIntent().getIntExtra("choice", 0); // default choice 0
switch(choice) {
case 0:
setContentView(R.layout.layout0);
break;
case 1:
setContentView(R.layout.layout1);
break;
default:
setContentView(R.layout.layout2);
}
Thus, based on user's choice you can choose a different layout and write you business logic accordingly thereafter.
Another option you have for your use case is that you define different activities for each of your layouts and then call startActivity() to appropriate activity. This will separate out the business logic of handling the different layouts and may therefore be easy to maintain.
You can also go the fragment way but, ultimately it would also employ one of the above methods. Note that the method you choose highly depends on your use-case and therefore I cannot make that decision for you.
You can't do that since each Activity has its own layout.
What you can do instead is send the data needed to setup your second Activity's RelativeLayout so that it looks like the one in your first Activity via Intent extras.
I'll just give you an idea , you can send data from the first activity to the second using Intents , however you can create a layout dynamically using data received by the second Activity and adding all the parameters you need.
I hope it will help you

How do I create a new screen that's a copy of the prior page?

I'm working on an app that allows you to track the number of rows and stitches per row in a crochet or knitting project. I'd like to implement a "New Project" button that creates a new activity for the new project complete with black counts and everything.
The only thing is, I know how to create a new activity/page manually -- I have no idea how to do this on the push of a button -- that is, not needing to create x number of activities to preload, but instead, letting the "New Project" button create the new activity -- and have it be a copy of the prior one.
I hope this question is clear enough!
Before switching to another activity you can save the current state of the current activity in any permanent storage, like Shared Preferences... along with a counter as an id for each view included in ur current activity.
Then in new activity you can create all the views again with the same details from the Shared Preferences or so..
You can also use a serializable class.. but i will take a long route to save all properties related to a view.
To reate a new activity on the push of a button you can simply get your button from your layout, add an onclicklistener and start a new Activity from that. Have a look at this stack overflow question:
How to start new activity on button click
In case you want the new Activity to be a copy of the previous one, it is probably best to create a new Activity and apply the same data and UI state as the previous one.
To do this, you can add all Activity data to the extras of the intent to start the Activity (Lists/vectors can be added using the parcelable interface) and then you can use this data in the on create() of your new Activity. (By checking if a certain extra is null or not, you can differentiate between the first activity of your app or all subsequent ones)
If you want me to be more specific, please post your source code so I can have a look at your data model.

Going back to activity with EditTexts populated. - Android

I have Activity A which has editTexts and from activity A, a user can go to activity B and fill out more information. Once the user is done on activity B, they press a button and come back to A. I would like to come back to A with the information that the user had filled in to be already there and not have to fill in the information again.
Currently, this is my code for coming back from B to A.
Intent intent = new Intent(NewAddressActivity.this, CreditCardActivity.class);
intent.putExtra("newAddressEntered", true);
intent.putExtra("newAddress", (Serializable) newAddress);
startActivity(intent);
With this code, when the user comes back, the fields on activity A are empty.
*Note - I need to pass data from B to A when going back.
Any tips on how to do this properly would be greatly appreciated.
Thanks
You are on the right track. You can do that using .putExtra
You can pass extra data via the intent using intent.putExtra("key",
text_field.getText().toString()) on the intent before you send it (in
the first activity) and getIntent().getExtras().getString("key") in
the second activity.
This is assuming text_field is your EditText you want to pass the
value from. You can change "key" to whatever you want, too.
You're actually not "coming back", but starting a new empty intent, thats why the fields are blank again. Instead, you should just call:
finish()
Regarding filling related fields from different Activities, I wouldn't recommend that, but if you need to keep it that way, you may have a singleton class to store all field values for instance.
Also, you could send B fields to A as activity results.-
http://developer.android.com/training/basics/intents/result.html
But still, I would recommend keeping all related fields in one Activity.
Change the launchmode of your Activity A (CreditCardActivity) to singleTop in manifest file and try. The documentation says
If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.
So your activity should retain old values.

Using Primitive Data Types in another Class and the res/menu/.xml file

I'm a very new to Java. I thought I was doing okay but have now hit a brick wall, so to speak.
The idea is I use the 'home button' '_menu' for the user to choose one of 26 formats. The format they choose has 3 variables. Those 3 variables are then used in the first xml view, along with 2 user inputs to calulate another variable. This variable is then used in a second xml view, along with a third user input here, to calculate the final answer.
I have created the 26 choices and if for example I choose option 5, on the emulator screen I see all the correct values associated with this choice. I don't think those values are getting stored anywhere. I say this because if I come out of that view and return back into it, it's not showing, as in my example, choice 5. It's showing its initial state, as though I was going into it the first time. I assume it's something to do with launching this activity from the start but is there anyway around this. Or really where do I start.
My second question is with the integer variables that I created from this choice. I need to pass them into another java file for the first set of calculations. I've tried to pass the variables/data with the, 'new intent putExtra' but can't get it to work. But I don't think I can use this anyway since the I don't want to launch the second view directly from the res/menu/ .xml view.
Not sure if this is making sense to anyone. Can someone help point me in the right direction?
I don't quite understand your first question, but it sounds like you're launching a new activity and when you quit and come back to it, everything is reset. If you're launching a new activity after selecting the options from your phone's menu button, you should implement a method that saves data to the shared preferences of the main activity. This method should be called on the activities onPause(), onDestroyed(), or onStop() method. You can also add a method on onResume() where the activity checks if there's any data stored in shared preferences and if so, make the desired changes.
As for your second question...I kinda don't understand it either. new intent and putextra is used when you're starting a new activity and want to pass data to it. Views are not "launched" they are only inflated and brought on display whenever you want. I did an app once where I had everything in one activity and just using setContentView() method all the time. In the long run, it just complicated everything. It is easier to keep things simple and launch activities. Here is an example of some variables being passed to a new activity:
On my main activity (FirstActivity) I have:
(when newActivityButton is clicked)
case R.id.newActivityButton:
Intent mIntent = new Intent(FirstActivity.this,SecondActivity.class);
String[] luckyNumbers = {
luckyNumber[0].getText().toString(),
luckyNumber[1].getText().toString(),
luckyNumber[2].getText().toString(),
luckyNumber[3].getText().toString(),
luckyNumber[4].getText().toString(),
luckyNumber[5].getText().toString()};
mIntent.putExtra("luckyNumbers", luckyNumbers);
mIntent.putExtra("message", messageField.getText().toString());
FirstActivity.this.startActivity(mIntent);
break;
luckyNumbers[] is an array of textviews.
Then on my NewActivity onCreate(), I have:
message = getIntent().getExtras().getString("message");
Log.i("TAG", message);
luckyNumbers = getIntent().getExtras().getStringArray("luckyNumbers");
cv.setLuckyNumbers(this.luckyNumbers);
cv.setMessage(this.message);
where cv is just a custom view I created with its own methods

Categories

Resources