Compare object to object from hash map in android - android

I have HashMap<Shop, String> shopMap where I put two values:
shopMap(shopModel1, shopModel1.getName());
shopMap(shopModel2, shopModel2.getName());
In my method for search shop by name I passed object of shop identical like shopModel1 to get his name:
public String getNameForShop(Shop filter) {
return shopMap.get(filter);
}
but I get null. Objects have the same all values. There is any way to get shop name from hash map using object?

It is not ok to have the object as key value. Map it by name.
I guess mapping by object, in fact, it happens with the object's memory address. Then you search in map for an object it doesn't compare objects fields, just the addresses.
HashMap<String, Shop> shopMap;
if( shopMap.get("shopname").equals(anotherShop) ){
//do staff
}

Related

Firebase Database change node ID

How can I change the naming of the nodes of my children in the image below?
questions_stats is a List<Integer>, I'm aware that I get integers as nodes Id because this is a List. I create each of the children randomly with a number between 0 and 1000. I set this ID as part of the object and to find it I loop trough the list. What I want is to set the "0671" as the Key of the Object at the moment I create it.
How should I define my object in order to access each child with an Id that I define as a String.
Each of the questions_stats is an object.
This is my UserProfile Class definition.
public class UserProfile implements Parcelable {
private List<Integer> questions_list;
private List<QuestionsStats> questions_stats;
private String country_name, share_code, user_name;
private int token_count;
private Boolean is_guest;
public UserProfile() {
}
public UserProfile(List<Integer> questions_list, List<QuestionsStats> questions_stats, String country_name, String share_code, String user_name, int token_count, Boolean is_guest) {
this.questions_list = questions_list;
this.questions_stats = questions_stats;
this.country_name = country_name;
this.share_code = share_code;
this.user_name = user_name;
this.token_count = token_count;
this.is_guest = is_guest;
}
}
I know I can set them using the child("0159").setValue(QuestionStats) individually.
But for my purpose I need to retrieve the data of the "user" as a whole and then iterate whithin questions_stats like it is a List.
How should I define my UserProfile class in order to achieve what I want?
Anybody could give me a hint?
How can I change the node names of my children in the image below?
Answer: There is no way in which you can change the names of the nodes from your Firebase database. There is no API for doing that. What can you do instead is to attach a listener on that node and get the dataSnapshot object. Having that data, you can write it in another place using other names. You cannot simply rename them from 0 to 0000, 1 to 0001 and so on.
Perhaps I should have asked for How to "Set" the node Id instead of "Change"
What I have is an List<QuestionsStats>, but when using an List<QuestionsStats> you get indexes as Keys, What I want is to have the same List<QuestionsStats> but instead of indexes, String Keys for each of my items.
So I changed my List for a Map<String, QuestionsStats>. Now the tricky part is when parceling the Object. You can use readMap() or writeMap() to parcel as shown here in this answer by #David Wasser, but it gives a warning:
Please use writeBundle(Bundle) instead. Flattens a Map into the parcel
at the current dataPosition(), growing dataCapacity() if needed. The
Map keys must be String objects. The Map values are written using
writeValue(Object) and must follow the specification there. It is
strongly recommended to use writeBundle(Bundle) instead of this
method, since the Bundle class provides a type-safe API that allows
you to avoid mysterious type errors at the point of marshalling.
So with the help of the comments in This Question I parceled using this code, note that I'm leaving the "easy" way commented in case somebody find it useful or have any comment on that :
protected UserProfile(Parcel in) {
// in.readMap(myMap, Object.class.getClassLoader());
myMap = new HashMap<>();
String[] array = in.createStringArray();
Bundle bundle = in.readBundle(Object.class.getClassLoader());
for (String s : array) {
myMap.put(s, (Object) bundle.getParcelable(s));
}
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// dest.writeMap(myMap);
Bundle bundle = new Bundle();
for (Map.Entry<String, Object> entry : myMap.entrySet()) {
bundle.putParcelable(entry.getKey(), entry.getValue());
}
Set<String> keySet = myMap.keySet();
String[] array = keySet.toArray(new String[keySet.size()]);
dest.writeStringArray(array);
dest.writeBundle(bundle);
}
Why I want this, well at the moment my list contains less than 100 items but it could grow up to a 1000, I'm no Pro, but I believe that if I already know the key of the item I'm interested in will be always better than having to iterate over the list to find it. In the end my main problem was the usage of a Map, I did not know howto.

How can I get the value in android sugar, I'm only getting the object reference

