Actually,my application flow is like this Home->A->B->Info(form data)->D->Final page.From final page if I press on one button it again navigates back to A page and start the flow from onwards.If I comes to info page I should display the earliear data.Right now my approach is passing parcelable object within all acitivities from A->B->Info->D->Final.If suppose want to use Preferences, doesn't supports the parcelable object and don't want to put each string of object individually within preferences becaus I had more than 10 items within object.Is there any better approach without passing bundle between actvities.
BR,
Developer.
you can create Global class and declare Static variables and use them in anyware in the application.
Example:
public class global_variable {
public static String sample ;
}
where you want to use ;
global_variable.sample = "your value";
You could use any number of technologies to parse your data object into a string and reassemble again. Then you could store the string in preferences.
Take a look at gson to convert objects to json http://code.google.com/p/google-gson/
Or you could google xstream to convert to xml
If you create a class representing your 'object' with appropriate setters/getters and let that class implement Parceable and then pass that class between Activites as a Parceable in a Bundle, would that be bad?
If that would be bad (e.g. if the amount of object data is very big or they are somehow not Parceable in principle) and you only have one meaningful instance of a class at a time you can make that class a singleton or keep it within your Application object.
Related
Let's assume I have a class MainActivity.
This contains a number of objects stored in fields, such as instances of Player, Enemy, Level, etc. Each of these objects needs to be able to refer to every other object.
What is the best way to go about this?
Make these fields static, and refer to them accordingly, i.e.
MainActivity.player.setHealth(0);
Create getter methods for each field, and simply pass each object a reference to MainActivity, so that they can call these getter methods, i.e.
mainActivity.getPlayer().setHealth(0);
Pass each object a reference to every other object, and store these references in fields within each object, so that they can be referred to directly, i.e.
player.setHealth(0);
Not a real answer but just to give you some tips.
Your Player should be like so:
public class Player
{
private static Player _player = null;
int _health;
...
public static Player getInstance()
{
if (_player == null)
_player = new Player(...);
return _player;
}
public void increaseHealth(int amount)
{
_health += amount;
}
}
Then in any part of your application when you need a Player you can do:
Player p = Player.getInstance();
and you will get the same player all the time. You can do a similar thing with your level class as only 1 level will be active at any one time.
However the Enemy class will need a different approach. I would make a List inside the Level class and get at them like so:
Level l = Level.getInstance();
List<Enemy> enemiesOnLevel = l.getEnemies();
// do something with them
Have a look in the Android docs here: http://developer.android.com/guide/faq/framework.html#3. There is also the possibility to serialize your object into primitive datatypes and pass those within your Intent to the new Activity.
A couple more options to share objects between activities are to use parcable, which I think is probably the highest performance method, and shared preferences.
In my app I used to learn (the little I know about android programming), I used gson to serialize the object to json, then stored it in shared preferences in activity A , then recreated it from shared preferences in activity B, and then stored it again.
I want to know when to use parcelable and when not to . I know that parcelable is way of parcel complex data type in android , but as per official document http://developer.android.com/guide/faq/framework.html#3 , nothing such is mention . So when is parcelable really needed ??
By implementing the Parcelable interface, you can make your class object capable of being stored in a Bundle and you can then easily pass it to another activity with the help of an Intent.
e.g.
Intent i = new Intent(....);
i.putParcelableExtra("name", object);
Then in the other activity, get it like this:
YourClass object = (YourClass) getIntent().getExtras().getParcelableExtra("name");
Notice the typecasting. That is necessary in order to use your class's methods.
To pass data to another activity, we are usually put bundle object on activity intent that will be called. Bundle can be filled with primitive data types like long, integer, and boolean. It can be filled with simple data type like String class to represent text. For example, an activity calls another activity at the same time sends simple data to it.
In destination activity, we check the bundle. If it is exist, we open the data of bundle from the origin activity.
Now, how if we want to pass the complex data type like our defined class object to another activity? For this need, we can use Parcelable in Android.
Parcelable is an interface for classes so a class that implements Parcelable can be written to and read from a Parcel. The data in Parcel form can be passed between two threads. Parcel itself is a class that have abilities to serialize and deserialize object of class.
I have an object which has the following class fields:
int, int, String, MyDatabaseType (custom object), List < MyDatabaseDetail > (array list of custom objects)
Is it possible for me to pass this through an intent/bundle?
I've played around a little bit with serializable and parcelable, but I couldn't get it working. Would I need to make all of custom object types parcelable, instead of just the main one that I want to pass?
Surely there is a better way?
When you pass data in an intent, it must be Parcelable. That is because the intent may passed to a different application, and thus a different VM. As your object may be crossing process boundaries, it needs a mechanism that will allow it to be saved/restored. This is analogous to passing data via a web service call (in this case, the object is "flattened" to something like either XML or JSON).
Even if the intent stays within your application, parcelability allows the object to survive even if Android chooses to kill/re-launch your application, which can happen if memory is running low.
Serialization can be used instead of parcelization, however parcelization is more efficient.
You can make your class Parcelable if it contains variables that are not serializable. If all variables inside your class are primitive or serializable or you can make them serializable, it's easy enough to do it.
You can follow this guide: http://developer.android.com/reference/java/io/Serializable.html
In most cases, all you have to do is to make your class implement Serializable interface and add the following line in your class:
private static final long serialVersionUID = 0L;
(read more in the guide above).
Is it possible for Activity(s) to communicate using user defined object?
p.s.
So far as I know, when I want Activity(s) to communicate to each other, I have to use primitive type of objects, such as int, String, boolean,...etc.
We don't use Serializable, Parcelable and static class.
If talkin about extras when caling intents, you can implement Serializable or Parcelable interface in your objects to pass them through.
You can also put that object into own implementation of Application class and access it in Activity or Service class as described in my other answer. But please keep in mind, that sharing state in that manner may be a sign of more general problem in your design.
You have a few options:
1.You could wrap the more complex structure in a class that implements the Parcelable interface, which can be stored in an extra.
2.You could wrap the more complex structure in a class that implements the Serializable interface, which can be stored in an extra
3.You use static data members to pass stuff around, since they are all in the same process
4.You use external storage (file, database, SharedPreferences)
5.As the person who just posted noted, use a common component, such as a custom Application or a local Service
What you do not want to do is pass big stuff via extras. For example, if you are creating an application that grabs pictures off the camera, you do not want to pass those in extras -- use a static data member (icky as that sounds). Intents are designed to work cross-process, which means there is some amount of data copying that goes on, which you want to avoid when it is not necessary for big stuff.
Answer copy from here
Intent myintent = new Intent(Info.this, GraphDiag.class).putExtra("<StringName>", value);
startActivity(myintent);
use the above code in parent activity
and in child activity
int s= getIntent().getIntExtra("<StringName>");
in the same u retrive the float,char,String values
This question already has answers here:
How to pass an object from one activity to another on Android
(35 answers)
Closed 9 years ago.
I need to be able to use one object in multiple activities within my app, and it needs to be the same object. What is the best way to do this?
I have tried making the object "public static" so it can be accessed by other activities, but for some reason this just isn't cutting it. Is there another way of doing this?
When you are creating an object of intent, you can take advantage of following two methods
for passing objects between two activities.
putParcelable
putSerializable
You can have your class implement either Parcelable or Serializable. Then you can pass around your custom classes across activities. I have found this very useful.
Here is a small snippet of code I am using
CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);
And in newly started activity code will be something like this...
Bundle b = this.getIntent().getExtras();
if (b != null)
mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);
You can create a subclass of Application and store your shared object there. The Application object should exist for the lifetime of your app as long as there is some active component.
From your activities, you can access the application object via getApplication().
This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,
class Myclass {
int a;
class SubClass {
int b;
}
}
With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,
MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String
Now you can pass this String across activities as a StringExtra with the activity intent.
Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);
Then in the receiving activity, create the original object from the string representation.
String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object
It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.
UPDATE
While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.
Eventbus
Otto
Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,
public class PersonHelper
{
public static Person person;
}
I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.
It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable and pass them in the extras of the Intent to start the new Activity.
Your object can also implement the Parcelable interface. Then you can use the Bundle.putParcelable() method and pass your object between activities within intent.
The Photostream application uses this approach and may be used as a reference.