Learning about Intents, passing Data - android

Does anyone know any good resources where a beginner and understand Intents and Contexts. I understand the basics of activities, but i don't really understand how Intents go along with this.
Also, anyone know any good resources to learn about passing information between activities? For example, I have a splash screen, and I have multiple levels for an addition activity. I created an addition activity, but i want to be able to press different buttons to determine different difficulties. So obviously I dont want to create like 5 different layouts with the same activity with just the difficulty changed. So since I already have the code for the addition activity, how can I pass data from the splash activity to the addition activity? The data might be an int that designates a difficulty level. I would then be able to access the int from the addition activity and base it off of that.
Thanks

You can easily pass Int between activities using Intents.
Activity1
Intent intent = new Intent(Activity1.this,Activity2.class);
intent.putExtra("param", 1);
startActivity(intent);
Activity2
onCreate(Bundle b) {
int param = getIntent().getIntExtra("param");
}
All primary datatypes Integer,Long,String,etc can be passed as an extra. Technically, anything that is Serializable can be an extra.
Eg.
class Student implements Serializable
{
//...
}
Intent intent = //...
intent.putSerializable("key", new Student());
To retrieve it,
Student s = (Student)getIntent().getSerializableExtra();

http://developer.android.com/guide/topics/intents/intents-filters.html
http://www.vogella.de/articles/AndroidServices/article.html
I really recommend a lot of Vogella's tutorials. They've really helped me out a lot.

Related

How to send data from activity to another activity without Intent in android

In my application I want send data from activity to another activity and for this I don't want use Intent.
I know I can use this code :
Intent intent = new Intent(context, Activity.class);
intent.putExtra("name", value);
startActivity(intent);
and for this I don't want use SharedPreferences again!
Do you know other way for send data from activity to another activity without 2 above ways?
If I understand correctly, you are looking for a way to pass data from one Activity to another Activity without using either SharedPreferences or the SQLite database. Using an Intent is OK but not with startActivity(). I assume that this also goes for startActivityForResult().
Two Activitys of the same application will as a rule not be in the foreground at the same time, so LocalBroadcastManager won't be very helpful in this case. Simply "sending" won't be possible, one needs some kind of middle man.
You could look into EventBus libraries, e.g. Otto EventBus
But maybe you'd prefer to work with some type of POJO to hold the data, and perhaps some Observer which the Activitys could query. Such a class could be implemented as a field in a custom class extending Application.

Any benefit to starting an Activity via an intent one way versus another?

I know of two ways to start an Activity with an intent. Let's say I'm in Activity A and I want to start Activity B. I could do the following.
1)
In Activity B I have some static method:
public static Intent newIntent(Context packageContext){
Intent intent = new Intent(packageContext, ActivityB.class);
return intent;
}
And from Activity A I can call:
startActivity(ActivityB.newIntent(this));
2) The other method is the one I see more often:
From Activity A I do the following
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
Are there any benefits or drawbacks to using one versus the other? I think method 1 is a bit cleaner because it keeps the intent information in the class that will actually be started with the intent.
case first
Pros :
This follows the DRY principle mean don't repeat your self
Cons :
It is only limited to one class i.e ActivityB.class
Unclear naming convention for a Utility class
Note flexible to add extra properties unless method definition is modified to accept some map or something
Second case
Pros:
More flexible as any activity can be started
Any attribute can be added to intent object i.g putExtra and so many other
Cons :
Does not follow the DRY principle
Inefficient when duplicated many times
Improvements
Give your method proper naming
Can be overloaded to accept a map for key-value
Apply Class<?> to accept any class as parameter
The two approaches do exactly the same thing.
I think the first approach is indeed easier to understand and it's less code. But I think most people got used to the second approach and might be a little confused when they see it like that. This drawback isn't that significant though I don't think.
The thing is, if you use the first approach, you still need to use the second approach if you want to start an activity that you didn't create because you can't just add a static method to an already compiled .class file. This might make your code a little inconsistent.
Also, the name newIntent is kind of confusing. I don't know if it's just me, but doesn't it sound a bit like that you are going from Activity B to A? Maybe just intent?