I'm using for first time sugar and all seems that work fine. I can save the data and seems that I'm getting the data when I try to do a find. My problem is that I'm getting the object and not the value that I have store and I'm not really sure why, because I'm doing the same that I can see in the official documentation
This is that I'm doing to get the data:
Select name= Select.from(MyClass.class).where(Condition.prop("name").lt("Bob"));
String data = name.toString();
Log.e("aaaaa", data.toString());
This is that I'm gettin in the log:
com.orm.query.Select#3ce7ff7b
With that Select statement, you are querying for the MyClass object by name, and that returns you a Select object.
To get the name from it you should fetch results from the Select (here I do it with .first()) and put that in a MyClass object. Then you can get the name from that.
MyClass myClass = Select.from(MyClass.class)
.where(Condition.prop("name").lt("Bob"))
.first();
String name = myClass.getName();
provided your MyClass has a method getName()
I'm doing the same that I can see in the official documentation
I don't thnk you are.
In the documentation here, it shows this piece of code:
Select.from(TestRecord.class)
.where(Condition.prop("test").eq("satya"),
Condition.prop("prop").eq(2))
.list();
When you compare it with your code, you see that you missed the call to list.
If you don't call list, the where method will return a Select object. And that's all you get.
list will return all of the results that the query has found. So the correct way to do this would be:
List<MyClass> results =
Select.from(MyClass.class).
where(Condition.prop("name").
lt("Bob")).list();
for (MyClass obj: results) {
Log.i("aaaa", obj.toString());
// or you can write
// Log.i("aaaa", obj.name);
}
The above would print all the results. If you only need the first result, you can call results.get(0).

store two string and one integer in shared preference using hashmap

I want to store three values in shared preference
Can I store integer as third value in hashmap? As i passed null for string, what can i passed for integer?
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_PASS, pref.getString(KEY_PASS, null));
user.put(KEY_ID,pref.getInt(KEY_ID,));//what should i pass here??
// return user
return user;
}
you've declared your HashMap() as a map that contains String objects, so, no, you can't really just store an integer in there. However, you can convert the integer to a string if you like. Since getInt() returns a primitive int, you should use the static method Integer.toString(valuetomakeintoastring)
The second value in your call to getInt() is the default value that should be returned if the KEY value is not found in the preferences. Use some value that can't be confused as a valid value for your application.
user.put(KEY_ID,Integer.toString(pref.getInt(KEY_ID,<somedefaultintegervalue>));
Perhaps a HashMap is not the right data structure for you to use here? Perhaps you really need to define a class that contains these values together, then create a HashMap of that class?

ParseObject.put method saving strings etc as arrays? Is this a bug?

I try to save simple Object attibutes using the .put("name", data) method
ParseObject parseLibraryItem = new ParseObject("UserLibrary");
parseLibraryItem.add("movieId", 121);
parseLibraryItem.add("runtime", 134);
parseLibraryItem.add("status", "released");
parseLibraryItem.add("name", "TestParseMovie");
parseLibraryItem.add("releaseDate", "2014-11-06");
parseLibraryItem.add("imagePath", "/7k9db7pJyTaVbz3G4eshGltivR1.jpg");
parseLibraryItem.add("description", "This is just a test");
parseLibraryItem.add("tagline", "The craziest movie ever");
parseLibraryItem.add("createdBy", ParseUser.getCurrentUser());
parseLibraryItem.setACL(new ParseACL(ParseUser.getCurrentUser()));
parseLibraryItem.saveInBackground();
Here is the Parse backend
When I try to query the Object I have to then strip the returned string of the Brackets. What am I doing wrong here?
Instead of using the method add(String key, Object value), which atomically adds an object to the end of the array associated with a given key, try using the method put(String key, Object value), which adds a key-value pair to this object.
source : Android Parse API https://parse.com/docs/android/api/

Ormlite RawRowMapper truncated double

I am using RawRowMapper to load relevant columns from ormlite. RawRowMapper returns all data as String.
The observation is that it truncates the double value.
Example:
Data inserted -> 57.1117146374
Data type used to store the data -> Double
Data from Ormlite when directly queried: -> 57.1117146374 (This is correct and essentially means that ormlite is actually storing the data correctly)
Data from Ormlite when using mapper -> 57.1117 (Truncated data coming as part of String[] resultColumns
Any idea how do I avoid it getting truncated?
EDIT:
#DatabaseField(columnName = "LAT")
private Double lat;
Object Field:
private double lat;
The key here is that the string in resultcolumns[], I get is already truncated.
Data from Ormlite when using mapper -> 57.1117 (Truncated data coming as part of String[] resultColumns
The problem seems to be that getting a double value out as a String is truncated by Android's cursor.getString(...) method. Not sure why but if the result is extracted by using cursor.getDouble(columnIndex); on the same column-index, the full precision is preserved.
The solution here I believe is to map the rows differently. If you use dao.queryRaw(String, DataType[], ...) method, the double field seems to be extracted appropriately. Here's a sample from my test class.
GenericRawResults<Object[]> results =
dao.queryRaw(dao.queryBuilder().selectColumns("lat")
.prepareStatementString(), new DataType[] { DataType.DOUBLE });
CloseableIterator<Object[]> iterator = results.closeableIterator();
try {
assertTrue(iterator.hasNext());
Object[] objs = iterator.next();
assertEquals(foo.doubleField, objs[0]);
} finally {
iterator.close();
}
You could also use a custom row mapper and the dao.queryRaw(String, RawRowMapper, ...) method to convert and return a custom object with a double field.

Categories

Resources