Sending data from one Activity to another Activity
Today i am using explicit intents to send data from one activity to another . For this i create a new project called Explicit. Then i create new XML file in layout called Second.xml.
As i am sending data from one to another activity . I need to create a new activity for this i go to src and right click it and create new java file(activity)
Creating new java class for new activity |
After creating, open second.java and a blank class appears . I need to extend that class by Activity.After extending, i need to right click in between two curly braces then go to Source and then click Override/Implement Methods.
Then a new windows appear. Inside Activity there all a lots of options to be choose but i choose only onCreate(Bundle).
Choosing OnCreate(Bundle) |
Now i goto main.xml and drag a button and Edittext in layout.
Dragging Edittext and Button in layout |
Now i need to go to main java file and write following code:
final EditText et = (EditText) findViewById(R.id.editText1); //getting id of edittext
Button b1 = (Button) findViewById(R.id.button1); // getting id of button
//when button is clicked this function is called
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this , Second.class);
intent.putExtra("thetext", et.getText().toString());
startActivity(intent);
}
});
Sending data from first activity using intent |
Go to second.xml and i drag a Textview in it where the word send from first activity will be shown.
Now go to Second.java and write this codes:
setContentView(R.layout.second);
TextView tv = (TextView) findViewById(R.id.textView1); //getting id of textview
tv.setText(getIntent().getExtras().getString("thetext")); //setting the string in textview
And i also need to add the second activity in my manifest and shown in figure.
Adding activity in manifest file |
No comments:
Post a Comment
Did this post help you? Do you have any questions? Drop your thoughts here...