I have my ArrayList
ArrayList<Item> itemList = new ArrayList<Item>();
It is then populated with Items.
Later on, I want to access the items attributes in a loop to get data but
Item[] itemArr = (Item[]) itemList.toArray();
This gives me error:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to com.raynemartin.SAAndroidAppCompetition.Item[]
If this is destined to fail, how else can I access attributes of Items?
The Items are in an ArrayList so they can populate and android ListView. Now I want to sort the ArrayList, but need to access the .getRating() method of my Item class.
Item[] itemArr= (Item[])itemList.toArray();
for(int i =0;i<itemArr.length;i++){
for(int j=i;i<itemArr.length;j++){
if(itemArr[j].getRating()>itemArr[i].getRating()){
Item temp = itemArr[j];
itemArr[j] = itemArr[i];
itemArr[i] = temp;
}
}
}
}
EDIT - here is item class code
public class Item {
private String title;
private String category;
private String downloads;
private double rating;
private Bitmap icon;
public Item(String title, String category, String downloads,double rating,Bitmap icon) {
this.title = title;
this.category = category;
this.downloads = downloads;
this.icon = icon;
this.rating = rating;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDownloads() {
return downloads;
}
public void setDownloads(String downloads) {
this.downloads = downloads;
}
public Bitmap getIcon() {
return icon;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}
To sort you can try the below.
In your Item class implement toString
public String toString()
{
return String.valueOf(rating);
}
Implement a Comparator
class SortingRating implements Comparator<Item>
{
#Override
public int compare(Item arg0, Item arg1) {
if (arg0.getRating() < arg1.getRating()) return -1;
if (arg0.getRating() > arg1.getRating()) return 1;
return 0;
}
}
Then sort your list
Collections.sort(itemList, new SortingRating());
Example : Correct me if i am wrong.
public class MainClass {
static ArrayList<Item> aa = new ArrayList<Item>();
public static void main(String[] args) {
Item i1 = new Item("soap","sales","yes",4.0);
aa.add(i1);
Item i2 = new Item("soap","sales","yes",5.2);
aa.add(i2);
Item i3 = new Item("soap","sales","yes",3.8);
aa.add(i3);
Item i4 = new Item("soap","sales","yes",5.1);
aa.add(i4);
Collections.sort(aa, new SortingRating());
for(int i=0;i<aa.size();i++)
{
System.out.println("Title : " +aa.get(i).getTitle()+"--"+"Category : "+aa.get(i).getCategory()+"--"+"Downlaods : "+aa.get(i).getDownloads()+"--"+"Rating : "+aa.get(i).getRating());
}
}
}
class SortingRating implements Comparator<Item>
{
#Override
public int compare(Item arg0, Item arg1) {
if (arg0.getRating() < arg1.getRating()) return -1;
if (arg0.getRating() > arg1.getRating()) return 1;
return 0;
}
}
Item class. Left out Bitmap icon
public class Item {
private String title;
private String category;
private String downloads;
private double rating;
public Item(String title, String category, String downloads,double rating) {
this.title = title;
this.category = category;
this.downloads = downloads;
this.rating = rating;
}
public String toString()
{
return String.valueOf(rating);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDownloads() {
return downloads;
}
public void setDownloads(String downloads) {
this.downloads = downloads;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}
Output
Title : soap--Category : sales--Downlaods : yes--Rating : 3.8
Title : soap--Category : sales--Downlaods : yes--Rating : 4.0
Title : soap--Category : sales--Downlaods : yes--Rating : 5.1
Title : soap--Category : sales--Downlaods : yes--Rating : 5.2
Let the class Item implement the interface Comparable and use
Collections.sort(itemList);
to sort your collection. So you don't have to construct an array and sort it yourself.
If you really need to access the elements as an array you would be better using
itemList.toArray(new Item[0]);
or
itemList.toArray(new Item[itemList.size()]);
as this will give you an array of type Item rather than an array of object. There is lots of discussion on this issue else where on the web.
Related
I'm not able to get list object which has another list in it through parcelable to another activity. Below is my code.
SnipDataEvents.java
public class SnipDataEvents implements Parcelable {
private String title,image,language,bookingUrl,infoUrl,genre;
private List<Venues> venuesList;
public SnipDataEvents(String title,String image,String language,String genre,String bookingUrl,String infoUrl,List<Venues> list){
venuesList = new ArrayList<>();
venuesList.addAll(list);
this.title = title;
this.image = image;
this.language = language;
this.genre = genre;
this.bookingUrl = bookingUrl;
this.infoUrl = infoUrl;
this.venuesList = list;
}
protected SnipDataEvents(Parcel in) {
title = in.readString();
image = in.readString();
language = in.readString();
bookingUrl = in.readString();
infoUrl = in.readString();
genre = in.readString();
in.readTypedList(getVenuesList(),Venues.CREATOR);
}
public static final Creator<SnipDataEvents> CREATOR = new Creator<SnipDataEvents>() {
#Override
public SnipDataEvents createFromParcel(Parcel in) {
return new SnipDataEvents(in);
}
#Override
public SnipDataEvents[] newArray(int size) {
return new SnipDataEvents[size];
}
};
public String getImage() {
return image;
}
public String getTitle() {
return title;
}
public List<Venues> getVenuesList() {
return venuesList;
}
public String getBookingUrl() {
return bookingUrl;
}
public String getGenre() {
return genre;
}
public String getInfoUrl() {
return infoUrl;
}
public String getLanguage() {
return language;
}
public void setVenuesList(List<Venues> venuesList) {
this.venuesList = venuesList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
parcel.writeString(image);
parcel.writeString(language);
parcel.writeString(bookingUrl);
parcel.writeString(infoUrl);
parcel.writeString(genre);
parcel.writeTypedList(venuesList);
}
}
Venues.java
public class Venues implements Parcelable {
private String name;
//private List<String> showTimes;
public Venues(String name, List<String> showTimes) {
//showTimes = new ArrayList<>();
this.name = name;
//this.showTimes = showTimes;
}
protected Venues(Parcel in) {
name = in.readString();
//showTimes = in.createStringArrayList();
}
public static final Creator<Venues> CREATOR = new Creator<Venues>() {
#Override
public Venues createFromParcel(Parcel in) {
return new Venues(in);
}
#Override
public Venues[] newArray(int size) {
return new Venues[size];
}
};
public String getName() {
return name;
}
//public List<String> getShowTimes() {
// return showTimes;
// }
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
}
}
MainActivity.java
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("snipdataevents",(ArrayList<SnipDataEvents>)snipDataEvents);
intent.putExtras(bundle);
startActivity(intent);
DetailActivity.java
Bundle bundle = getIntent().getExtras();
snipDataEvents = bundle.getParcelableArrayList("snipdataevents");
when I run the code ,in DetailActivity.java bundle.getParcelableArrayList("snipdataevents") returns null
when I removed this
in.readTypedList(getVenuesList(),Venues.CREATOR);
and
parcel.writeTypedList(venuesList);
aboves lines in SnipDataEvents.java
then run, bundle.getParcelableArrayList("snipdataevents") returns list.
I don't know whats wrong with the code...
Can anyone please help??
You can done this one by Passing ArrayList in form of String.
Add implementation 'com.google.code.gson:gson:2.8.4' in dependencies block build.gradle.
Click on Sync Project with Gradle Files
SnipDataEvents.java
public class SnipDataEvents {
private String title, image, language, bookingUrl, infoUrl, genre;
private List<Venues> venuesList;
public SnipDataEvents(String title, String image, String language, String genre, String bookingUrl, String infoUrl, List<Venues> list) {
venuesList = new ArrayList<>();
venuesList.addAll(list);
this.title = title;
this.image = image;
this.language = language;
this.genre = genre;
this.bookingUrl = bookingUrl;
this.infoUrl = infoUrl;
this.venuesList = list;
}
public String getImage() {
return image;
}
public String getTitle() {
return title;
}
public List<Venues> getVenuesList() {
return venuesList;
}
public void setVenuesList(List<Venues> venuesList) {
this.venuesList = venuesList;
}
public String getBookingUrl() {
return bookingUrl;
}
public String getGenre() {
return genre;
}
public String getInfoUrl() {
return infoUrl;
}
public String getLanguage() {
return language;
}
}
Venues.java
public class Venues {
private String name;
public Venues(String name, List<String> showTimes) {
this.name = name;
}
public String getName() {
return name;
}
}
MainActivity.java
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putExtra("snipdataevents", new Gson().toJson(snipDataEvents));
intent.putExtras(bundle);
startActivity(intent);
DetailActivity.java
String json = getIntent().getStringExtra("snipdataevents");
snipDataEvents = Arrays.asList(new Gson().fromJson(json, SnipDataEvents[].class))
im newbie on android. I need to send data from ListView with customAdapter to detailActivity that show detail's item from selected item of listView. I have seen a few post about it and i still confuse about it.
Would you help me?
This is my data class :
public class ListData {
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
}
This is my arrayList declaration :
ArrayList<ListData> data = new ArrayList<ListData>();
data.add(new ListData("Sidik Suhendar", "Telkom University"));
I don't have idea, how i can send my arraylist data to another activity. Please help me :) give me some example too :) Thanks
You need to make your base object, ListData parcelable:
public class ListData implements Parcelable {
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
#Override
public int describeContents() {
return 0;
}
public ListData(Parcel source) {
title = source.readString();
desc = source.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(desc);
}
public static final Creator<ListData> CREATOR = new Creator<ListData>(){
#Override
public ListData createFromParcel(Parcel source) {
return new ListData(source);
}
#Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
Once it is parcelable you can simply do in the first activity:
ArrayList<ListData> data = new ArrayList<ListData>();
data.add(new ListData("Sidik Suhendar", "Telkom University"));
intent.putParcelableArrayListExtra("ARRAY_LIST", data);
And you can read it in the other activity as:
ArrayList<ListData> data = (ArrayList<ListData>) getIntent().getExtras().getParcelableArrayList("ARRAY_LIST");
EDIT:
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ListData item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,DetailActivity.class);
intent.putExtra("ARRAY_ITEM", item);
startActivity(intent);
}
});
Then in the destination activity:
ListData data = (ListData) getIntent().getExtras().getParcelable("ARRAY_ITEM");
First step: ListData implements Parcelable:
public class ListData implements Parcelable {
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeString(this.desc);
}
protected ListData(Parcel in) {
this.title = in.readString();
this.desc = in.readString();
}
public static final Parcelable.Creator<ListData> CREATOR = new Parcelable.Creator<ListData>() {
#Override
public ListData createFromParcel(Parcel source) {
return new ListData(source);
}
#Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
Second step:send data:
ArrayList<ListData> data = new ArrayList<ListData>();
data.add(new ListData("Sidik Suhendar", "Telkom University"));
Intent intent = new Intent(this, TargetActivity.class);
intent.putParcelableArrayListExtra("data",data);
Third step:receive data
ArrayList<ListData> data = intent.getParcelableArrayListExtra("data");
I put in intent my object with following code (while putting list does exists, I checked in debugger)
Intent intent = new Intent(getApplicationContext(), ProductActivity.class);
intent.putExtra("product", CategoryActivity.this.list.get(position));
startActivity(intent);
And then retrive
Intent intent = getIntent();
product = (Product) intent.getSerializableExtra("product");
But it is null
Model class is following
public class Product implements Serializable {
Integer pk;
String name;
String description;
Integer price;
String image_url;
List<Option> options;
public Product(Integer pk, String name, String description, Integer price, String image_url, List<Option> options) {
this.pk = pk;
this.name = name;
this.description = description;
this.price = price;
this.image_url = image_url;
this.options = options;
}
public Integer getPk() {
return pk;
}
public void setPk(Integer pk) {
this.pk = pk;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
}
What am I doing wrong ?
You have to add more code to use your class inside intent data.
import android.os.Parcel;
import android.os.Parcelable;
public class Yourclass implements Parcelable {
//your code
#Override
public void writeToParcel(Parcel out, int flags) {
//e.g.
out.writeInt(this.getWhat());
//similar code
}
#Override
public int describeContents() {
return 0;
}
private YourClass(Parcel in) {
//e.g.
this.setWhat(in.readInt());
}
public static final Parcelable.Creator<YourClass> CREATOR
= new Parcelable.Creator<YourClass>() {
public YourClass createFromParcel(Parcel in) {
return new YourClass(in);
}
public YourClass[] newArray(int size) {
return new YourClass[size];
}
};
}
to store use intent.putExtra(EXTRANAME, obj); to retrieve use YourClass myObj = (YourClass) getIntent().getParcelableExtra(EXTRANAME);
I have created the following parcelable object:
public class ViewModel implements Parcelable {
private String image, price, credit, title, description, id;
public ViewModel(String image, String price, String credit, String title, String description, String id) {
this.image = image;
this.price = price;
this.credit = credit;
this.title = title;
this.description = description;
this.id = id;
}
public String getPrice() {
return price;
}
public String getCredit() {
return credit;
}
public String getDescription() {
return description;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getImage() {
return image;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {
this.image,
this.price,
this.credit,
this.title,
this.description,
this.id
});
}
/** Static field used to regenerate object, individually or as arrays */
public static final Parcelable.Creator<ViewModel> CREATOR = new Parcelable.Creator<ViewModel>() {
public ViewModel createFromParcel(Parcel pc) {
return new ViewModel(pc);
}
public ViewModel[] newArray(int size) {
return new ViewModel[size];
}
};
/**Creator from Parcel, reads back fields IN THE ORDER they were written */
public ViewModel(Parcel pc){
image = pc.readString();
price = pc.readString();
credit = pc.readString();
title = pc.readString();
description = pc.readString();
id = pc.readString();
}
}
Now I am sending an ArrayList of ViewModel through bundle:
bundle.putParcelableArrayList("products", viewModels);
Is there anything wrong I am doing? Because I get null Bundle Arguments, but if I send a simple string, everything works.
make this change:
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.image);
dest.writeString(this.price);
dest.writeString(this.credit);
dest.writeString(this.title);
dest.writeString(this.description);
dest.writeString(this.id);
}
getIntent().getParcelableArrayListExtra("product"); // get the list
You are trying to retrieve a parcelable ArrayList. You need to retrive a parcelable ViewModel object that you created. Change:
bundle.putParcelableArrayList("product", viewModels);
and
getIntent().getParcelableArrayList("product");
to:
bundle.putParcelable("product", viewModels);
and
getIntent().getParcelable("product");
I am using Sugar ORM 1.3.1 and i am trying to save the following objects
public class Article extends SugarRecord<Article> implements Serializable {
#JsonProperty("Categories")
private List<Category> categories = new ArrayList<Category>();
#JsonProperty("Contents")
private List<Content> contents = new ArrayList<Content>();
#JsonProperty("Country")
private CountryRelated country;
#JsonProperty("Description")
private String description;
#JsonProperty("ExpiryDate")
private String expiryDate;
#JsonProperty("ExtraFields")
private List<ExtraField> extraFields = new ArrayList<ExtraField>();
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("ImageURL")
private String imageURL;
#JsonProperty("Name")
private String name;
#JsonProperty("PortalID")
private int portalID;
#JsonProperty("PublishDate")
private String publishDate;
#JsonProperty("Region")
private Region region;
#JsonProperty("Related")
private List<Related> related = new ArrayList<Related>();
#JsonProperty("Newsbite")
private boolean newsbite;
#JsonProperty("ShareURL")
private String shareURL;
#JsonProperty("Tags")
private List<Tag> tags = new ArrayList<Tag>();
#JsonProperty("Type")
private int type;
public Article() {
}
public Article(List<Category> categories, List<Content> contents, List<ExtraField> extraFields, CountryRelated country, String description, String expiryDate, int identifier, String imageURL, String name, boolean newsbite, int portalID, String publishDate, Region region, List<Related> related, String shareURL, List<Tag> tags, int type) {
this.categories = categories;
this.contents = contents;
this.extraFields = extraFields;
this.country = country;
this.description = description;
this.expiryDate = expiryDate;
this.identifier = identifier;
this.imageURL = imageURL;
this.name = name;
this.newsbite = newsbite;
this.portalID = portalID;
this.publishDate = publishDate;
this.region = region;
this.related = related;
this.shareURL = shareURL;
this.tags = tags;
this.type = type;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Content> getContents() {
return contents;
}
public void setContents(List<Content> contents) {
this.contents = contents;
}
public List<ExtraField> getExtraFields() {
return extraFields;
}
public void setExtraFields(List<ExtraField> extraFields) {
this.extraFields = extraFields;
}
public CountryRelated getCountry() {
return country;
}
public void setCountry(CountryRelated country) {
this.country = country;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNewsbite() {
return newsbite;
}
public void setNewsbite(boolean newsbite) {
this.newsbite = newsbite;
}
public int getPortalID() {
return portalID;
}
public void setPortalID(int portalID) {
this.portalID = portalID;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Related> getRelated() {
return related;
}
public void setRelated(List<Related> related) {
this.related = related;
}
public String getShareURL() {
return shareURL;
}
public void setShareURL(String shareURL) {
this.shareURL = shareURL;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
Category.class
public class Category extends SugarRecord<Category> implements Serializable {
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("Name")
private String name;
public constructor + getters and setters }
Content.class and CountryRelated.class have same structure
after i do article.save() my lists doesnt save . Am i doing something wrong or it doesnt save lists at all ???
I few things to look at.
First. I do not believe that the database will handle a column with the type of List or a type of other Object. When I tried running your code, I received:
Class cannot be read from Sqlite3 database. Please check the type of field categories(java.util.List)
These should be types the database can store. Try serializing your List(s) to Strings to insert them in the db. You can try doing this in your getter and setter. The setter takes the list of objects and converts it to a serialized String, the getter takes the serialized String and converts it back to a list of objects.
In the instance of SugarOrm, you can reference another table and it will create a relationship outlined here:
http://satyan.github.io/sugar/creation.html#why
Notice the "Author" type is just referencing a record from another table in the database.
Second I usually try and set my default values inside my default constructor. so something like:
... property declarations...
public Article() {
this.name = "Default Value";
}
Hope this helps you finish troublshooting!