Pass data between activities Android [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 5 years ago.
I want to know if there is a way to pass a class object, which can't implement serializable interface between 2 android activities.
I know that to pass data using intent you have to implement serializable interface, but unfortunately I can't do this, any idea?
public class ContactMongo implements Serializable{
private DB collection;
public ContactMongo()
{ }
}
DB doesn't implement serializable, so I can't perform intent.putExtra();
You probably want to use a service, but you haven't told us anything about what you're trying to pass, so I guess you want to use ugly hacks.
There is such an ugly hack available, but it'll quickly get out of control (especially if you cannot even search on this topic by yourself) - you can extend your Application class and use its methods to pass data between activities. Generally, it should be avoided and other ways to pass data and let activities communicate should be used (like extracting the data from the object you want to pass).
Hope this helps you, comment if you have any questions (I'll update my answer with better solution if you give more information on what you're trying to do)
You need to send an intent with whatever you want to pass.
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
Object object;
intent.putExtra("nameforyourobject", object);
startActivity(intent);
https://developer.android.com/training/basics/firstapp/starting-activity.html

Android intent extra message versus static variable

What is the purpose of using an intent with a message instead of just declaring a static variable in java and calling it from the new activity? It seems easier to me this way because you can have the static variable be anything you want (i.e. ArrayList, Object, etc.).
public class FirstActivity extends Activity {
public static String name;
...
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
name = "Robert";
startActivity(intent);
}
public class SecondActivity extends Activity {
...
textView.setText(FirstActivity.name);
}
By using extras to start SecondActivity, you make it more reusable. Many of the stock activities work this way, that's why you can reuse for example the camera activity to take and save photos, because it does not make assumptions about who is calling it.
In your case SecondActivity depends on FirstActivity having been loaded in the JVM. I would not count on that, and it's certainly not a recommended practice to have such dependency between activities. Don't do this. Use extras to pass values between activities, as recommended by the SDK.
To clarify, the OP's strategy won't work if another app outside of his/hers wants to handle the Intent. Because of this, it's not a "best practice".
There are roughly 30 different putExtra variations for an Intent, each representing a different data type you can add. They include general purpose data types such as Bundle, Parcelable, Serializable, and so forth. I can't think offhand of anything that these don't cover.
I don't use statics or variables defined by overriding Application or other similar ways of assuming that some data is floating about in storage. It's much more robust to assume that my Activity or Fragment is totally independent.
Using Intent make you slower than static
For example if you use mvp or mvvm
At least you have to pass like id through layer by later

How to pass information between Activities

I have asked this question a few times on here already, but still am not confident enough to start throwing things into my code because I'm afraid I'll ruin the functionality it already has.
What I want to do is have a Bluetooth connection with a device that I can send/receive data to/from, and be able to access it from several different Activities. I know Intents can be used, but can anyone try to explain how intents work?
I don't understand how if I start with an Activity, how I can build an object within that Activity, then end it, and still have the object. When I call the intent in the following Activity, how do I access it?
I can not find example code of an Activity with a custom object that is passed through an intent, opened in another Activity, then passed again through another Activity, and so on. All I can find is things for string's, int's and it seems that those methods are hardcoded for the specific objects.
Any help would be greatly appreciated, thanks.
If you want to pass a custom object from an Activity to another one, your object have to implement Parcelable interface.
Here you can find an example of an object which implements Parcelable.
Once you have an instance of this object you can add it to an intent and pass it to other activity.
Let's say you have 2 activities: A and B.
If you want to send a custom object from A to B try put your parceable object in an intent and get it back in Activity B.
// Activity A
Notebook myNotebook = new Notebook(); // the "Parcelable" object
Intent intent = new Intent(A.this, B.class);
intent.putExtra("object", myNotebook);
startActivityForResult(intent);
// Activity B
// in onCreate method
Notebook notebook = intent.getParcelableExtra("object");
there is a good reason you don't find a good example of transfering complicate objects: you don't suppose to that a lot. it's possible to transfer with intent extra any object, with declare the class you want to transfer as implements Serializable, or Parcalable.
but - this is not recomended doing so, unless you have good reason.
there are unlimited ways to create "cross activities" objects (databases, singeltones, services..), and passing complicated objects in intent is heavy operation. also it makes terrible performances doing so.
anyway - if you want anyway doing so, that's the way:
this is how to pass serlizable object:
Intent intent = new Intent();
intent.putExtra(name, someInstanceOfClassWhichImplementsSerializableInterface);
this is how to acheive it on the other activity:
getIntent().getSerializableExtra(name);
about the question that you don't understand how the object still lives after you finish the activity - finish() activity is not triggering distractor!!!, but do triggers to onDestoy() callback. the system decides when it's the right time call the activities distracor , and even if it was distractor - it's not preventing from the Intent object to stay alive - because nobody said your activity is the only one holding reference to it. the intent reference held by the system for the perpose of passing it to the new activity which opened with it.
Using intent you can send serialized object which is like converting you object into byte stream. If you want to send your object as it is you can use handlers.
e.g.
create Bluetooth connection using service(android service)
define handler in you activity which will be static object
from service to send the object add to msg.obj send that msg to handler

Categories

Resources