From 8acfaf4161854279b2027ec95fb72a6bcabba8ef Mon Sep 17 00:00:00 2001 From: Wan Ching Date: Fri, 14 Jul 2017 00:47:50 +0800 Subject: [PATCH] changed public data field to private data field --- .../customadapterdemo/CustomUsersAdapter.java | 13 ++++++++----- .../codepath/example/customadapterdemo/User.java | 16 ++++++++++++++-- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/codepath/example/customadapterdemo/CustomUsersAdapter.java b/app/src/main/java/com/codepath/example/customadapterdemo/CustomUsersAdapter.java index e29b938..053f42a 100644 --- a/app/src/main/java/com/codepath/example/customadapterdemo/CustomUsersAdapter.java +++ b/app/src/main/java/com/codepath/example/customadapterdemo/CustomUsersAdapter.java @@ -16,18 +16,21 @@ public CustomUsersAdapter(Context context, ArrayList users) { @Override public View getView(int position, View convertView, ViewGroup parent) { - // Get the data item for this position - User user = getItem(position); + // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false); } - // Lookup view for data population + + // Get the data item for this position + User user = getItem(position); + + // Lookup view for data population TextView tvName = (TextView) convertView.findViewById(R.id.tvName); TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown); // Populate the data into the template view using the data object - tvName.setText(user.name); - tvHome.setText(user.hometown); + tvName.setText(user.getName()); + tvHome.setText(user.getHometown()); // Return the completed view to render on screen return convertView; } diff --git a/app/src/main/java/com/codepath/example/customadapterdemo/User.java b/app/src/main/java/com/codepath/example/customadapterdemo/User.java index 8a6fbdd..175a8ef 100644 --- a/app/src/main/java/com/codepath/example/customadapterdemo/User.java +++ b/app/src/main/java/com/codepath/example/customadapterdemo/User.java @@ -3,14 +3,26 @@ import java.util.ArrayList; public class User { - public String name; - public String hometown; + + //declare private data instead of public to ensure the privacy of data field of each class + private String name; + private String hometown; public User(String name, String hometown) { this.name = name; this.hometown = hometown; } + //retrieve user's name + public String getName(){ + return name; + } + + //retrieve users' hometown + public String getHometown(){ + return hometown; + } + public static ArrayList getUsers() { ArrayList users = new ArrayList(); users.add(new User("Harry", "San Diego"));