Getting values passed to new Activity - java

I am following the android programming tutorial here: http://developer.android.com/training/basics/firstapp/starting-activity.html
It details how to start a new activity and send some data to it.
I have these activities now: SplashActivity, LoginActivity, RegisterActivity, and MainActivity.
SplashActivity does a quick preference read to see if you are logged in. If you are, it passes a user ID to MainActivity thus:
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(EXTRA_USERID, userID);
Where userID is a user ID number as String.
Both Login and Register Activity does its thing, which returns a valid user ID from network. They pass it to main activity using the same code snippet above.
This is defined in all three activity classes: public final static String EXTRA_USERID= "com.example.myfirstapp.USERID";.
Following the tutorial, I have this code in the onCreate method of MainActivity:
Intent intent = getIntent();
String userID = intent.getStringExtra([LoginActivity].EXTRA_USERID);
Notice the square bracketed peice of code [LoginActivity]. I don't know what to put here. I don't know which activity starts the MainActivity. Putting LoginActivity seems to only work when the login activity starts the main activity. When people register or the user ID is read from preferences in SplashActivity, the return value is an empty string.
What is the method for determining which activity started MainActivity? Or is there a way to simply get the value passed to the activity without specifying from which Activity it is created?
Any help would be appreciated.

The first argument to putExtra is a string key you define that can be used to extract the value later on. The key should start with your app's package name.
It doesn't matter where you define the key as long as you pass the right key when you launch the intent - e.g.:
public class MainActivity extends Activity {
public static final String EXTRA_USERID = "com.my.app.USERID";
}
If you launch MainActivity from LoginActivity or SplashActivity, you'll want to reference the same MainActivity.EXTRA_USERID string anywhere the intent is created. It might be easier to define a common function that takes the user ID and creates an intent with the right extra parameters.

Related

how can forward data form i activity to 3 activity via 2 activity

I am making my own project but I am stuck.
Getting the information from the user in the first activity is working just fine.
But when I try to get those numbers, ints, in the third activity via a second activity, it is showing me the default value.
I am trying it using an Intent, but it is not working.
Intent intent = new Intent(this, active.class);
Intent intent2 = new Intent(this, BMR_Active.class);
intent.putExtra(EXTRA_TEXT_height,height );
intent.putExtra(EXTRA_TEXT_weight,weight);
intent.putExtra(EXTRA_TEXT_age,age);
startActivity(intent);
It is giving me a default value i.e. 0(I have given) in BMR activity then i am going via active activity.
Your putExtra method via intent would work fine, but are you also running putExtra BEFORE starting the third activiy?
The data is first passed from first activity to second activity, then from second activity is passed to third activity using the same method.
Additional Note:
In cases like this, I would usually use fragments instead, I would store the data in the activity and fragments will obtain the datas via getActivity(). This will eliminate the needs of multiple passing of data around.
Based on what you said in your comment about passing data straight from Activity 1 to Activity 3, then what you can do is the following:
Page1.class:
Intent toPage3 = new Intent(Page1.this, Page3.class);
int myNum = 5;
toPage3.putExtra("Number", myNum);
startActivity(toPage3);
Page3.class:
Intent receiveIntent = getIntent();
int numFromPage1 = receiveIntent.getIntExtra("Number");
I believe that this should answer your question. numFromPage1 will be an int containing the value from Page1.

sum up the score of two quiz and show it to the menu

So guys I have two quiz and when the user do both of them i want to show into the menu the sum of user's score.Here is the part of my code that has relation with my question:
Quiz 1:
Intent intentt=new Intent(multiplechoicek1.this,menuaskisewn1.class);
intentt.putExtra("scoree",mscore);
startActivity(intentt);
Quiz 2:
Intent intent=new Intent(diagwnismakefalaio1.this,menuaskisewn1.class);
intent.putExtra("score",mScore);
startActivity(intent);
Menu
Intent intent=getIntent();
int score=intent.getIntExtra("score",0);
Intent intentt=getIntent();
int scoree=intentt.getIntExtra("scoree",0);
int athroisma=score+scoree;
currentscore.setText("To σκορ σου είναι: "+ athroisma +"/24");
When i test the app it shows only the sum of correct answers of 1 quiz..i suppose that this is because when it calls the oncreate method when one quiz is over the intent from the second quiz gets the default value...so it nevers sums up the correct answers of both quiz.(I didnt use sharedpreferences cause i dont want to store data after the app is closed).Any ideas? Thank you and sorry for bad English :)
As you are starting "menuaskisewn1" activity from "multiplechoicek1" and "diagwnismakefalaio1" with "startActivity" method, it will create new activity of "menuaskisewn1" and then "menuaskisewn1" will get only extras from that intent which was called last time. so you have only one intent extra instead of both at a time.
Also you don't want to save data in shared preference.
In this case you can create a class which extends "Application" class and then take two static variable within it. In this way you can access those variable in every activity and also you can sum up those two variables in which ever activity you want. By using this way, you don't have to pass those in intent extras.
Make sure your manifest file will use that application class.
It's not clear how and when you execute the code for opening the menuaskisewn1 activity, but it seems that you are opening it twice, why?
Then when menuaskisewn1 is opened, it seems like you want to get 2 different intents with:
Intent intent=getIntent();
but what you are doing is getting the same intent twice and this is the intent that started the activity, because an activity is started by 1 Intent only.
So this intent contains either the extra with key "score" and this is saved in score or the extra with key "scoree" and this is saved in scoree but not both.
So one of the variables score or scoree is 0 and when you add them the result is the same as one of the variables.
What you can do is start only once the activity and put 2 extra values:
Intent intent=new Intent(multiplechoicek1.this,menuaskisewn1.class);
intent.putExtra("score1", mscore1);
intent.putExtra("score2", mscore2);
startActivity(intent);
and get the values when the activity opens:
Intent intent=getIntent();
int score1=intent.getIntExtra("score1",0);
int score2=intent.getIntExtra("score2",0);
int athroisma=score1+score2;
currentscore.setText("To σκορ σου είναι: "+ athroisma +"/24");

