How to add hash containing list in multipart entity? - android

I need my HTTP params should be
Parameters: {"MainHash"=>{"MyArray"=>[one,two,three]}}
For that I have tried
Try (1)
for (String item : array_items) {
entity.addPart("MainHash[MyArray[]]", new StringBody(item));
}
Result
Parameters: {"MainHash"=>{"MyArray"=>[nil,nil,nil]}} //nil for each item
Try (2)
entity.addPart("MainHash[MyArray[]]", new StringBody("["+items_string+"]"));
Result
Parameters: {"MainHash"=>{"MyArray"=>"[one,two,three]"}} //quotes added to array
When I tried it with list with out hash it is working.
But I need to append list inside hash.
Any suggestions on the same are highly appreciated.

I believe you want your MainHash with same key in MainArray.
So, you can try,
for (String item : array_items) {
entity.addPart("MainHash[MyArray][]", new StringBody(item));
}
It will create,
[one,two,three]
as an array.

Related

ArrayList in HashMap kotlin

How to add some value in ArrayList which is inside of HashMap? My bellow code showing 0 sizes of the hash
val hash= HashMap<String, ArrayList<String> >()
hash["bro"]?.add("Ali Umar")
hash["sis"]?.add("Tamanna")
hash["bro"]?.add("Faruk")
hash["sis"]?.add("Aklima")
hash["bro"]?.add("Ab Siddik")
Log.d("Hash", hash.size.toString())
You have to initialize a List and put the key and that initialized List into the HashMap before you can add any more items to the value of a key. In your example code nothing is put into the HashMap and nothing can be added.
Try it like this (or similar)
fun main() {
// initialize the hashmap
val hash = hashMapOf<String, MutableList<String>>()
// put the keys with empty lists into the hashmap
hash.put("bro", mutableListOf())
hash.put("sis", mutableListOf())
// add items to the value (the list) of existing keys
hash.get("bro")?.add("Ali Umar")
hash.get("sis")?.add("Tamanna")
hash.get("bro")?.add("Faruk")
hash.get("sis")?.add("Aklima")
hash.get("bro")?.add("Ab Siddik")
// print size and content
println("Hash size is ${hash.size.toString()}")
println(hash)
}
In the Kotlin Playground this outputs
Hash size is 2
{sis=[Tamanna, Aklima], bro=[Ali Umar, Faruk, Ab Siddik]}
The problem is that the following instructions are just reading from the hashmap but not inserting anything
hash["bro"]
hash["sis"]
so when you create your hashmap with val hash= HashMap<String, ArrayList<String> >() it is empty and "bro" and "sis" do not exist. so it is null and the add function will not be called because of ?. skips execution if the value is null.
so to add something to bro and sis you first have to put values to your hashmap.
hash.put("bro",ArrayList<String>())
hash.put("sis",ArrayList<String>())
this would change your example as follows
val hash= HashMap<String, ArrayList<String> >()
hash.put("bro",ArrayList<String>())
hash.put("sis",ArrayList<String>())
hash["bro"]?.add("Ali Umar")
hash["sis"]?.add("Tamanna")
hash["bro"]?.add("Faruk")
hash["sis"]?.add("Aklima")
hash["bro"]?.add("Ab Siddik")
Log.d("Hash", hash.size.toString())

add/overwrite field of type array in Firestore

I want to add a field of type array inside a collection.
if the field doesn't exist create it. if it exists overwrite it with the new array value.
the field should be called macAddress and it's of type array of String
I have tried the following:
val macInput = setting_mac_text.text.toString()
val macArray = macInput.split(",")
val macList = Arrays.asList(macArray)
val data =
hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
//save it in firebase
db.collection(FirebaseConstants.ORGANIZATION)
.document(orgID + ".${FirebaseConstants.USER_MAC_ADDRESS}")
.set(FieldValue.arrayUnion(macList))
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "successfully inserted")
} else {
Log.d(TAG, " failed ${task.exception}")
}
}
also tried to insert the list itself and hash map like this
val data = hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
db.collection(FirebaseConstants.ORGANIZATION)
.document(orgID)
.set(data))
but it keeps giving me java.lang.IllegalArgumentException: Invalid data. Nested arrays are not supported
what am I doing wrong here?
You're doing three things wrong here:
FieldValue.arrayUnion() is only meant to be used as the value of a field to add elements to that field. The way you are using it now in the first sample, it's being taken as the entire contents of the document.
set() with one parameter is only intended to create or overwrite an entire document. It can't be used to update an existing document. You would have to pass in SetOptions to tell it to merge if you want an update. Or, you would simply use update() to modify an existing document.
Your code that deals with macArray and macList isn't working the way you expect. You are creating a list with one element, which is itself an array. The error message is telling you that you can't have nested arrays like this.
I suggest taking a step back and simplifying your code, removing all the moving parts that don't have to do with Firestore. Just hard code values in your Firestore update until the update works the way you want, then add in the code that works with actual values. Get one simple thing to work, then add to it. If you get an error, you will know that the code you just added was incorrect.
To overwrite an array, you would simply call the set method and have the merge option set to true:
try {
const query = await DatabaseService.queryBuilder({
collection: CollectionName,
});
return await query
.doc(insuranceId)
.set(
{ DOCUMENT_PROPERTY_HERE: ARRAY_HERE },
{ merge: true }
);
} catch (exception) {
return Promise.reject(exception);
}

