Discussing the nuts and bolts of software development

Tuesday, February 01, 2011

 

Pass Me the Data, by Rob Woods

You've written the Hello Android app, then created your own simple app. Now you've created a much more complicated app with several activities. You may need to be able to pass data between your activities. In this post, I will take you from the basics of passing simple data types between activities, right up to making your own custom objects parcelable so they can also be passed along with the same ease as a simple data type.
If you feel that you need a bit more background on this subject matter before reading further, here is a helpful article on Android application development.

Before we start passing data around, first you will need to understand how an activity is launched. To launch a new activity, you would create an Intent and pass it to the Activity method startActivity().

Illustration:
"Intent newIntent = new Intent(Context, Class);
startActivity(newIntent);"

Now lets say you have a listactivity, and whenever a user taps on an entry in the list, you want to launch a new activity that does something with the data from that list entry. The most basic scenario for passing data is to attach an extra to the intent in the form of

"newIntent.putExtra(name,value);"

Where name is a String that is used to "tag" your data and value is the actual data object you are passing to the intended activity. Value can be many different types, including String, int, Boolean, etc. You can see the complete list of putextra methods here.

Here's an example from the callingaActivity.
"Intent newIntent = new Intent(this, SomeActivity.class);
newIntent.putExtra("MAGIC_NUMBER", 42);
startActivity(newIntent);"

Now on the called activity side (receiving the Intent), in your activities onCreate() method, you will need to retrieve the extra data from the intent. You can do this by calling getIntent() to get the intent that started the activity, then getIntExtra(name, default). This is if you passed an int value, if you passed a different type, you would use the corresponding method for that type.

For example:
"int magic_number = getIntent().getIntExtra("MAGIC_NUMBER", 420);"

Note that the default value is used if the tag "MAGIC_NUMBER" had no value assigned to it. This is great if you are just passing one piece of data using a basic data type, but if you are passing more data than just a single type, you might want to consider using Bundle.

Basically, a Bundle is just a mapping of tag-data pairs grouped together into one passable object. Let's say that you had a contact list and when the user taps a contact, you want to pass the name, id and phone number to the called Activity. You could do so like this:

"Intent newIntent = Intent(this, ContactDetails.class);
Bundle extras = new Bundle();
extras.putString("CONTACT_NAME", name);
extras.putInt("CONTACT_ID", id);
extras.putString("CONTACT_NUMBER", number);
newIntent.putExtras(extras);
startActivity(newIntent);:

And on the receiving Activity:

"Bundle extras = getIntent().getExtras();
String name = extras.getString("CONTACT_NAME");
int id = extras.getInt("CONTACT_ID");
String number = extras.getString("CONTACT_NUMBER");"

Now lets say you've created your own data class with several different types of data representing the class:

"public class Dog extends Object {
private String mType;
private String mName;
private int mId;

public Dog(String type, String name, int id) {
mType = type;
mName = name;
mId = id;
} "

You could pass each piece of data separately by adding 4 tag-data pairs to a Bundle and passing the Bundle. However, a smarter way of doing this is to implement the parcelable interface in your Dog class. The parcelable interface has 2 methods which are needed to implement, describeContents() and writeToParcel(Parcel, int).

"@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mType);
dest.writeString(mName);
dest.writeInt(id);
}"

Using this method, you must add each of your data types to the Parcel with the correct write method for its data type.

If your class has child classes, you can use the describeContents() method to differentiate between child classes so that when you unparcel your parceled object, you can create the correct child object.

This is only half of the solution. Now that you have the facilities to write your object to a parcel, you also need to be able to rebuild your object in the called activity. First you will need a new constructor for your class. One that takes a parcel object and can populate it's data members from it;

'public Dog(Parcel dest) {
mType = dest.readString();
mName = dest.readString();
mId = dest.readInt();
}'

Note the order.
You must read your data types from your parcel in the same order you wrote them. Essentially you're flattening your data into one data stream, then reading it back on the other side.

Finally, you will need to create a parcelable creator in your class that will trigger your new parcelable constructor when needed:

"public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
@Override
public LocalContact createFromParcel(Parcel source) {
return new LocalContact(source);
}

@Override
public LocalContact[] newArray(int size) {
return new LocalContact[size];
}
};"

