Room TypeConverter and search in the table line
-
Please tell me I'm out of control, I don't know what I'm doing.
There's an enveloper:
public class MapConverter { @TypeConverter public String getStringFromMap(Map<Integer, String> map) { if(map!= null) { StringBuilder mapAsString = new StringBuilder(); for (Integer key : map.keySet()) { mapAsString.append(key + "=" + map.get(key) + ","); } return mapAsString.toString(); } else{ return null; } }
@TypeConverter public Map<Integer, String> getMapFromString(String s) { Map<Integer, String> myMap = new HashMap<Integer, String>(); String[] pairs = s.split(","); // 1 элемент - 0=Элемент 0 for (int i = 0; i < pairs.length; i++) { String pair = pairs[i]; String[] keyValue = pair.split("="); myMap.put(Integer.parseInt(keyValue[0]), keyValue[1]); } return myMap; }
}
Class of object:
@Entity(tableName = "contacts")
public class Contact {
@PrimaryKey(autoGenerate = true)private int id; private String name; private String number; private String group; private String subgroup; private String description; private int priority; @TypeConverters(MapConverter.class) private Map<Integer, String> mapOfGroup; @TypeConverters(MapConverter.class) private Map<Integer, String> mapOfSubGroup;
Method DAO
@Query("SELECT * FROM contacts WHERE mapOfGroup LIKE '%' || :nameGroup || '%' ")
Flowable<List<Contact>> getAllContactsOfGroup(String nameGroup);
Nothing comes back. As soon as I haven't tried it. I did.
LIKE :nameGroup || '%'
In addition to the table adding:
Although the converter has not yet added a line to the method
getStringFromMap
:} else{
return null;
}
The data were not added and made a mistake.
I see that line in an attempt to obtain data:2021-11-10 23:05:53.782 21564-21564/com.example.contacts D/Throwable get Contacts of Group: Attempt to invoke virtual method 'java.lang.String[] java.lang.String.split(java.lang.String)' on a null object reference
Help me figure this out, please. Thank you.
UPDATE:
I found a mistake when I put it in the converter, I changed it, but I still can't get the data.
New converter:@TypeConverter
public String getStringFromMap(Map<Integer, String> map) {
StringBuilder mapAsString = new StringBuilder();
int sizeMap = map.size()-1;
int counter = 0;
for (Integer key : map.keySet()) {
if(counter == sizeMap){
mapAsString.append(key + "=" + map.get(key));
} else {
mapAsString.append(key + "=" + map.get(key) + ",");
}
counter++;
}
return mapAsString.toString();
}
The error comes when:
D/Throwable get Contacts of Group: Index: 0, Size: 0
-
In general, it: The problem was in class.
Contact
Second fieldprivate Map<Integer, String> mapOfSubGroup;
Also indicated@TypeConverters
But at the same time, this field has not been transferred.Map
♪ That's why the converter was called twice, the first time he and the field made a mistake,Map null
The Query request itself works as follows:
'%' || :nameGroup || '%'
and'%' or :nameGroup or '%' ")