How to create an object from UI elements in a nice way? - android

In my android application I have some fields like
MyButton a;
MyEditText b;
MySpinner c;
MyTextView d;
Each of these is like public class MyButton extends Button implements InfoExtract and
public interface InfoExtract{
String getTheText();
}
Out of these fields (the user can change some of them), there is a UserProfile to be created like so:
public class ProfileUpdate {
// The fields have to be string no matter what
String firstName;
String lastName;
String dateOfBirth;
String relationshipStatus
}
The execution flow is like that:
List<InfoExtract> uiElements = new ArrayList<InfoExtract>();
uiElements.add(a);
uiElements.add(b);
uiElements.add(c);
uiElements.add(d);
someButton.setOnClickListener(new SaveProfileListener(uiElements);
The SaveProfileListener more or less does this:
ProfileUpdate pup = new ProfileUpdate();
int i = 0;
pup.firstName = uiElements.get(i++).getTheText()
pup.lastName = uiElements.get(i++).getTheText();
pup.dateOfBirth = uiElements.get(i++).getTheText();
pup.relationshipStatus = uiElements.get(i++).getTheText();
Bad thing #1: If I want to add another fields its obviously much work.
Bad thing #2: The order of elements in the list is important.
Bad thing #3: I cannot easily manipulate the date format for dateOfBirth for example.
What i could have done but what is equally bad:
// Pass the listener what fields it should use.
someButton.setOnClickListener(new SaveProfileListener(a, b, c, d);
How to make this nice and clean?

I ended up using a Map and a new Enum type for each field.

Related

Is it possible to hide some fields from our model?

I decided to use Room for caching data and now because of the situation of the library that I developed, I need to hide some fields of my model and then give them to the client that use my library.
The model below had orderId and I added this because I need that but when I don't want to give this filled model with orderId. i know how to ignore fields in JSON. But how can i hide this one from my model and then give it to the client.
Do I make a mistake in using Room in the first place?
public class Participant {
#PrimaryKey
private long id;
#ColumnInfo(name = "order_id")
private long orderId;
private long threadId;
private String name;
private String firstName;
private String lastName;
For example :
i have a listener that is like the below
listener.add(participant);
i want to hide orderId first and then pass it to the listener.
Then in another class override this:
#Override
public void onAdd(Paticipant participant) {
super.onAdd(participant);
//here
}
One way to hide orderId from classes which use Participant, is to provide a getter for this variable and return null:
public Long getOrderId() {
return null;
}
We must change orderId to a Long in order for it to be set as null.
Additionally, you can override the toString() method to ignore orderId in any string representations of the class.
Use GSON library and create a new class for JSON model, without orderId:
class ParticipantJson {
final long id;
final long threadId;
final String name;
final String firstName;
final String lastName;
// Constructor
}
Then you can create JSON representation with:
ParticipantJson participant = new ParticipantJson(/* fields from Room model */);
Gson gson = new Gson();
String json = gson.toJson(participant);
USE A DIFFERENT MODEL FOR PRESENTATION!
Sorry for the caps but I cannot emphasize how important it is to use a different model for presentation.
Although you can hide fields from libraries like GSON or ROOM using keywords like transient or annotation like ignore you cannot hide a model attribute from class itself. Also remember that you cannot enforce a rule on a model that is not designed for the purpose.
TLDR; Create a new model and using a mapper map the Room model to this new presentation model.

Add Objects of different Types to ListAdapter

I am building an Android Application, and I need to display information from different Objects in my ListAdapter.
E.g. I need to show patientName from Patient, and roomNumber from Room etc.
All my Objects are serialized from JSON-response(s).
At first I thought about creating a wrapper class, just for displaying the information in my List - but it seems like a crappy solution.
Like so:
public class ListOverviewWrapper {
final String firstName;
final String lastName;
final int roomNumber;
final String departmentName;
...
}
I can't seem to figure out, how to do this effectively. Any suggestions?

is there anyway i can have listarray<string,int,int> in android?

is there anyway i can have multi dimensional array ex: listarray string,int,int in android??
it is quite possible with Map & Set in Java/C++.
Make your own container with fields good explaining its purpose:
class PersonData {
public int age;
public int id;
public String name }
And make list of it:
List<PersonData> dataList = new ArrayList<PersonData>();
Acces your fields by:
dataList.get(5).age = 11;
As Egor said in comment, a good practice will be set those field as protected and create setters and getters, if you don't need extreme performance in this specific case.

sorting custom object array on two fields

I'm sorting an array of custom objects (ListData[]) on two fields. I want it to be sorted by theme, and them by name. I thought i made a nice comparator in the custom object class and that i could use Arrays.sort(ld) to make my code working and sorting my array. But apparently im doing something wrong...
my custom object:
public class ListData implements Comparable<ListData>{
public int venueID;
public String name;
public String photoUrl;
public String tip;
public String theme;
#Override
public int compareTo(ListData ld0) {
return this.venueID- ld0.venueID;
}
public static Comparator<ListData> ListDataThemeAndNameComparator = new Comparator<ListData>() {
#Override
public int compare(ListData ld1, ListData ld2) {
String compareTheme1 = ld1.theme.toUpperCase();
String compareTheme2= ld2.theme.toUpperCase();
String compareName1 = ld1.name.toUpperCase();
String compareName2= ld2.name.toUpperCase();
//ascending
int comp = compareTheme1.compareTo(compareTheme2); // comp themes
if(comp==0){ // same theme
comp= compareName1.compareTo(compareName2); // compare names
}
return comp;
}
};
}
And in my main activity i have:
ListData ld[]= new ListData[jsonResponse.size()];
(some code filling my ListData array)
Arrays.sort(ld, ListData.ListDataThemeAndNameComparator); // compare by theme and then by name
Does anyone know what i'm doing wrong?
I edited my code But still it fails, now on a nullpointerexception on the compareTheme1 = ld1.theme.toUpperCase();. But i am sure my array is not empty, i logged it the line before sorting it and its filled with about 500 items.
Your ListData object should implements Comparable not Comparator interface.
EDIT:
To make things clear, you can sort an array by Array.sort(). To make custom sort, you can specify your comparator in Array.sort(), if you don't do that, array will be sorted in natural order which you can define by implementing Comparable interface. So you have two options how to custom sort:
by using custom comparator and specifying it in Array.sort()
by implementing Comparable interface to your items
I would suggest you to go with implementing Comparable. You save memory by not creating new comparator objects and Comparator is useful if you are comparing objects of different types which is not your case.

How can i improve my app

I have an app which present some beaches to the users.there is a list view with the name of every beach and when the user press on a name it opens a new activity with a photo and some text.i have created a .java class for every beach( same copy-paste code ) and a common .xml file. is there any better way to do it?for example to have all the beaches and their text in a db?
why don't you just instance the same class but with different parameters in the constructor?
Something like this:
public class Beach{
protected String name;
protected String pathImage;
public Beach(String name, String pathImage){
this.name = name;
this.pathImage = pathImage;
}
}
//Somewhere else in your application...
Beach beach1 = new Beach("Cancun","/images/cancun.png");
Beach beach2 = new Beach("Miami","/images/miami.png");
I would store the beach information in a SQLlite database, then just create a single Beach view that knows how to display the information from the database. A problem with this is that you might want to build a simple tool to allow you to manage the information in the database so you don't have to do it through queries on the command line.
You could ofcourse create a (abstract) superclass Beach.java and let other beaches extend that class. That way, you've got less redundant code.
public abstract class Beach{
protected String name;
public Beach(String name){
this.name = name;
}
public abstract String getOtherInfo();
}
public class FirstBeach extends Beach{
public FirstBeach(){
super("FirstBeach");
}
public String getOtherInfo(){
return "someInfo";
}
}

Categories

Resources