using acra, the following code does not compile with error
DEFAULT_REPORT_FIELDS cannot be resolved or is not a field
private Map<String, String> remap(Map<ReportField, String> report) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final Map<String, String> finalReport = new HashMap<String, String>(
report.size());
for (ReportField field : fields) {
if (mMapping == null || mMapping.get(field) == null) {
finalReport.put(field.toString(), report.get(field));
} else {
finalReport.put(mMapping.get(field), report.get(field));
}
}
return finalReport;
}
That must be for an old(er) version. Try this instead:
ACRAConstants.DEFAULT_REPORT_FIELDS
Related
Instantiation Exception in this code:
public static ObjType DeepCloneObject(ObjType Object) throws IllegalAccessException, InstantiationException {
Object Clone = Object.getClass().newInstance();
for (Field field : Object.getClass().getDeclaredFields()) {
field.setAccessible(true);
// Skip if filed is null or final
if(field.get(Object) == null || Modifier.isFinal(field.getModifiers())){
continue;
}
if(field.getType().isPrimitive() || field.getType().equals(String.class)
|| Objects.equals(field.getType().getSuperclass(), Number.class)
|| field.getType().equals(Boolean.class)){
field.set(Clone, field.get(Object));
}else{
Object childObj = field.get(Object);
if(childObj == Object){ // Self-reference check
field.set(Clone, Clone);
}else{
field.set(Clone, DeepCloneObject(field.get(Object)));
}
}
}
return (ObjType)Clone;
}
Usage:
public static DownloadTask CreateTaskFromFiles(ArrayList Indexes, DownloadTask OriginalTask) throws IllegalAccessException, InstantiationException {
// Warning: Slow algorithm
DownloadTask NewTask = Utils.DeepCloneObject(OriginalTask);
if (NewTask != null) {
NewTask.Files = new ArrayList<DownloadTaskFile>();
for (int i = 0; i < OriginalTask.Files.size(); ++i) {
if (!Indexes.contains(i)) {
NewTask.Files.remove(i);
}
}
}
return NewTask;
}
==============================================================
LogCat:
Failed to clone object - com.gamedevers.blackazerbaijan_sa_mp.core.SAMP.Components.DownloadSystem.DownloadTask
This was the closest question that I found but still not what I'm looking for.
I'm using google Firestore to save user information (number, sex, etc). I use a JSON custom object to save, but when I'm trying to get the information I'm not able to transform in JSON object again.
private void getUserData() {
ffDatabase.collection(Objects.requireNonNull(mAuth.getCurrentUser()).getUid()).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
JSONObject user = new JSONObject(task.getResult()
.toObjects(JSONObject.class).get(0));
DataStorageTemporary.getInstance().setJsonUser(user);
} else {
Log.w("ERROR load data", "Error getting documents.", task.getException());
}
}
});
}
I tried to get from Task(result) the JSON object, but it won't work:
task.getResult().toObjects(JSONObject.class).get(0)
I know that I can change QuerySnapshot to DocumentSnapshot, but I still no able to get the JSON Object from.
You would need to create a custom User Class and then write to firestore using that POJO as #Doug Stevenson says. see the following from the docs:
"Custom objects Using Java Map objects to represent your documents is often not very convenient, so Cloud Firestore also supports writing your own Java objects with custom classes. Cloud Firestore will internally convert the objects to supported data types."
Firestore doesn't store JSON. It stores key/value pairs with strongly typed values. When you read a document on Android, you have two choices to get a hold of those fields:
Automatically map the key/value pairs to a POJO that conforms to JavaBeans standards. JSONObject is not a valid JavaBean type object.
Access each key/value pair out of the document individually.
ApiFuture<QuerySnapshot> future = db.collection(collection).get();
List<QueryDocumentSnapshot> documents = future.get().getDocuments();
Iterate through the DocumentSnapshots and use recursion to create a JSONObject.
You can use getData() on DocumentSnapshot object to get a Map of your Firestore Document and then you can parse the object and create your own JSONObject.
for (DocumentSnapshot document : documents) {
JSONObject obj = mapToJSON(document.getData());
// Other stuff here ...
}
private JSONObject mapToJSON(Map<String, Object> map) {
JSONObject obj = new JSONObject();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
Map<String, Object> subMap = (Map<String, Object>) value;
obj.put(key, mapToJSON(subMap));
} else if (value instanceof List) {
obj.put(key, listToJSONArray((List) value));
}
else {
obj.put(key, value);
}
}
return obj;
}
private JSONArray listToJSONArray(List<Object> list) {
JSONArray arr = new JSONArray();
for(Object obj: list) {
if (obj instanceof Map) {
arr.add(mapToJSON((Map) obj));
}
else if(obj instanceof List) {
arr.add(listToJSONArray((List) obj));
}
else {
arr.add(obj);
}
}
return arr;
}
I took #atmandhol's solution as a starting point but used the JsonObjectBuilder. I also converted the chars-string-valueType structure of Firestore back to a single JsonStructure.
Use it as inspiration (not a full-proof solution). E.g. more valueTypes than "STRING" need to be added.
private JsonObject mapToJSON(Map<String, Object> map) {
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if ( isSingleElement(value) ) {
builder.add(key, getSingleValueAsString(((Map) value)));
} else if (value instanceof Map) {
Map<String, Object> subMap = (Map<String, Object>) value;
builder.add(key, mapToJSON(subMap));
} else if (value instanceof List) {
builder.add(key, listToJSONArray((List<Object>) value));
}
else {
builder.add(key, value.toString());
}
}
return builder.build();
}
private String getSingleValueAsString(Map value) {
if( value.get("valueType").equals("STRING") ) {
return value.get("string").toString();
}
return "";
}
private boolean isSingleElement(Object value) {
return ( value instanceof Map
&& ((Map) value).containsKey("valueType"));
}
private JsonArray listToJSONArray(List<Object> list) {
JsonArrayBuilder builder = Json.createArrayBuilder();
for(Object value: list) {
if ( isSingleElement(value) ) {
builder.add(getSingleValueAsString(((Map) value)));
} else if (value instanceof Map) {
builder.add(mapToJSON((Map<String, Object>) value));
}
else if(value instanceof List) {
builder.add(listToJSONArray((List<Object>) value));
}
else {
builder.add(value.toString());
}
}
return builder.build();
}
I am usign CouchBase lite 1.4 in Android.
I want to remove documents locally after a time, let´s says 15 minutes. I haven been reading that we can remove documents locally using the setExpirationDate() method
So what I am doing is:
public String createOrUpdateDocument(String jsonDocument) {
Document d = null;
String res = null;
HashMap<String, Object> map = (HashMap<String, Object>) GSONParser.getInstance()
.fromJson(jsonDocument, HashMap.class);
if (map.get("_id") != null) {
//update
try {
d = load((String) map.get("_id"));
} catch (Exception e) {
}
} else {
d = work.createDocument();
Date date = Calendar.getInstance().getTime();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MINUTE, 15);
Date expiration = c.getTime();
d.setExpirationDate(expiration);
}
if (d != null) {
try {
Revision r = d.putProperties(map);
map.put("_id", r.getDocument().getId());
map.put("_rev", r.getDocument().getCurrentRevisionId());
res = GSONParser.getInstance().toJson(map);
} catch (CouchbaseLiteException e) {}
}
return res;
}
In the other hand I have a list with all the documents I have so what I am doing in order to get a the list with all the documents is:
public static List<Object> getWorkDocumentListByTypeAndCompany(String type, Long idCompany){
if (idCompany == null){
return getWorkDocumentListByType(type);
}
List<Object> l = new ArrayList<Object>();
View byIdCompany = CouchbaseManager.getInstance().getWorkdocbytypecompany();
Query q = byIdCompany.createQuery();
q.setMapOnly(true);
q.setStartKey(Arrays.asList(type, idCompany));
q.setEndKey(Arrays.asList(type, idCompany));
try {
QueryEnumerator r = q.run();
for (Iterator<QueryRow> it = r; it.hasNext(); ) {
QueryRow row = it.next();
String jsonValue = GSONParser.getInstance().toJson(row.getValue());
l.add(getFromJSONValue(type, jsonValue));
}
}catch (Exception e){
e.printStackTrace();
}
return l;
}
where
.getWorkdocbytypecompany()
is:
workdocbytypecompany = work.getView("work_doc_bytypecompany");
workdocbytypecompany.setMap(new Mapper() {
#Override
public void map(Map<String, Object> document, Emitter emitter) {
if (!document.containsKey("ismaster") && document.containsKey("type") && document.containsKey("company")) {
List<Object> key = new ArrayList<Object>();
HashMap<String, Object> company = (HashMap<String, Object>)document.get("company");
Object idcompany = company.get("id");
key.add(document.get("type"));
key.add(idcompany == null ? null : new Double(idcompany.toString()).longValue());
emitter.emit(key, document);
}
}
},"1.2");
But it does not work, the document is not removed, no errors got, no info
What I am doing wrong?
I'm having a list where filling the values to list through looping as below.
List<String> labelGroupDataValue = null;
if (labelGroupData.size() != 0) {
for (HashMap<String, List<String>> LabelMap : labelGroupData) {
for (Map.Entry<String, List<String>> labelGroupDataEntry : LabelMap.entrySet()) {
if (labelGroupDataEntry.getKey() != null) {
String keyvalue = labelGroupDataEntry.getKey();
if (keyvalue.contains(key)) {
labelGroupDataValue = labelGroupDataEntry.getValue();
CheckIsCustomizings(labelGroupDataValue);
}
}
}
}
}
The problem i'm facing is labelGroupDataValue contains the data of only last looping.
Where i'm doing wrong, could you please help me in this regard.
Code for IsCustomizings:
private void CheckIsCustomizings(List> value) {
// Looping through the List to check whether Customizings syncGroup is present or not
for (int j = 0; j < value.size(); j++) {
if (value.get(j).equals("SALESDOCS")) {
value.set(j, "SALES_DOCUMENTS");
}
if (value.get(j).equalsIgnoreCase("TRADEASSETS")) {
value.set(j, "TRADE_ASSETS");
}
if (value.get(j).equalsIgnoreCase("PROMOTIONSCAMPAIGNS")) {
value.set(j, "PROMOTIONS_CAMPAIGNS");
}
String checkName = "CUSTOMIZINGS";
if (value.get(j).toLowerCase().contains(checkName.toLowerCase())) {
IsCustomizingPresent = true;
break;
}
}
// If Customizings syncGroup is not present, add the same to List for displaying to the user
if (!IsCustomizingPresent) {
value.add("CUSTOMIZING");
}
}
Here is how to correctly add to an existing list:
List<String> labelGroupDataValue = new ArrayList<>();
if (labelGroupData.size() != 0) {
... //omissis
labelGroupDataValue.addAll(labelGroupDataEntry.getValue());
CheckIsCustomizings(labelGroupDataValue);
...
}
The correctness of the rest of the code is up to you.
you need to initialize "labelGroupDataValue" inside the forloop,
what's happening now is there is only single memory is allocated to the list which get overwritten everytime in the loop, hence only the last value stays.
try the below code if it helps
List<String> labelGroupDataValue = null;
if (labelGroupData.size() != 0) {
for (HashMap<String, List<String>> LabelMap : labelGroupData) {
for (Map.Entry<String, List<String>> labelGroupDataEntry : LabelMap.entrySet()) {
if (labelGroupDataEntry.getKey() != null) {
String keyvalue = labelGroupDataEntry.getKey();
labelGroupDataValue = new ArrayList<>();
if (keyvalue.contains(key)) {
labelGroupDataValue = labelGroupDataEntry.getValue();
CheckIsCustomizings(labelGroupDataValue);
}
}
}
}
}
I am facing a problem creating a Json which is actually a complex one and i need to create it through HashMap only..I was actually looking for some recursive function that could be a best solution to my problem.
JSON i need to create looks like..
{"pkt":{
"data2":{"z":"3", "y":"2", "x":"1"},
"data3":{"n":"3", "l":"1", "m":"2"},
"mid":"1328779096525",
"data1":{"b":"2", "c":"3", "a":"1"},
"msg":"10012"
}
}
any ideas??
You'd do something like this:
public void toJSON(Map<?, ?> map, JSONStringer stringer) throws JSONException {
stringer.object();
for (Map.Entry<?, ?> entry : map.entrySet()) {
stringer.key(String.valueOf(entry.getKey()));
toJSONValue(entry.getValue(), stringer);
}
stringer.endObject();
}
public void toJSONValue(Object value, JSONStringer stringer) throws JSONException {
if (value == null) {
stringer.value(null);
} else if (value instanceof Collection) {
toJSON((Collection<?>) value, stringer);
} else if (value instanceof Map) {
toJSON((Map<?, ?>) value, stringer);
} else if (value.getClass().isArray()) {
if (value.getClass().getComponentType().isPrimitive()) {
stringer.array();
if (value instanceof byte[]) {
for (byte b : (byte[]) value) {
stringer.value(b);
}
} else if (value instanceof short[]) {
for (short s : (short[]) value) {
stringer.value(s);
}
} else if (value instanceof int[]) {
for (int i : (int[]) value) {
stringer.value(i);
}
} else if (value instanceof float[]) {
for (float f : (float[]) value) {
stringer.value(f);
}
} else if (value instanceof double[]) {
for (double d : (double[]) value) {
stringer.value(d);
}
} else if (value instanceof char[]) {
for (char c : (char[]) value) {
stringer.value(c);
}
} else if (value instanceof boolean[]) {
for (boolean b : (boolean[]) value) {
stringer.value(b);
}
}
stringer.endArray();
} else {
toJSON((Object[]) value, stringer);
}
} else {
stringer.value(value);
}
}
public void toJSON(Object[] array, JSONStringer stringer) throws JSONException {
stringer.array();
for (Object value : array) {
toJSONValue(value, stringer);
}
stringer.endArray();
}
public void toJSON(Collection<?> collection, JSONStringer stringer) throws JSONException {
stringer.array();
for (Object value : collection) {
toJSONValue(value, stringer);
}
stringer.endArray();
}
To construct the example you gave:
// Using a variety of maps since all should work..
HashMap<String, Object> pkt = new HashMap<String, Object>();
LinkedHashMap<String, String> data1 = new LinkedHashMap<String, String>();
data1.put("b", "2");
data1.put("c", "3");
data1.put("a", "1");
LinkedHashMap<String, String> data2 = new LinkedHashMap<String, String>();
data2.put("z", "3");
data2.put("y", "2");
data2.put("x", "1");
TreeMap<String, Object> data3 = new TreeMap<String, Object>();
data3.put("z", "3");
data3.put("y", "2");
data3.put("x", "1");
pkt.put("data2", data2);
pkt.put("data3", data3);
pkt.put("mid", "1328779096525");
pkt.put("data1", data1);
pkt.put("msg", "10012");
try {
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.key("pkt");
toJSON(pkt, stringer);
stringer.endObject();
System.out.println(stringer.toString());
} catch (JSONException e) {
// Time for some error-handling
}
Which would result in (formatted for viewing):
{
"pkt":{
"data2":{
"z":"3",
"y":"2",
"x":"1"
},
"mid":"1328779096525",
"data3":{
"x":"1",
"y":"2",
"z":"3"
},
"msg":"10012",
"data1":{
"b":"2",
"c":"3",
"a":"1"
}
}
}
We're using GSON for our object/JSON conversions. Here's a link for more info: GSON