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");
Related
I'm building a book reader app and currently having some issues on how to move to next or previous chapter.
The fragment that is in charge of showing a list of chapter (basically a ListView). I capture the item with onItemClick:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity().getApplicationContext(),ReaderActivity.class);
intent.putExtra("name",adapter.getItem(i).getName());
intent.putExtra("url",adapter.getItem(i).getUrl());
startActivity(intent);
}
});
It will start the ReaderActivity and display the content of the book. Now the ReaderActivity has 2 buttons for moving to next/previous chapter. How can I get the data (the name and url) from the ListView?
At the moment I'm thinking of two methods:
Calling finish() on ReaderActivity and override the onDestroy() method to call a method to get the next/previous data in the fragment that holds the ListView.
Passing the whole ArrayList of chapters to ReaderActivity so it can retrieve the item it wants (probably not a good solution since there are too many chapters).
Is there a better way?
There are way to many ways to get the best one.
Some of them:
Use your Application.java to share in-memory data (data stores) from any place. Example:
public final Application extends android.app.Application {
private List<Chapter> chapters;
public void setChapters(List<Chapter> chapters) {
this.chapters = chapters != null ? chapters : Collections.<Chapter>epmtyList();
}
public List<Chapter> get Chapters() {
return chapters;
}
}
// from any place which has context (or is context)
List<Chapter> chapters = ((Application) getContext().getApplicationContext()).getChapters();
Make your list a static member with a public static getter and then reference is from your ReaderActivity
public final ApplicationActivity extends Activity {
private static List<Chapter> chapters;
....
public static List<Chapter> getChapters() {
return chapters;
}
Store the list in shared preferences so any activity can reference it
Include the list of chapters in your intent extras and pass it to your ReaderActivity
I think your ReaderActivity needs to deal with the whole book rather a single chapter. Which means approach (4) is most likely a good candidate.
I would put the list data in the Application class (or another singleton), and then the ReaderActivity would be able to query it for the next chapter. Actually then it could just get the details of the next chapter and update its contents accordingly, without needing to create a new activity at all.
In my project have to populate the list view from local database.I have implemented it.When I click the row in list item I need to show all the details in list row in next activity.I implemented custom list adapter.I not yet started to code for detailed list row.How can I pass all details in single row to another activity.Can anyone help me?
You can set the information in tags of textviews of your custom list and pass them through intents.
one thing that you can do is just pass the id (PK) of the item . Then on next activity you can fetch it again from database.
another options is that you can create a class with all the data you want to forward as class'members and serialize the object and send it along with the intent.
here is a example
public class ActivityExtra implements Parcelable {
public Integer a=0;
public String b="";
private GameActivityExtra(Parcel in) {
this.a = in.readInt();
this.b = in.readString();
}
public GameActivityExtra() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(a);
dest.writeString(b);
}
public static final Parcelable.Creator<GameActivityExtra> CREATOR = new Parcelable.Creator<GameActivityExtra>() {
public GameActivityExtra createFromParcel(Parcel in) {
return new GameActivityExtra(in);
}
public GameActivityExtra[] newArray(int size) {
return new GameActivityExtra[size];
}
};
}
now create instance of this class in your activity . and use intent.putextra(...) to put it . and get the same object while receiving it.
Use #nitesh goel answer to make your object class parcelabe.
Then onitemclick use
intent.putExtra("object", object);
to send your object to other activity.
And in corresponding activity use
intent.getParcelableExtra("object");
to get your object. then you can get everything of that object.
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();
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