Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMiguel Gonzalez Rocha
2,849 PointsCan someone explain his last line of code?
public class MainActivity extends Activity {
private EditText mNameField;
private Button mStartButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNameField = (EditText) findViewById(R.id.nameEditText);
mStartButton = (Button) findViewById(R.id.startButton);
mStartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = mNameField.getText().toString();
Toast.makeText(MainActivity.this,"Welcome " + name ,Toast.LENGTH_LONG).show();
startStory(name);
}
});
}
private void startStory(String name){
Intent intent = new Intent(this, StoryActivity.class);
intent.putExtra("name",name);
startActivity(intent);
}
}
In the startStory method what is exactly the difference between "name" and name?
1 Answer
James Simshaw
28,738 PointsHello,
In the line intent.putExtra("name", name), the difference is that "name" is the key that the value is being stored under and the variable name is the value that is getting put in. This way, when we want to retrieve the variable, we can look it up via the "name" key.
In other words, the basic form is putExtra(key, value);
Miguel Gonzalez Rocha
2,849 PointsMiguel Gonzalez Rocha
2,849 PointsHello, thanks for the answer, now the other question is, what is key? i was reading the documentation and i found that the key as you said is "the name of the extra data, with package prefix" this is what is messing me up :s
James Simshaw
28,738 PointsJames Simshaw
28,738 PointsThe class on Java Data Structures on the Java track available here will likely give better explaination than this. However, the key is the name that you're storing the value under. Consider it a similar to a Map in Java or a dictionary in Python.
As far as I know, the part "with package prefix" will only really come into play if you're working with intents from another package/program.
Miguel Gonzalez Rocha
2,849 PointsMiguel Gonzalez Rocha
2,849 Pointsi found what you meant im actually halfway on the java structures maybe i should finish it if i see this kind of info is necessary to fully understand the android course, thankyou James
James Simshaw
28,738 PointsJames Simshaw
28,738 PointsYou're welcome. Good luck with both Java and Android programming.