Friday, June 8, 2012

Data sharing between two Android applications

In this tutorial I'm going to illustrate how we can share data between two Android applications using Shared Preference.
To implement this I used two Android applications. One is "Datawriter" and the other one is "Datareader".
"Datawriter" is to update shared data. Its' package name is com.writer.data class name is DataWriterActivity . Here is the code for DataWriterActivity class.

package com.writer.data;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

public class DataWriterActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        dataWriter();
    }
    
    public void dataWriter(){
        String strShareValue = "Hello! this is shared data";
        SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("demostring", strShareValue);
        editor.commit();
    }
}

dataWriter method will write the string Hello! this is shared data to a shared memory.

Next application is to read shared data. The application name is  Datareader and its' package name is com.datareader class name is DataReaderActivity. Here is the code for DataReaderActivity class.
package com.datareader;

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.widget.TextView;

public class DataReaderActivity extends Activity {
 String dataShared;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         dataRead();
         TextView tv = (TextView)findViewById(R.id.textView1);
         tv.setText(dataShared);
        
    }
    
    public void dataRead(){
      Context con;
         try {
             con = createPackageContext("com.writer.data", 0);
             SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
             dataShared = pref.getString("demostring", "No Value");
         }
         catch (NameNotFoundException e) {
             Log.e("Not data shared", e.toString());
         }
    }
}

"com.writer.data" in the highlighted line is the package name of the first application which we used to share data.
Following is the out put of second application :

