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";
}
}
Related
On Android, I try to retrieve some specific fields form a contact but I cant find how to do it.
I'd like to retrieve the following fields: "Enterprise", "Function", and "Label" and of course the fields "Name", "First Name" and "Phone number(s)"
The fields are here on a contact (numbered 1,2 and 3 on the screenshots):
Screen 1
Screen 2
Is there some sample functions already available ????
Just to know how to get those fields. I'm not a java expert...
I think you should use a Model with getter and setter methods. Than you can access all the fields with calling getter method.
Note: You have to save your data first.
Demo:
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
I need to have a relatively large number of categories defined (about 30 at start, we'll be adding more). Consider this code:
public class Category {
public static final Category DRESS = new Category("Dress");
public static final Category SKIRT = new Category("Skirt");
...
private static final List<Category> CATEGORIES = Arrays.aslist(DRESS, SKIRT, ...);
private String name;
public Category(String name) {
this.name = name;
}
//Some static public method to iterate over categories
...
I need to have the categories declared and also need a way to iterate over them. I discard reflection because I think it's not a very good practice.
Is declaring a large name of static final fields of the same class and also having them inside a list a good practice? As an alternative, I thought about having a Map<Integer, Category> instead the list, and the fields were integers that would identify each category, so you would get the categories by getting them inside the map. Would this be better in terms of time and space performance?
PS: It's for an android project, if it changes something
Consider this code:
public class Category {
public static final Category DRESS = new Category("Dress");
public static final Category SKIRT = new Category("Skirt");
Yeah this is literally what enums do in the background, so
public enum Category {
DRESS("Dress"),
SKIRT("Skirt"),
...;
private String name;
private Category(String name) {
this.name = name;
}
// Category.values() returns the elements as an array
You should use enum instead of creating an object with new Category("Dress"); because creating an object is expensive than using enum. Java enums are implemented more like classes, so you can change your code seamlessly:
public enum Category {
DRESS("Dress"), SKIRT("Skirt");
private final String name;
Category(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Note:
The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
Read more about enum at Enum Types
I would say using a List is good enough.
You should consider a Map only if you have to look up a
particular Category very frequently via some key property (like an int your case).
If There are no properties or methods in the Category class consider replace them with just Strings.
If new Categories are created at runtime and you want to persist them consider using a DB or File to save the Categories.
Edit: Answering the question in the comment
That would depend on the Category class. If its only purpose is to enumerate all the categories and the class itself does not have any other instance methods or properties then in terms of space complexity an Integer and your Category class is similar (since in a Map integer will be boxed in the Integer class object)
I would still suggest that you use a class called Category and a list if the purpose is only iterating over them and/or using specific instances of the Category class elsewhere in your application eg. Category.SOME_CATEGORY.
The following example is a good use-case
someMethod(Category category) {
// do something
}
versus
someMethod(int category) {
// before doing anything
// lookup this category by an int key
// in the the Map<Integer, Category>
}
The problem with the latter is that you could pass any int which may or may not be a valid key for a category. Using a class gives some bit for extra compile time check. Though you could always use an int def too. But again I would repeat that it all boils down to whether Category class has any instance methods or properties.
For small list, it is okay to use List or Map.
But for a large list, you may want to store them in a database.
Also ArrayList of String will be slightly efficient than using ArrayList of Category
I am currently working on an app that uses Firebase's real-time database and data binding for displaying. To keep it simple, here's a simple version of the problem:
Given a model class:
public class User {
private String name;
private Date date;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Date getDate() { return date; }
public void setDate(Date date) { this.date = date; }
}
And a ViewModel class for the users:
public class UserViewModel {
private User user;
public void setUser(User user) {
this.user = user;
}
public String getName() { return user.getName() }
public void setName(String name) { user.setName(name); }
public String getDateAsString() { // ... }
}
Now, in the activity/fragment I have a RecyclerView rendering a list of users. So within the adapter's onCreateViewHolder() I inflate a layout using DataBindingUtils, create a new ViewHolder and a new UserViewModel instance which accesses the UI. In onBindViewHolder() the UserViewModel gets assigned with the according User instance.
So far, so good: Given a list of users, its items get rendered into the RecyclerView through the UserViewModel.
For the app, I also use Firebase to read and write to the Realtime database. So when I now get a callback that a User entry has been updated, I directly modify the infos in the according instance.
So now to the question: How do I inform the UserViewModel that the data has changed and that it needs to redraw the according views in the UI?
I know one step I need to do is to have UserViewModel extend BaseObservable, mark the methods with #Bindable and add calls to notifyPropertyChanged(int) in the setters of the ViewModel. But this doesn't solve the problem of how to inform the UserViewModel of an update to the model data.
Any help and example code is appreciated! Thx! :)
You don't need to extend UserViewModel with BaseObservable, but you can. I'll show another way how you can achieve this.
Personally, I prefer to create a ObservableField<User> in my UserViewModel, create getters and setters like:
private final ObservableField<User> userField = new ObservableField<User>();
public UserViewModel(User user){
userField.set(user);
}
public ObservableField<User> getUser(){
return userField;
}
pass it to the layout and reference the properties like this:
<variable
name="userViewModel"
type="your.package.UserViewModel" />
<EditText
android:text"#={userViewModel.user.name}" />
Whenever your user changes his Name in your EditText, the changes are also updated in your model. (Using two-way databinding with #={})
Updated to use the ObservableField, thanks for the heads up, #tynn. Correct me, if I'm still wrong.
If I understand you correctly, you can take a look at using RxJava/RxAndroid to subscribe your viewModel to changes in the model class or the firebase instance (they should be observable). So for example, as you want to let the viewModel know that the firebase has a new user and that a user entry has been updated, you can call the viewModels onNext method from that callback, which will notify the viewModel subscribed to it, and run the method you want to run (like fetching the data), then with base observable you can then notify your list.
I have a ListView, actually generated by parsing a XML file downloaded from Internet.
This XML file contains data about a person: IdNumber, Name, Age, PhotoURL, Birthday, Phone numbers, Email account, etc.
I get all the XML data when generating the ListView, but on each row I show some values of the person (not all), just name, age, photo (from the PhotoURL) and email.
I would like to get the "IdNumber" to parse it to the Activity that shows all the info, this activity should read the "IdNumber", get all the data of only that person and show it.
How can I parse a value that I'm not using on my ListView?
Thanks in advance,
Herni
For each row in the listView create an Object with all the fields you've originally parsed.
You will create a model that like this:
public class Person
{
String idNumber,Name,Email;
public void SetIdNumber(String p_value)
{
this.idNumber = p_value;
}
public void SetName(String p_value)
{
this.Name= p_value;
}
public void SetEmail(String p_value)
{
this.Email= p_value;
}
//Get Methods
public String GetIdNumber()
{
return idNumber;
}
public String GetName()
{
return Name;
}
public String GetEmail()
{
return Email;
}
When you parse your xml you will create an ArrayList list; and fill after the 'list' you will use this everywhere you want.
For example when you click your first item of your listview you could ;
Person p = list.get(position that clicked your listview);
Now you will use your Person model. This is simple object oriant man.
How can i read the categories education and work in a android ListView? Now on clicking any category its childs Google,IBM,etc. are shown in a new screen. How can it be implemented?
You have to follow the following steps to get your work done
Step-1 You need to parse the xml. see http://xmlpull.org/v1/src/java/samples/MyXmlPullApp.java
Step-2 Create a bean class for Category. means all the category related data will be stored in that bean class
Step-3 Create an arraylist of that bean class
Step-4 Create a list view using that arraylist ( the list view will display only name of categories)
Step-5 Implement on itemclik listener on the list view. get the position. retrieve the data pass to the intent call second activity
Step-6 In the second activity create a listview and display the data whatever is passed by first activity
NetworkBean
public class NetWorkBean {
String name;
int id;
NetWorkBean(String name, int id){
this.name = name;
this.id = id;
}
public String getNetWorkName(){
return name;
}
public int getNetWorkId(){
return id;
}
}
CategoryBean
import java.util.ArrayList;
public class CategoryBean {
String name;
ArrayList<NetWorkBean> networkList;
public CategoryBean(String name, ArrayList<NetWorkBean> networkList){
this.name = name;
this.networkList = networkList;
}
public String getNetWorkName(){
return name;
}
public ArrayList<NetWorkBean> getNetWorkList(){
return networkList;
}
}
you can see this
http://www.androidpeople.com/android-xml-parsing-tutorial-%E2%80%93-using-domparser
After parsing the data set it to the list view.Then in the list onclick event implement
what you need.You can call an another activity and sending the corresponding address in a
bundle then retrieving that on the activity you can show in webview