Langsung ke konten utama

Data sharing using Bundle

Data sharing between Activities using Bundle, When we create object for intent only we need to add data to bundle and add bundle object to intent object and we need to read the data from targeted Activity, Following Example Explains How data sharing Takes place between Activities using Bundle.





Step 1: Create New Application
Step 2: Write the following code in strings.xml

Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Intent Sharing</string>
    <string name="main_button_cancel">Cancel</string>
    <string name="title_activity_second">Second Activity</string>
    <string name="main_button_submit">Submit</string>
    <string name="main_button_submit_hint">Please Enter User Name</string>
    <string name="main_button_cancel_hint">Please Enter Password</string>

</resources>

Step 3: Write the following code in activity_main.xml

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/main_editText_usename"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:hint="@string/main_button_submit_hint" />
       

    <EditText
        android:id="@+id/main_editText_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/main_editText_usename"
        android:layout_below="@+id/main_editText_usename"
        android:layout_marginTop="20dp"
        android:hint="@string/main_button_cancel_hint"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/main_button_submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/main_editText_password"
        android:layout_below="@+id/main_editText_password"
        android:layout_marginTop="23dp"
        android:text="@string/main_button_submit" />

    <Button
        android:id="@+id/main_button_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/main_button_submit"
        android:layout_alignBottom="@+id/main_button_submit"
        android:layout_centerHorizontal="true"
        android:text="@string/main_button_cancel" />


</RelativeLayout>

Step 4: Write the following code in MainActivity.java

MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

       EditText edit_username, edit_password;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              Button button_submit = (Button) findViewById(R.id.main_button_submit);
              Button button_cancel = (Button) findViewById(R.id.main_button_cancel);
              edit_username = (EditText) findViewById(R.id.main_editText_usename);
              edit_password = (EditText) findViewById(R.id.main_editText_password);

              button_submit.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           String username = edit_username.getText().toString();
                           String password = edit_password.getText().toString();

                           Intent intent = newIntent(getApplicationContext(),
                                         SecondActivity.class);

                           Bundle bundle = new Bundle();
                           bundle.putString("username", username);
                           bundle.putString("password", password);

                           intent.putExtras(bundle);
                           startActivity(intent);
                           finish(); // finish() is to finish the activity
                                                // it will not add activity to back stack
                     }
              });

              button_cancel.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           edit_username.setText("");
                           edit_password.setText("");
                     }
              });
       }

}

Step 4: Create new Activity (SecondActivity)

Step 5: Register SecondActivity in manifest file, add the following code in manifest.xml

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.swamy.intentsharing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.swamy.intentsharing.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.swamy.intentsharing.SecondActivity"
            android:label="@string/title_activity_second" >
        </activity>
    </application>


</manifest>

Step 6: Write the following code in activity_second.xml

activity_second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity" >

    <TextView
        android:id="@+id/second_textView_disp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />


</RelativeLayout>

Step 7: Write the following code in SecondActivity.java

SecondActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_second);

              TextView editText_disp = (TextView)                                                          findViewById(R.id.second_textView_disp);

              Intent intent = getIntent();
              Bundle bundle = intent.getExtras();
             
              String username = bundle.getString("username");
              String password = bundle.getString("password");

              editText_disp.append("Username : " + username + "\n");
              editText_disp.append("Password : " + password);
       }
 }

Komentar

Postingan populer dari blog ini

How Create a Accessibility Service in Android

Hello friends, In this Tutorial. In this post, I will show you how to use Accessibility Service for Android. Before that, we need to know What is Accessibility Service . Accessibility Service Here, I am taking an example for creating Virtual Service Button instead of Default Back Button. Project Structure: Create a new Project in Android Studio with the required Specifications. Codes: AndroidManifest.xml Don't forget to add the following permission in your manifest file. <uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> Don't forget to add the following Lines in your manifest file to create service for your application. <service android:name=".MyService" android:label="@string/app_name" android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"> <intent-filter> <...

How to Perform Rest API using Retrofit in Android (Part-1)

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSONParsing and Volley. This post is Split into Two Parts. First Part Contains Architecture of Retrofit and How to create MySQL DB and PHP Scripts for Basic Operations. Second Part Contains how to perform Retrofit Operations in Android. Architecture of Retrofit Web Service We need 3 Things for Complete Retrofit Architecture. RestAdapter An Interface with all networking methods and parameters. Getter Setter Class to save data coming from server. Project Structure: Create MySQL DataBase and PHP Scripts. Following image shows my database structure. PHP Scripts: I created db_config.php which contains the script to connect DB. <?php /** * Database config variables */ define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "retrofit_exampl...

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail...