Friday, 9 March 2012

Share Data Across Application in Android

                      Share Data Across Application in android using Shared Preference


* Android allow us to share data across applications.
* Context.MODE_WORLD_READABLE is important thing in shared preference for global data access.

* Run both project in the same emulator, Follow the below steps,


Step 1:

Create the android application name as "SharedPref1"

Package name as "com.sharepref1"

Copy the below code and paste it in main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/edit_share_value"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_share_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share Data" />

</LinearLayout>


Copy the below code and paste it in your java class(SharedPref1Activity).

package com.sharedpref1;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SharedPref1Activity extends Activity {
    EditText editShareValue;
    Button btnShareValue;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnShareValue = (Button) this.findViewById(R.id.btn_share_value);
        editShareValue = (EditText) this.findViewById(R.id.edit_share_value);

        btnShareValue.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String strShareValue = editShareValue.getText().toString()
                        .trim();
                SharedPreferences prefs = getSharedPreferences("demopref",
                        Context.MODE_WORLD_READABLE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("demostring", strShareValue);
                editor.commit();

            }
        });
    }
}







save and run the program ,enter any data and click Share Data button.



Step 2:
Create the android application name as "SharedPref2"

Package name as "com.sharepref2"

Copy the below code and paste it in main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text_display_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/btn_display_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Value" />

</LinearLayout>


Copy the below code and paste it in your java class(SharedPref2Activity).


package com.sharedpref2;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SharedPref2Activity extends Activity {
    TextView displaySharedValue;
    Button displayValue;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        displaySharedValue = (TextView) this
                .findViewById(R.id.text_display_value);
        displayValue = (Button) this.findViewById(R.id.btn_display_value);
        displayValue.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Context con;
                try {

                    con = createPackageContext("com.sharedpref1", 0);
                    SharedPreferences pref = con.getSharedPreferences(
                            "demopref", Context.MODE_PRIVATE);
                    String data = pref.getString("demostring", "No Value");
                    displaySharedValue.setText(data);
                } catch (NameNotFoundException e) {
                    Log.e("Not data shared", e.toString());
                }
            }
        });

    }
}

save and run the program in the same emulator which you run the first one.


Now click DisplayValue button.Now you get the data which you entered in sharedpref1.

Full source code SharedPref

22 comments:

  1. thank you very much. This tutorial is very helpful

    ReplyDelete
    Replies
    1. thank you for commenting.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Thank you anees, Here I need to remember one thing the MODE_WORLD_READABLE is deprecated in API level 17. Avoid using this.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. sir can you kindly help me out to share data to share database between same app working on different physical devices in android
      i'll be highly grateful. waiting for a reply!

      Delete
  3. While reading Word readable data shared by first app, we should create shared pref object like-

    Replacing

    getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);

    with

    getSharedPreferences("PREF_NAME", Context.MODE_MULTI_PROCESS);

    in second app to get updated value in second app.

    ReplyDelete
    Replies
    1. thank you :)

      Delete
    2. Thanks man... this annoying me a whole day...

      Delete
  4. is it possibe to access the sharedpreference in one app which is created by some other app by only knowing the name of the sharedpreference ( not knowing the package of the app who created the shared preference)...

    ReplyDelete
  5. can anyone tell me how to open a file (like doc , excel, pdf )if that are in the internal storage (/data/data/{app package name}/ATT.pdf ) of android ( phonegap ) application ?
    i am trying to develop application in android phonegap. in taht application from a url i am downloading a file and storing into the internal storage (/data/data/{app package name}/) of application. iam able to store that file to internal storage, but not know how to open that file.. plz help :(

    ReplyDelete
  6. how to share sqlite data between two different applications in android..plz tell me..

    ReplyDelete
    Replies
    1. Using content Provider.

      Delete
  7. This was helpful for me... Thank you...

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. please post tutorials "Share Data Across two android phones". long distance communication should be..

    ReplyDelete
  10. and please tell me can we share data between two android phones using GSM??? if yes than please post tutorial.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Hello, i used your code (exactly the same code) with API Level 14 (minium and target Level) and got some problems:
    At first I start App1 (SharedPref1Activity) and type in "hi how are you". Now I start App2 and click on Button "Display Value" and I get the text "hi how are you".
    When I switch now back to App1 and use the text "im fine" and click on button "Share Data".
    I switch to App2 and click on Button "Display Value" and again a get the text "hi how are you" and not the text "im fine". I tested it on a HTC One (M7) smartphone and on a Samsung Galaxy Tab and i got the same result. What can i do that the sharedPreference will be reloaded or refreshed with the new text?
    Thank you in advance for help.

    ReplyDelete