Facing issue with AsyncTask in Android

I am facing the following issue.
String[] pkg_id = new String[]{package_id};
Log.d("pkg_id","=>"+Arrays.toString(pkg_id));
HashMap<String,String> data_pkg_act = new HashMap<>();
for(int k=0;k<pk_id.length;k++)
{
Log.d("pkg_id","==>"+package_id);
//Here am getting pkg_id==>1 and pkg_id==> 2
try {
data_pkg_act.put("package_id", package_id);
new GetPackageDetails(data_pkg_act).execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
HashMap is overriding the 1st value with 2nd I wanted to make a call twice based on package_id. AsyncTask calling twice but with package id 2 am not able to call it for package id 1
this is just because, HashMap can not have same keys twice. as it works by key, value pair. you will need to use separate keys for both entries to make it work.
you are using same key 'package_id' for two different package ids

Add element to end of a list - AWS DB from Android

I have a list item within AWS NoSQL DB.
I want to add a String value to the end of that list. My code is the following:
HashMap<String, AttributeValue> primaryKey = new HashMap<>();
AttributeValue key = new AttributeValue()
.withS(Array1[x]);
AttributeValue range = new AttributeValue()
.withS(Array2[x]);
primaryKey.put("XXXXX", key);
primaryKey.put("XXXXX", range);
try {
UpdateItemRequest request = new UpdateItemRequest()
.withTableName("XXXXXXXXXXXXXXXX")
.withKey(primaryKey)
.addAttributeUpdatesEntry(
"groups", new AttributeValueUpdate()
.withValue(new AttributeValue().withS(groupID))
.withAction(AttributeAction.ADD));
dynamoDBClient.updateItem(request);
Unsurprisingly this just overwrites the entire list in the AWS DB with the string rather than adding a new element to the list.
Is there anyway to do this without having to download the whole list, adding the string and then re-uploading? Would be allot cleaner to just ask that a new element is added to the end of the list.
Figured it out if anyone is having a similar issue.
Rather than trying to add an element to the "groups" field which is a list I changed the field in DynamoDB to a string set and adjusted the code as follows:
try {
UpdateItemRequest request = new UpdateItemRequest()
.withTableName("XXXXXXXXXXX")
.withKey(primaryKey)
.addAttributeUpdatesEntry(
"groups", new AttributeValueUpdate()
.withValue(new AttributeValue().withSS(groupID))
.withAction(AttributeAction.ADD));
dynamoDBClient.updateItem(request);
This now adds a new element to the end of the string set
I believe you're are actually looking for this:
UpdateItemRequest request = new UpdateItemRequest();
request.setTableName("myTableName");
request.setKey(Collections.singletonMap("hashkey",
new AttributeValue().withS("my_key")));
request.setUpdateExpression("list_append(:prepend_value, my_list)");
request.setExpressionAttributeValues(
Collections.singletonMap(":prepend_value",
new AttributeValue().withN("1"))
);
dynamodb.updateItem(request);
Example taken from: How to update a Map or a List on AWS DynamoDB document API?

How to access Firebase Database node using contains() method?

I am working on an app using Firebase Database. In my Firebase Database I have a node like xxxxxx_yyyyyy, where xxxxxx represents first user ID and yyyyyy represents second user ID. Now I want to retrieve only nodes which contains xxxxxx_ from my database. I don't know how to do this. Because all I know is Firebase gives only equalsTo() method.
There is no query like contain(). I recommend to change node structure (locating yyyyy under xxxxx).
There Is no Query Like Contains in Fire base.!
if you dnt want to change structure of your node you can Store Data in list and then simply use list.contains() you will get your desired Result.!
HtBVbQP0qMSrCStroYsIiMSuhMC3 //node userID
Name:XXXXXXX
You can get this Data by using orderbychild(XXXXXX);
There is no contain() method, however, you can solve this problem in two ways:
Using the split() method from String class.
Using Regex Pattern
Here is the code:
String firebaseField = "xxxxxx_yyyyyy";
String[] data = firebaseField.split("_");
System.out.print("Using split method: ");
for(String part : data) {
if (part.equals("xxxxxx")) {
System.out.print(part + " ");
//Add your logic
}
}
Or
System.out.print("\nUsing Regex Pattern: ");
Pattern datePattern = Pattern.compile("_");
data = datePattern.split(firebaseField);
for(String part : data) {
if (part.equals("xxxxxx")) {
System.out.print(part + " ");
//Add your logic
}
}
Hope it helps.

Categories

Resources