27 comments:

  1. You actuаlly maκe it ѕeеm rеallу easy together with уouг presеntatіon hoωever
    I in fіnԁіng thiѕ mаtteг to be reallу something
    that I feel I'd never understand. It kind of feels too complex and very large for me. I'm havіng а loоk fοгwаrd fог youг nехt publіsh, I'll attempt to get the hold of it!
    Look into my homepage great advertising

    ReplyDelete
  2. Hаve уou eveг thought about incluԁing а little bit mοre thаn јuѕt your articlеs?
    I mean, whаt уou sаy is valuable аnd everything.
    Nevеrtheless think about іf you added some gгeat
    images oг videoѕ to give your posts morе, "pop"!
    Youг content іs eхcellent but wіth imageѕ and ѵideo сlips, thіs site could unԁeniably
    be one of the ѵегy beѕt in іtѕ niche.

    Vегy good blog!
    My blog post ... free registration

    ReplyDelete
  3. Hаve you ever thоught about incluԁing a little bit more
    thаn just уour articlеs? I mean, what you saу is valuable аnd everything.
    Nevertheless think about if you addeԁ some great
    images oг videоs to give your posts more, "pop"!
    Υour content іs eхcellent but
    with images and viԁeo clips, thіs site could unԁеniablу be one of thе very best in its niche.

    Vеrу goοd blog!
    My website > free registration

    ReplyDelete
  4. I have really learned newer and more effective things
    from the blog post. One more thing to I have discovered is that typically,
    FSBO sellers will probably reject an individual. Remember, they would prefer to never use your products and services.

    But if anyone maintain a gradual, professional partnership, offering aid and
    being in contact for about four to five weeks, you will usually be capable of
    win a conversation. From there, a house listing follows. Thanks
    Also see my site: Edmonton podiatrist

    ReplyDelete
  5. Link exchange is nothing else except it is simply placing the other person’s webpage link on your page at proper place and other person will
    also do same in support of you.
    Also visit my web-site Small business software

    ReplyDelete
  6. You are a very bright person!
    My web page > pink digital camera

    ReplyDelete
  7. An intrіguing ԁiѕcuѕsion is defіnitely
    wоrth comment. I do thinκ that you ought to publіsh more
    abοut this topіc, it mіght not be a taboo subject
    but usually peοple ԁo not diѕcuѕs these
    subjеcts. To the next! Chеers!!
    my site > Dubai based premier web Designing company

    ReplyDelete
  8. Thank you so many!
    Oh why, oh why can't everybody write a piece of self explanatory code, instead of explaining simple things with thousands of words.

    -tk

    ReplyDelete
  9. Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didn't appear. Grrrr... well I'm not writing
    all that over again. Anyways, just wanted to say superb blog!
    Here is my web page ... black friday ads

    ReplyDelete
  10. Wonderful site. А lot of useful information heге.

    I am sending іt tο somе pals anѕ also sharing in dеlіciоus.
    And obѵiously, thank уοu оn youг sweat!
    My weblog - lowest home equity loan rates

    ReplyDelete
  11. What's Going down i'm neω to this, Ӏ stumbled
    upon this I have fоund It positively uѕeful and it has helped me οut
    loadѕ. I'm hoping to contribute & assist different customers like its helped me. Good job.
    Also visit my blog ... http://www.drirfanrana.com/

    ReplyDelete
  12. WOW just what I was searching for. Came here by searching for poor
    credit home equity loans
    Also visit my blog post :: private loans

    ReplyDelete
  13. My programmer is trying to persuade me to move to .

    net from PHP. I have always disliked the idea because
    of the costs. But he's tryiong none the less. I've been using WordPress on various websites for about a
    year and am anxious about switching to another platform.
    I have heard great things about blogengine.
    net. Is there a way I can transfer all my wordpress posts into
    it? Any help would be greatly appreciated!
    Here is my weblog ... kredit ohne schufa sofort

    ReplyDelete
  14. Good day! Do you use Twitter? I'd like to follow you if that would be okay. I'm undoubtedly
    enjoying your blog and look forward to new posts.
    My website ; wechsel von privater in gesetzliche krankenkasse

    ReplyDelete
  15. Have you ever considered about including a little bit more
    than just your articles? I mean, what you say is important and everything.
    But just imagine if you added some great photos or video clips to give your posts more, "pop"!
    Your content is excellent but with images and videos, this site could certainly be one of the very best in its niche.
    Awesome blog!
    My webpage ; private krankenversicherungen vergleich

    ReplyDelete
  16. I do not comment, however after browsing a great deal of remarks
    on "Data sharing between two Android applications".
    I do have a couple of questions for you if you tend
    not to mind. Is it just me or does it look as if like a
    few of the remarks look as if they are written by brain
    dead individuals? :-P And, if you are writing at other online social sites, I would
    like to follow you. Would you post a list of the complete urls of your public pages like your twitter feed, Facebook page or linkedin profile?
    My website :: replay online outlet

    ReplyDelete
  17. Hi there, after reading this amazing post i am also happy to
    share my know-how here with friends.
    My web page :: promote products

    ReplyDelete
  18. I was wondering if you ever thought of changing the structure
    of your website? Its very well written; I love what youve got
    to say. But maybe you could a little more in the
    way of content so people could connect with it better.

    Youve got an awful lot of text for only having one or
    2 images. Maybe you could space it out better?
    Here is my webpage - free vacations

    ReplyDelete
  19. I'm really enjoying the design and layout of your blog. It's a very easy on the eyes which
    makes it much more enjoyable for me to come here and visit more often.

    Did you hire out a designer to create your theme? Outstanding work!
    Also visit my weblog :: home loan for bad credit

    ReplyDelete
  20. Way cool! Some very valid points! I appreciate you penning this post and the rest of the website is very
    good.
    Also visit my website - kredite mit negativer schufa

    ReplyDelete
  21. You really make it seem really easy along with your presentation however I
    find this matter to be really one thing which I feel I would never understand.

    It kind of feels too complicated and very large for
    me. I am having a look ahead for your subsequent post, I'll attempt to get the cling of it!
    Here is my blog post - best search engine optimization

    ReplyDelete
  22. These are truly wonderful ideas in concerning blogging.
    You have touched some pleasant points here. Any way
    keep up wrinting.
    Feel free to surf my web blog - the best all inclusive vacations

    ReplyDelete
  23. I am really loving the theme/design of your website.

    Do you ever run into any browser compatibility problems?
    A handful of my blog readers have complained about
    my site not working correctly in Explorer but looks great in Safari.
    Do you have any solutions to help fix this problem?
    My website :: reseller hosting cheapest

    ReplyDelete
  24. Thank you for sharing this wonderful information. i really impressed by it.keep on posting..
    Mobile Application Development

    ReplyDelete
  25. hii.. Thanks to share it useful information.very informative. Mobile Application development

    ReplyDelete