Using Strings from resources in List. - java

I'm new to Android and I'm having a problem using String variables from resources in my code. I tried a couple of solutions found on the internet and Android API Guides, but they didn't work in this specific case, could also be me not using them correctly.
To be more specific, I have a Master/Detail flow activity and I would like to use resource strings as item names for multilanguage purposes, but I have a problem with recovering actual strings.
The error I get is:
Cannot resolve method 'getString()'
Here is my code based on android studio dummy file
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
static {
String temp = getString(R.string.cat_n1);
addItem(new CatName("1", temp);
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public FieldCat(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}

You need to specify the resource. Try this,
getResources().getString(R.string.cat_n1);
getString(int resId): Return a localized string from the application's package's default string table.
getResources().getString(int id): Returns the string value associated with a particular resource ID. It will be stripped of any styled text information.

Try using it with a constructor passing the context and calling getstring on that
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
public Categories(Context ct)
{
String temp = ct.getString(R.string.abc_action_bar_home_description);
addItem(new CatName("1", temp));
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public CatName(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}

Related

Deserialize an object's property which has an inconsistent name?

Using Retrofit here to consume Google Civic API.
The library requires you to create a model of what the API will return as I have done already with Election. Which is basically a copy of the google documentation.
(Retrofit binds the response properties to properties with the same name)
Election.Java :
public class Election {
private long id;
private String name;
private String electionDay;
private String ocdDivisionId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getElectionDay() {
return electionDay;
}
public void setElectionDay(String electionDay) {
this.electionDay = electionDay;
}
public String getOcdDivisionId() {
return ocdDivisionId;
}
public void setOcdDivisionId(String ocdDivisionId) {
this.ocdDivisionId = ocdDivisionId;
}
}
But Representatives have an inconsistent property name, thus I don't see a way to model this in a way Retrofit will know how to deserialize the API's response.
Representatives object (JSON) :
property name is called (key)
How do I let Retrofit deserialize a model that captures the property named variable after a key of the division?
Assuming you're using a Gson converter, I personally would use a map. I guess the same can be achieved with other converters, but I never used them. Say you have the following object:
public class Division {
#SerializedName("name")
#Expose
private String name;
#SerializedName("alsoKnownAs")
#Expose
private List<String> alsoKnownAs = new ArrayList<>();
#SerializedName("officeIndices")
#Expose
private List<Integer> officeIndices = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAlsoKnownAs() {
return alsoKnownAs;
}
public void setAlsoKnownAs(List<String> alsoKnownAs) {
this.alsoKnownAs = alsoKnownAs;
}
public List<Integer> getOfficeIndices() {
return officeIndices;
}
public void setOfficeIndices(List<Integer> officeIndices) {
this.officeIndices = officeIndices;
}
}
Which represents the object inside the divisions array. You can then have the class:
private class Divisions {
#SerializedName("divisions")
#Expose
private Map<String, Division> divisions = new HashMap<>();
// ...
}
Notice the usage of a map here? Behind the scenes Gson will be able to serialise and deserialise your objects. The class Divisions is the root of the json you gave us in the question.
Hope this helps

Android ArrayList: check an element exists of another ArrayList

I have two ArrayList.
private ArrayList<Friend> friendsList = new ArrayList<Friend>();
private ArrayList<Friend> myFriendsList = new ArrayList<Friend>();
First one contains all Friend of database. Second one contains only user Friend. In my search option(SearchManager) i've a ListView contains searched friends of friendsList. When i select a Friend of ListView, i want to check if the Friend exists in myFriendsList. I used following code
friendListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
handelListItemClick(adapter.getItem(position));
}
});
private void handelListItemClick(Friend friend) {
for(Friend fr: myFriendsList){
Log.v("Check User Name:", fr.getName());
}
if (myFriendsList.contains(friend)) {works with matched friend}
But it can't check the selected Friend in myFriendsList. In LogCat it show myFriendsList information. Thanks in advance.
Update
Here is my Friend class
public class Friend {
private String id, name, thumbnailUrl;
public Friend() {
}
public Friend(String name, String thumbnailUrl) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
}
public Friend(String name, String thumbnailUrl, String id) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
this.id = id;
}
public String getID(){
return id;
}
public void setID(String id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
To be able to use methods to find and search like contains your custom class MUST implement correctly the hasCode and equals methods.
Here is the link about the implementing hasCode and here about implementing equals. It is Java Best Practises website that I like very much and from where I've learned about it.
equals() is used in most collections to determine if a collection contains a given element
hashCode() of this object is calculated and used to determine where to search for the object in the hash tables.
For more information on either of these topics visit oracle webiste or take a look here
If You could decide that two Friend objects are equal to each other if just their id's are equal.
So , In your Friend Class include
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Friend)) return false;
Friend friend = (Friend) o;
if (!id.equals(friend.id)) return false;
return true;
}
#Override
public int hashCode() {
return id.hashCode();
}
Now just do,
private void handelListItemClick(Friend friend) {
if (myFriendsList.contains(friend)) {works with matched friend}
}
Edit
You can take a look at this tutorial to learn more about the topic

