Showing posts with label app. Show all posts
Showing posts with label app. Show all posts

Tuesday 23 December 2014

Pass Data between Activity in Android


Hello Friends ,

Today I got one message from a person to tell him how to pass data between android activities So, I am going to give a simple way for how we can transfer data or how we can pass data across activities in android . In android we use activity for  each layout code .

I am using Mono Android for this article but that will similar functions in Dalvik android that is used with java based android applications .

Here are simple Steps How to Pass data between Activities in Android Using Csharp -

  1. Open Visual Studio . Click on File --> New Project -->
  2. Now choose Mono For Android and click on Android Application . Now Simple Android application will be created
  3. This project will create a single activity named MainActivity (MainActivity.cs), which contains a button.
  4. Add a second New activity class named Activity2 to the project. by right click on Solution Name and click on New then click on Android Activity leave the name as default and click on Ok  This class must inherit from Android.App.Activity .
  5. right click on layout folder inside Resource folder then click new and choose Android Layout give it a name and leave as default and click ok .
  6. In the button.Click handler in MainActivity.cs , create an intent for Activity2 , and add data to the intent by calling PutExtra and this data given in Put Extra will be transfered to Activity2 . Add the Code Below for that :-
 button.Click += delegate {
               // button.Text = string.Format("{0} clicks!", count++);
                var activity2 = new Intent(this, typeof(Activity2));
                activity2.PutExtra("MyData", "Data from Activity1");
                StartActivity(activity2);
            };
      
      7. Now Open you layout.xm file in Resource --> layout folder ( layout folder under resource folder ) . Add code below to it for Adding button under <linearlayout> tag :-

        <Button
        android:id="@+id/MyButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/Hello" />    string text = Intent.GetStringExtra

    8. Now add code below to Newly added Activity - activity2.cs under Activiy.Oncreate Method :-
            ("MyData") ?? "Data not available";
            string text1 = Intent.GetStringExtra("MyData");
            Button button = FindViewById<Button>(Resource.Id.MyButton);
            button.Text = text;

       9. Now Run the app by pressing F5 and see the output in emulator as below -
Pass Data between Activity in android 
10. Now click on button saying "Hello World,Click Me!" Now you will see New Avtivity Activity2 as below that contain the text that we have passed from activity Activity1

Pass Data between Activity in android