Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hey guys I am reasonably new to Android programming but have some experience with .net anyway what I would like to do is create a class say RestartDialog then call this class from an activity. Normally in .net I would use:
RestartDialog rd = new RestartDialog();
rd.setType(EXTENDED_TYPE);
rd.show;
then it would start in extended mode however in Android you need Intents to start activitys and this is the only way am I right? I know I can use Intent.putExtra etc but I will need to set many values first.
What would be my best bet to achive this please? Thanks in advance for your help.
Intent is the way to send data. so in case you have to send many data, you can use Parcelable. It is way faster also..
If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).
From the docs, a simple example for how to implement is:
// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
private int mData;
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).
Once you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra():
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
Then you can pull them back out with getParcelableExtra():
Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
You may also use GSON to send data..
First, you'll want to create an Intent:
Intent intent = new Intent();
Think of an intent as a way to store data values:
intent.putExtra("type", EXTENDED_TYPE);
When you're done putting information in your intent, you start the activity:
startActivity(intent);
Then, in your new activity, you extract the values you need in your onCreate method:
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.email_login_activity);
Intent intent = getIntent();
this.type = intent.getIntExtra("type", 0);
In this case, I've made getIntExtra return 0 if the extra "type" was not set.
Let me know if you have any other questions.
Though the easiest solution would be:
To create a class with static data members with getters setters.
set from one activity and get from another activity that object.
activity A
mytestclass.staticfunctionSet("","",""..etc.);
activity b
mytestclass obj= mytestclass.staticfunctionGet();
Related
I have a problem with with sharing data between two different activities. I have data like :
int number
String name
int number_2
int time
int total
I'm trying to make something like order list with this set of data . So it will take one set of data , then back to previous activity , move forward and again add data to it .
I have an idea of making it in array of object - but data inside was cleared after changing activity.
How can I make it ?
I don't know if and how to add Array of object to SharedPreferences , and get value of one element from there.
You should have a look at the documentation of the Intent(s) if you want to do that on the fly associating a key to the value(s) that you want to pass to your second activity.
Anyway, you can think any(sharedpref, database,...) way to pass your parameters but for those kind of things it's a convention and a good practice to follow that.
Don't used share preferences for this...Use the singleton pattern, extend Application, or just make a class with static variables and update them...
You can use .putExtra but since you are communicating with more than one activity the above suggestions are probably the best.
public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}
public static ShareData getInstance(){ return shareData}
//create getters and setters;
}
Why not to use Intents
Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);
in the second activity
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");
EDIT if you want to read more about adding array to shared preferences check this
Is it possible to add an array or object to SharedPreferences on Android
also this
http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html
I have been working on a e-commerce application for a while, and now I have a ListView that displays a list of products - Each products = 1 ImageView and some TextViews-.
I set an onItemClick listener on that ListView, the event that I want to occur when I click on one of that listView products is, Start the i new Activity, 'ProductDetails' that displays more informations on the product I have clicked on.
I have already asked this question somewhere else, but I didn't get a clear answer,
They said that I have to create a new 'list\details' project, but this can't happen now, as I've working on that project for like 20 days, and can't start all over again.
You can't send a TextView or an ImageView from Activity to Activity. what you can send instead is it's contents. so for example if you want to pass the information from the TextView you will need to pass the source String that is displayed there (Or extract the String from the TextView) you do that by passing a Bundle from the calling Activity to the invoked one or simply by putting it as an Extra:
intent.putExtra("string name", value);
and in the following Activity you get this data:
Intent intent = getIntent();
bundle = intent.getExtras();
bundle.getString("string name");
Then in the following Activity create a TextView with the passed String.
Same way is handled with the ImageView by passing the it's path.
Sorry I have posted an answer but was only a link to another site so it was deleted :-(
Here I come again with what could be the solution:
In your first activity, you need to use intent.putExtra(...) and retrieve the datas in your second activity with intent.getExtra(...).
Example activity 1:
i.putExtra("title01", yourDataCollection.get(position).get(KEY_TITLE01));
Activity 2 :
this.title01 = i.getStringExtra("title01");
There is a full project here : http://www.codeproject.com/Articles/507651/Customized-Android-ListView-with-Image-and-Text
Android uses intent to allow Activitys to interact. If you want to show a details of product, probably you have a Class that describe that product and with the information it holds you fill up your ListView. If you let the class Product implements Serializable you can use Intent.putExtra(String name, Serializable obj), to pass the Product description between Activitys. In ProductDetailsActivity you can use:
getIntent(). getSerializableExtra (String name)
to retrive the serializable you put inside the Intent you created to start ProductDetailsActivity
If you pass your model class around many times using Intent, perhaps it could implement the Parcelable interface for convenience. For example:
class ProductData implements Parcelable {
protected String name;
protected String someOtherData;
public static final Parcelable.Creator<ProductData> CREATOR = new Parcelable.Creator<ProductData>() {
#Override
public ProductData createFromParcel(Parcel source) {
return new ProductData(source);
}
#Override
public ProductData[] newArray(int size) {
return new ProductData[size];
}
};
public ProductData(){
}
public ProductData(Parcel source){
readFromParcel(source);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(someOtherData);
}
public void readFromParcel(Parcel source){
name = source.readString();
someOtherData = source.readString();
}
// Here goes the rest of your model code
}
Then you can easily pass the object to another Activity using an Intent:
intent.putExtra("product", productData);
and later get the data using
ProductData productData = intent.getParcelableExtra("product");
This question already has answers here:
Passing ArrayList through Intent
(6 answers)
Closed 9 years ago.
Is there a way to pass an ArrayList <ArrayList<Integer>> floors to another activity through Bundle?
Thanks
Is there a way to pass an ArrayList > floors to
another activity through Bundle?
Unfortunetly not.
If you would have ArrayList without nested it will work with putIntegerArrayList(key, value) and getIntegerArrayList(key).
But there is for sure another approach(es).I will explain you one possible way.
You can create class that will implement Serializable interface and in this class just create field and appropriate getter. I will give you basic example. Then you will pass Serializable through Activities.
public class DataHelper implements Serializable {
private ArrayList<ArrayList<Integer>> floors;
public DataHelper(ArrayList<ArrayList<Integer>> floors) {
this.floors = floors;
}
public ArrayList<ArrayList<Integer>> getList() {
return this.floors;
}
}
Save it to Bundle:
Bundle b = new Bundle();
b.putSerializable("floors", new DataHelper(floors));
and retrieve in target Activity:
getIntent().getExtras().getSerializable("floors");
To pass the arraylist from first activity to second activity.
Intent intent = new Intent(context, SecondActity.class);
intent.putIntegerArrayListExtra("arraylist",integerList); //integerList is ArrayList<Integer>
startActivity(intent);
To get the arrayList in second Activity.
ArrayList arrayList<Integer> = getIntent().getIntegerArrayListExtra("arraylist")
Read here.
If you want to pass the custom object between activities then read this thread.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Help with passing ArrayList and parcelable Activity
I have already tried to use putExtra() but to no avail.
When I use putExtra(), there were syntax error. and the only way (it seems) is to convert the whole data selected to string. But the problem is, I only need to display part of the data and not all of it. therefore I think that is not the way.
What I am trying to do is to send an ArrayList of data. The first Activity is where the program search the Array for the data and the second Activity is for displaying part of the data.
I need to send the data onClick() of the ListView. And I need the data to be in ArrayList<Item>.
Before anyone answers or comment on this question more please take a look at my reputation. So with that much reputation I think you know that I am new. Just take that into consideration before downvoting.
Assume you have a class like this, which implements Parcelable:
public class CustomParcelableClass implements Parcelable {
public String string;
public int i;
#Override
public int describeContents() {
return hashCode();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(i);
dest.writeString(string);
}
private Item(Parcel in) {
string= in.readString();
}
}
and you make an Intent like this:
ArrayList<CustomParcelableClass> myParcelableList =
new ArrayList<CustomParcelableClass>();
myParcelableList.add(...);
...
yourIntent.putParcelableArrayListExtra(LIST, myParcelableList);
where LIST is something like:
public static final String LIST = "LIST";
and in your second class, in a method like onNewIntent(Intent i), retrieve your ArrayList through a line like
ArrayList<CustomParcelableClass> myParcelableList =
i.getExtras().getParcelableArrayList(LIST);
I do not know why this shouldn't work for you.
I'd like to pass a custom Object from one activity to another, the Object consists of a String and a List of another custom Object which consists of an array of strings and an array of ints. I've read https://stackoverflow.com/a/2141166/830104, but then I've found this answer https://stackoverflow.com/a/7842273/830104. Which is better to use Bundle or Parcelable? What is the difference? When should I use this each? Thanks for your replies, Dan
Parcelable and Bundle are not exclusive concepts; you can even deploy both on your app at a time.
[1] Term Parcelable comes with Serialization concept in Java (and other high-level language such as C#, Python,...). It ensures that an object - which remains in RAM store - of such Parcelable class can be saved in file stream such as text or memory (offline status) then can be reconstructed to be used in program at runtime (online status).
In an Android application, within 2 independent activities (exclusively running - one starts then other will have to stop):
There will be NO pointer from current activity to refer to previous one and its members - because previous activity is stopped and cleared out form memory; so that to maintain object's value passed to next activity (called from Intent) the object need to be parcelable (serializable).
[2] While Bundle is normally the Android concept, denotes that a variable or group of variables. If look into lower level, it can be considered as HashMap with key-value pairs.
Conclusion:
Bundle is to store many objects with related keys, it can save any object in native types, but it doesn't know how to save a complex object (which contains an ArrayList for example)
Parcelable class is to ensure a complex instance of it can be serialized and de-serialized during runtime. This object can contains complex types such as ArrayList, HashMap, array, or struct,...
[UPDATED] - Example:
//Class without implementing Parcelable will cause error
//if passing though activities via Intent
public class NoneParcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public NoneParcelable()
{
nameList.add("abc");
nameList.add("xyz");
}
}
//Parcelable Class's objects can be exchanged
public class GoodParcelable implements Parcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public GoodParcelable()
{
nameList.add("Can");
nameList.add("be parsed");
}
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
// Serialize ArrayList name here
}
}
In source activity:
NoneParcelable nonePcl = new NoneParcelable();
GoodParcelable goodPcl = new GoodParcelable();
int count = 100;
Intent i = new Intent(...);
i.putExtra("NONE_P",nonePcl);
i.putExtra("GOOD_P",goodPcl);
i.putExtra("COUNT", count);
In destination activity:
Intent i = getIntent();
//this is BAD:
NoneParcelable nP = (NoneParcelable)i.getExtra("NONE_P"); //BAD code
//these are OK:
int count = (int)i.getExtra("COUNT");//OK
GoodParcelable myParcelableObject=(GoodParcelable)i.getParcelableExtra("GOOD_P");// OK