Data Passing (Using Intent)

Before proceeding further first make sure that you should know a little about Intent. 

If you already know what is intent than you can skip this step. And If you want to know what is Intent and how we can use it to navigate the user to the next screen then you should check my previous blog about Navigate Activity (Using Intent)



So now you understand how to use intent. Now look forward to sending the data other activity. In the real-time application, sometimes we have to carry the required data to another screen to perform some task based on it. In android, we can pass those data using intent. 


The intent is not only used to navigate the user to the next screen but also help us to carry the essential data from one place to another. To pass the data from intent we are using the putExtra() method of intent. 


Let's check with an example :



          Button newActivity= (Button) findViewById(R.id.button
          newActivity.setOnClickListener(new View.OnClickListener() {  
                       @Override public void onClick(View v) {
               Intent newact = new Intent(MainActivity.this,SecondActivity.class);
               newAct.putExtra("Name","Mahavir"); 
               newact.putExtra("Number",1234567890);
               startActivity(newact);}

So as per the example shown, I have one button and on the click of that button, I have to pass some data to other activity. Using the above code you are able to share the data with other activity but how can you use that data?

To use the data in another activity we have to read the data first and to do that we have to add some code in the other activity. So add the below code in the activity to read the data.


public class SecondActivity extends AppCompatActivity{ 
   @Override 
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.second_activity_helper);
      Bundle d=getIntent().getExtras();
      String name=d.getString("Name");
      long number=d.getInt("Number");
      TextView textView= (TextView) findViewById(R.id.secodtextview);
      textView.setText("Name ==> " +  name  + " Number ==> " + number);}}
I have used textview to show the data.
                         



So that's all. It's so easy, Right?

I love to learn new things and I will keep posting the easy and simple way to use the android component. If you want to learn more please stay tuned!