How to create a model containing arrays - android

I'm making a model for daily Forecast but I'm having some trouble with creating this model.
It has regular information (date, description...) but I need it to have various Strings of information in it for every 3 hours...(temperatures, wind speed, wind direction etc)
And that's where I don't know how to do it..maybe with an Array of some sort but not sure.
So far, here is what I have:
public class DayForecast implements Serializable{
private String date;
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Thx!

Try using ArrayList<HashMap<String,String>>. With this you can implement the same with less hassle and in organized manner.
Example usage:
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> data = new HashMap<String,String>();
data.put("description", your_string_description);
data.put("date", your_string_date);
data.put("other", your_string_other_information);
list.add(data);
And to get your data:
list.get(0).get("description"); //will return the string description in position 0
list.get(0).get("date"); //will return the string description in position 0 you can convert it to date if needed
note that the get(0) is the position in your arraylist since with this you can add more items let's say description.

It doesn't sound like an array of Strings would do it, since you mentioned temperature, wind-speed, wind-direction etc. I would create another model for that and store instances of it within the current one.
e.g.
public class WeatherCondition {
private double mTemperature;
private double mWindSpeed;
private String mDirection;
public WeatherCondition(double temperature, double windSpeed, String direction) {
mTemperature = temperature;
mWindSpeed = windSpeed;
mDirection = direction;
}
// ... setter and getter methods ...
}
and
public class DayForecast {
private String mDate;
private String mDescription;
private SparseArray<WeatherCondition> mWeatherConditions = new SparseArray<WeatherCondition>();
public WeatherCondition getWeatherCondition(int timeInHours) {
// return null if no weather condition was set
WeatherCondition weatherCondition = mWeatherConditions.get(timeInHours);
// or you could add some other logic here, if you would want the next available weather condition,
// but make sure to reflect that in the method name
return weatherCondition;
}
public void setWeatherCondition(int timeInHours, WeatherCondition weatherCondition) {
mWeatherConditions.append(timeInHours, weatherCondition);
}
// ... other setter and getter methods
}

Related

how to add value to objects array inside an object firestore

I'm trying to add custom object to array that is inside a custom object,
I mean I have object task I save him in cloud firestore, now I have few sub-tasks that I want to save them in the task object, but I want to add one each time.
I tried this code below:
db.collection(Constants.TASKLIST).document(uid)
.update("subTasks", FieldValue.arrayUnion(subTask));
data struct
http://www.up2me.co.il/v.php?file=2873228.png
this is my Task Object, the Task and subTask are same
public class Task implements Serializable {
private String description;
private String deadline;
private ArrayList<Task> subTasks;
public Task(String description, String deadline) {
this.description = description;
this.deadline = deadline;
this.subTasks = new ArrayList<>();
}
public String getDeadline() {
return deadline;
}
public String getDescription() {
return description;
}
public ArrayList<Task> getSubTasks() {
return subTasks;
}
public void setSubTasks(ArrayList<Task> subTasks) {
this.subTasks = subTasks;
}
public Task(String description) {
this.description = description;
}
public Task() {}
}
but its give me the following error:
Invalid data. Unsupported type:
Your ArrayList contains objects of type Task if I understand correctly.
Firestore only supports a certain amount of data types and that does not seem to be one of them.
Here is a list of the the items you can save on the firestore database.
what you could do for example is save the task as a reference or to make it simple just save the id's of the documents as strings in your array.

Save a List of custom object in savedInstanceState

I am currently building an app to retrieve information for a remote server. the data received are JSON and I am build a list of Data using the class below :
public class RedditData {
private RedditTopic data;
public RedditTopic getData() {
return data;
}
}
and RedditTopic class is defined as below:
public final class RedditTopic {
private static final String TAG = RedditTopic.class.getSimpleName();
private String author;
private String thumbnail;
private String title;
private String num_comments;
private long created_utc;
private String data;
private String name;
public RedditTopic(){};
public String getData() {
return data;
}
public String getAuthor() {
return author;
}
public String getThumbnail(){
return thumbnail;
}
public String getTitle(){
return title;
}
public String getComments(){
return num_comments + " comments";
}
public long getCreated_utc(){
return created_utc;
}
public String getRedditName(){
return name;
}
}
both of these classes are used to translate a JSON into an Object formatted data.
I do not want to really change them to make them Parceable to avoid impacting the extraction of JSON.
I have added :
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> SAVE");
savedInstanceState.putParcelableArrayList("RedditList", myListOfData );
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> RESTORE");
List<RedditData> myListOfData = savedInstanceState.getParcelableArrayList("RedditList");
}
Android complain because I need to implement Parceable in my class RedditData and I assume probably in the RedditTopic Class as well because RedditData returned a List of RedditTopic.
Is there a better way to do it? keep the List as I have it without requiring the Parceable option.
I do not have a List of String, it's a list of object.
Any idea?
Regards
Make your model objects parcleable.
There is a great extension, https://plugins.jetbrains.com/plugin/7332-android-parcelable-code-generator that will generate the neccesary parcelable methods for your class.
I highly recommend it.