getting the text from a TextView from a different activiy

I have 2 activities: Activity_A and Activity_B. On Activity_A I have a TextView with the id "MyTextView". How can I get its text from Avtivity_B?
I have tried to do this in Activity_B main Java file:
txtv = (TextView) findViewById(R.id.MyTextView);
txtv.getText().toString()
But this didn't work.
Is there any way to this without Intents?
You should get the content on the Activity where you have it and then send data from activity A to activity B with the intent:
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("fromActivityA",textView.getText());
And then you have to use getExtra() method on activity B for getting the data you send from activity A.
Hope you can find this helpful!
The challenge is that when an activity is not visible, it has been paused, and is no longer available. Also the id used in findViewById may refer to an id in the other activities layout file. Using an intent to pass the data when moving between activities is a good solution, or if you really need access to that data from different activities you could store it in shared preferences, in a database, or as a static field on the activity class itself.

Confirmation on my Understanding of Beginning Android Concept (Using Multiple Activities)

I am a beginner at android development, and have reached the end of Building your First App. Before I move on, I would like to confirm and validate my understanding of using multiple activities and communicating from one activity to another.
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
1) Is my understanding correct that the second paramater in the constructor for Intent (Intent intent = new Intent(this, DisplayMessageActivity.class)) serves as a reference for startActivity(...) and reflection is used to call the method onCreate() in the class DisplayMessageActivity since the class DisplayMessageActivity was given as a class object?
2) What is the use of the first paramater (the context one in the constructor)? (Basically how does Android use the first parameter, a brief description please, to start the activity)?
3) As seen in the tutorial, last part of building your first app, it advises me to declare a variable as such: (public final static String EXTRA_MESSAGE = "me.marshac.myfirstapp.MESSAGE";). I know the purpose of this declaration and initialization, but why don't I have to specify the full package name (me.marshac.myfirstapp. (...) .MESSAGE) and where is the MESSAGE variable coming from? The only two variables similar to that are both local variables in sendMessage() and the other activity's onCreate(), but they are different case and local?
I am sorry for the very in-depth inquiries, I want to establish a firm understanding of the beginner concepts before I move on to intermediate/advanced ones.
1) Yes. I think that's what is happening behind the scenes. If you want to know exactly how they did it, you can go to read the Android OS source code. It is open source, you know. Just Google it!
2) Android uses a stack for storing activities. When you first started your app, it's like this:
MyActivity
Then when you start another activity, a new activity object is pushed onto the stack
DisplayMessageActivity
MyActivity
When you tap the back button, an activity from the stack is popped.
If you didn't give this as the parameter, how would the OS know where to push the new activity onto?
3) I think this is just a convention of some kind. I usually use simple names like message, and it works! It's similar to asking why should I name a class in PascalCase and a local variable in camelCase?

Intent putExtra(String,String) inside of AsyncTask

I'm simply trying to carry a string onto the next activity without having to define an entire object for the task. I've seen similar solutions and gotten them to work BUT without using AsyncTask to create the intent.
protected void onPostExecute(Boolean result) {
if (loggedIn && hasPin) {
Intent intent = new Intent(UniteActivity.this,
WebViewActivity.class);
intent.putExtra(PASSED_USERNAME, passUser);
startActivity(intent);
}
if (loggedIn && !hasPin) {
Intent intent = new Intent(UniteActivity.this,
CreatePinActivity.class);
intent.putExtra(PASSED_USERNAME, passUser);
startActivity(intent);
PASSED_USERNAME is a public static constant to hold the package name, just as the putExtra() method requires. I then try to pull the value out in the next activity.
Intent extras = getIntent();
String username = extras.getStringExtra(UniteActivity.PASSED_USERNAME);
// carry username to next activity
Intent intent = new Intent(CreatePinActivity.this,WebViewActivity.class);
intent.putExtra(PASSED_USERNAME, username);
startActivity(intent);
There is never a String to pull out, the value of username is always null. I've gone through the debugger and found that the Eclipse IDE debugger shows different intent ID's between the activities, they are never consistant. Is it possible that AsyncTask is interfereing somehow because it splits into a seperate thread?
I don't know if this applies to your problem, because I can't see from your code snippet if the intermediary activity is freshly created or not.
BUT: the getIntent()-method always returns the first Intent that started the activity. If the activity remains in the background and receives a new Intent this value does not get updated automatically. You have to override onNewIntent(...) and manually call setIntent(...) for this to work (or do all your stuff directly there).
So just for the case that you do not run your posted code in the onCreate() method please check if you did not miss to fetch the real intent you are interested in.
Not sure of the exact answer for you solution.
You calling startActivity on the UI since it's in postExecute().
If all else fails you can just save that value to a sharedpreference.
The way you have handled the variable PASSED_USERNAME seems incorrect. You have used it in some palaces as simple PASSED_USERNAME whereas in some other places you have used it with the class named prefixed UniteActivity.PASSED_USERNAME. Since it is a Public Static Constant always use it prefixed with the class name.

Categories

Resources