Android intent extra message versus static variable - android

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

Related

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?

Can we usually skip using intents by using public variables in Android?

Many times we use intents to send data to a Fragment or get data back from a child. Can't we just put data in a public variable?
For example imagine if we want to get data from user from a dialog box.
I'm just talking about the "possibility". Undoubtedly, It is superior to use intents for code cleanness or safety...
you don't send intent's to fragments, if you want to use objects you need to have your object implement Parcelable then you can just send the object in the intent bundle
public class MyActivity extends Activity {
public int someValue = 1;
}
And in any fragment which has MyActivity as a host you can access ((MyActivity) getActivity()).someValue.
I think what he means is sending (local)broadcast... which is by the way the proper way of doing it according to my understanding.
Of course it is possible to have public (or even protected) fields and access them from a child-fragment with something like this:
assuming your parent activity is named "MainActivity"
((MainActivity) getActivity()).mMyPublicField
or:
((MainActivity) getActivity()).getPublicMethod()
- but I would never recommend doing this!
especially when you also start manipulating the public field you can run into ugly trouble when different threads are in play.
If something needs so be shared across the whole application, use SharedPreferences (if you want to store it for the next app session too) or as I mentioned first LocalBroadCastManager.

Alternative to a global variable for passing objects between activities

I need to pass a list of objects between activities, I am using a public static global variable in my Application class.
The problem is that this variable seems to be the first to be destroyed when the activity goes in the background for a while.
I never have problems with the activity going in the background but whenever I use a global variable like this, it always the first gets garbage collected or something to fee memory. This causes my application to crash.
How can I prevent this happening?
This is a bad approach of doing it storing it in a global variable.
You should either serialize your class or create a Singleton pattern and store that object in it.
Serializable Approach
public class ClassIntanceOne implements Serializable{
}
//In Activity
ClassIntanceOne class_instance_one = new ClassIntanceOne();
Bundle bundle = new Bundle();
bundle.putSerializable("object1", class_instance_one);
intent.putExtras(bundle);
startActivity(/*Your class*/);
The easiest solution is to include the objects in the intent, that is starting the other activity. This requires, that your objects implement Parcelable or Serializable.
Then just call:
Intent intent = getIntent();
intent.putExtra("myobjects", listOfObjects);
getContext().startActivity(intent);
It is bad practice in android to make use of globel static variables. The GC will always remove them when your activity goes to the background as the value is not used anymore. Also don't try to keep your object longer in memory as you need it. This may cause poor performance on devices with less memory.
Like SME_Dev said, you will need to serialzie your objects and pass them as an intent extra to the activitys.
When you can searialize your objects it's also easier to restore the current state of the app if it get's destroyed because you can make use of the recreating mechanism in android.

Intents or directly accessing a public variable of a different class

I noticed that most programmers in Android use an Intent or broadcast receiver to send a short text message from one class to another class.
If I am using a utility class that does not extend any other class like Activity or Service, why not just directly access the variable in the utility class like this.
UtilityClass utility = new UtilityClass();
String gotIt = utility.theOtherVariable; // direct access to variable in other class
is there anything wrong with doing it this way? I would rather do this than use an intent or broadcast receiver to send the small text message from the utility class to the Activity class.
EDIT
in addition to the instance of the class, you can also make the variable static that your are passing from one activity to another. in either case I don't see any value to using an extra of intent or broadcast receiver to pass information from one Activity to another.
Yes of-course you can use that And even it is good practice that you are using your own data structure but it is depend on need and scenario.
For example suppose you are receiving data from gps and you need that data in your app at some 5-6 places then its good to design one class and store the gps data in the variable of the class and access it where ever you want in your ways
Yes of course its good thing to make public class and keep your where Variable and Function as publicly so you can use in further activity.But that you all ready know that this type of function and variable will be use in some activity.
Where Intent is like Good and easy way to switching data one activity to anther activity.like if you don't want to use some variable more then single next activity then it will useful. More Impotent use of Intent is Return activity Result. like if you want to perform action but its depend on next activity then Intent will use as powerful tool to achieve your task.
Short and Sweet : It's Depend on Requirement.
Try this,
UtilityClass utility = new UtilityClass();
Initialized Utilityclass in Your Activity.Use Utilityclass object you will get all values in your utliityclass.
Example,
public class UtilityClass{
public static string gotIt = "value";
}
public class MainActivity extends Activity {
UtilityClass utility = new UtilityClass();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml);
String str = utility.gotIt;
}

Learning about Intents, passing Data

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.

Categories

Resources