Cannot bind RemoteObject from BlazeDS

I'm using BlazeDS in Tomcat7 and Flex. I'm trying to use custom classes between the client and server.
In as:
package
{
[Bindable]
[RemoteClass(alias="remoting.Product")]
public class Product
{
public var name:String;
public var id:int;
public var isVisible:Boolean;
}
}
In Java:
package remoting;
public class Product {
public String name;
public int id;
public Boolean isVisible;
public Product(){
name = "Product 0.1";
id = 123;
isVisible = false;
}
public void setName(String _name){
name = _name;
}
public void setId(int _id){
id = _id;
}
public void setVisible(Boolean _isVisible){
isVisible = _isVisible;
}
}
Service part:
public Product echo() {
Product product = new Product();
product.setId(123);
product.setName("My Product");
product.setVisible(true);
return product;
}
I can successfully set the destination of the RemoteObject and call the echo() method. The result event fires up, with the Product object in event.result. However, it does not contain any sensible data. The variables from AS class just get initialized with null, 0 and true values. I'm wondering what's the problem. I tried returning a String with parameters from Product and it works fine, so they get set fine. The problem is in mapping.
I could go another way and implement Externalizable but I don't understand this part from the example:
name = (String)in.readObject();
properties = (Map)in.readObject();
price = in.readFloat();
What if there is a number of strings?
Cheers.
In java class: use private fields and implement getters.
package remoting;
public class Product {
private String name;
private int id;
private Boolean isVisible;
public Product() {
name = "Product 0.1";
id = 123;
isVisible = false;
}
public void setName(String _name){
name = _name;
}
public String getName(){
return name;
}
public void setId(int _id){
id = _id;
}
public int getId(){
return id;
}
public void setIsVisible(Boolean _isVisible){
isVisible = _isVisible;
}
public Boolean getIsVisible() {
return isVisible;
}
}
You could also switch from BlazeDS to GraniteDS: the latter has a powerful transparent externalization mechanism as well as code generation tools that can really save your time (see documentation here).

Printing the name of an object in Java

I have researched, and although this is a really simple issue, I am not sure how to solve it.
The code I have looks like this:
public class Playlist {
public Playlist(String name) {
}
}
Separate files of course:
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
}
I am trying to print the actual name of this new playlist "workout playlist" but I can't seem to find a way to do so.
You need to store the name of your playlist in an instance variable. For instance:
public class Playlist {
private final String name;
public Playlist(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then you can print it with:
System.out.println(myPlayList.getName());
If you want to make the name mutable, then get rid of the final modifier and add a setName(String) method.
write get method to name or override toString method in the class
public class Playlist {
private String name;
public Playlist (String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Playlist [name=" + name + "]";
}
}
Print the name using
System.out.println(playlistObject.getName());
or
System.out.println(playlistObject).
I would prefer setting a getter method over toString() though.
public class Playlist {
private String name;
public Playlist(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to show the name:
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
System.out.println(myPlaylist.getName());
}
You are not at all storing the 'name' property in your object. So obviously you can't access name. One way is
public class Playlist {
public String name;
public Playlist(String name) {
this.name = name;
}
}
Now you should be able to access your attribute from your testcase like this.
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
System.out.println(myPlaylist.name);
}

create a class to model a list

I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}

Categories