sort List of Object by one of Object's field

I understand that Collections.sort(list) does the work for a list of strings, but what about list of Object? Say I have this object Contact:
public class Contact implements Serializable {
private SerializableBitmap picture;
private String name;
private String location;
public Contact() {
}
public void setPicture(SerializableBitmap picture) {
this.picture = picture;
}
public void setName(String name) {
this.name = name;
}
public void setLocation(String location) {
this.location = location;
}
public SerializableBitmap getPicture() {
return picture;
}
public String getName() {
return name;
}
public String getLocation() {
return location;
}
}
Then I have an ArrayList of this object. Is it possible to sort the list based on Contact name? I'm trying to populate it with ListView, but it should be in ascending order.
You need to implement a Custom Comparator like the following
public class ContactComparator implements Comparator<Contact> {
public int compare(Contact contact1, Contact contact2) {
//In the following line you set the criterion,
//which is the name of Contact in my example scenario
return contact1.getName().compareTo(contact2.getName());
}
}
Then all you need is to call it like this (anywhere in your code where you need to have your contacts sorted):
Collections.sort(myContacts, new ContactComparator());
myContacts is the list of Contact objects you need to sort (you name it list in your question).
If you are populating a List you should populate it with just a string[] then find Contact by name to get the contact object back. Then you can sort the string[] for the listview.
As seen in the comment you need to create a new array of object string anyway. It's totally up to you which way you want to do it.

how to get object's attributes

How can I get an object's attributes?
I created an object that has two fields, first one called Title containing the string value "title1" and second one called Description containing the string value "description1". I would like to get the strings inside.
The method item.toString() gets me the two strings one after the other. Is there a way to get the strings separatively?
Just create accessor methods for each field.
Assuming you have declared your fields like this:
private String title;
private String desciption;
create the accessor methods in your class definition like this:
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
then you just call these methods to get the appropriate value.
Class Declaration
public class Class_Name {
private String Category;
private String Category_Type;
public Class_Name () {
super();
}
public Class_Name(String Category, String Category_Type) {
super();
this.Category = Category;
this.Category_Type = Category_Type;
}
/*public Class_Name (String Category_Type) {
this.Category_Type = Category_Type;
}*/
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public String getCategory_Type() {
return Category_Type;
}
public void setCategory_Type(String Category_Type) {
this.Category_Type = Category_Type;
}
}
In the class where you should use this Object to store and retrieve values.
//Create an object for this class
private Class_Name data;
// To save values
data.setCategory(sCategory);
data.setCategory_Type(sType);
// To retrieve values
String sCategory = data.getCategory();
String sType = data.getCategory_Type();

Pass object that contains objects to Activity via Intent

I have an Object that I need to pass via the Intent to another Activity via the onclick method.
I was following this answer here How to send an object from one Android Activity to another using Intents?
Which works fine however my Object has within it an Array of objects.
How do I pass this object with its Array of Objects?
Below are the classes before using Parcelable
List (the object to be passed)
public class List {
private String Name;
private ArrayList<ListItem> items;
public List(){
items = new ArrayList<ListItem>();
}
public void addItem(String title, String d, String s, int p){
ListItem i = new ListItem();
i.setDecription(d);
i.setPrice(p);
i.setSite(s);
i.setTitle(title);
items.add(i);
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getCount() {
return items.size();
}
public ArrayList<ListItem> getList(){
return items;
}
}
ListItem
public class ListItem {
private String title;
private String decription;
private String site;
private int price;
public void setTitle(String title) {
this.title = title;
}
public void setDecription(String d){
this.decription = d;
}
public void setSite(String s){
this.site = s;
}
public void setPrice(int i){
this.price = i;
}
public String getTitle(){
return title;
}
public String getDecription(){
return decription;
}
public String getSite(){
return site;
}
public int getPrice(){
return price;
}
}
So how would I use Parcelable on List to send the ArrayList as well.
THank you and if you need any more info please ask!
You're trying to pass around data that shouldn't normally be passed around. A list is an ideal candidate for an SQLite Database. Try that or another way to persist data in android: http://developer.android.com/guide/topics/data/data-storage.html
If you insist on using Parcelable:
How can I make my custom objects Parcelable?
Also don't use List as your own type, it's standard JAVA.

Categories

Resources