One last thing I'll leave you with is the concept of chaining your parcelable objects. Lets say your Dog class has a custom object as one of its data members. You need to make sure that class also implements the parcelable interface. In order to support parcelizing your custom object inside your Dog class, you will need to change 2 methods.
First, Dog's writeToParcel(Parcel, int) method needs to tell your custom object to write itself to the parcel.
To do this, we can call writeParcelable(Object, int). This method will invoke your custom classes writeToParcel method:

"@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mType);
dest.writeString(mName);
dest.writeInt(id);
dest.writeParcelable(dogTag, flags);
}"

Here dogTag would be your custom class that could implement say, a phone number and address for where the dog lives. Second Dog's parcel constructor. Here we will call readParcelable(Classloader) to get the custom objects parceled data:

"public Dog(Parcel dest) {
mType = dest.readString();
mName = dest.readString();
mId = dest.readInt();
dogTag = dest.readParcelable(DogTag.class.getClassLoader());
}"

This should get you passing your data around to your activities!

Labels: , , , , , , , , , , , , ,


Comments:
I am for the first time here. I came across this blog and I find It really useful & it helped me out much. I hope to give something back and aid others like you helped me. I think this is engaging and eye-opening material. thesis writing service Thank you so much for caring about your content and your readers.
 
I am sure that this information will be useful for teachers. Here you can read more about Montessori education
 
I will gladly pas you the data as soon as I finish with my excel exercises. You are even allowed to do any corrections or editing if needed. I'll be happy to help.
 
We are a reputable writing company mental health argumentative essay of international experience with creation of different types of essays for students of all levels of education and self introduction essay
 
We will also help you with cheap online assistance at affordable prices by professional experts. We provide 24 * 7 service and support for all our users. I Need Help With Homework
 
You are doing a tremendous job. It is very enlightening and achieves what it desires. I will make sure that I read all of your blogs in future. It will definitively enhance my knowledge.
how to write a research paper
how to cite a research paper
 
In an era where Best Essay Writing Service in USA are thriving, it has become increasingly difficult for students to identify with a reliable company that offers Top Essay Writing Services and Legit Top Essay Writing.

 
Ducat provides digital marketing training in noida as per the current industry standards. Our training programs will enable professionals to secure placements in MNCs. We are providing our world-class training facilities for all the students who want to become professional java developer.
 
HP Deskjet 3700 Offline Mac with the directions given here. The normal issues and their answer are given in detail for HP DeskJet 3700 printer disconnected blunder.
 
I feel a lot more people need to read this, very good info!.Learn best Data Science Course in Hyderabad
 
I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read!! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site.Learn Best Data Science Training in Hyderabad
 
Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.Learn best Business Analytics Course in Hyderabad
 
I and my friends often read your posts and discuss on them. We get valuable information through your posts. Thanks a lot.
java training institute in noida
 
Your post is very great.i read this post this is a very helpful. i will definitely go ahead and take advantage of this. You absolutely have wonderful stories.Cheers for sharing with us your blog. python training in noida
 
Hi! This website would be interesting for students who are overloaded with different writing tasks. Don't waste your time and write us!
 
Appreciating the persistence you put into your blog and detailed information you provided.
Thanks for sharing! Glad to read your posts. Thumbs up👍!!

online internship
online internships
watch internship online
online internship for students
the internship online
online internship with certificate
online internship certificate
python online internship
data science online internship

 
Want to watch the best movies before anyone else .
Then you should visit 123freemovies
 
Hello! If you see that you have no time for writing papers then it's better t apply to the professionals. For example, you can apply to the writing service where you can find https://elitewritings.com/buy-response-essay-online.html
 
nice information thank you
Data Science Course in Hyderabad
 
Seeking psychology research writing services are very common nowadays since there are very many students in need of Psychology Coursework Writing Services and psychology assignment writing services.

 
Fantastic blog with top quality information, enjoyed reading it and found very valuable thanks for sharing.
Data Analytics Course Online
 
I have voiced some of the posts on your website now, and I really like your blogging style. I added it to my list of favorite blogging sites and will be back soon ... PMP Certification in Hyderabad
 
Great article with valuable information found very resourceful and enjoyed reading it waiting for next blog update thanks for sharing.
Ethical Hacking Course in Bangalore
 
Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
Cyber Security Course in Bangalore
 
Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
Cyber Security Training in Bangalore
 
Great article with valuable information found very resourceful and enjoyed reading it waiting for next blog updated thanks for sharing.
typeerror nonetype object is not subscriptable
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?