How can I get another HasMap from entry.getValue? - java

From For each loop, inside entry.getValue(), There is another map coming from firestore. How can I get?
Code:
#Override
public void onComplete (#NonNull Task < QuerySnapshot > task) {
if (task.isSuccessful()) {
// binding.contentMain.noData.setVisibility(View.GONE);
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
showLog("Data: " + document.getData());
postMap.putAll(document.getData());
}
try {
for (Map.Entry<String, Object> entry : postMap.entrySet()) {
if (entry.getKey().equals(CONTENT)) {
showLog("value: " + entry.getValue().toString());
contentMap = new HashMap<>();
contentMap.putAll(entry.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
// binding.contentMain.noData.setVisibility(View.VISIBLE);
showLog("Error getting documents: " + task.getException());
}
}
I tried like below but compiler error. No suugestion:
Map map = new HashMap();
((Map)map.get( "keyname" )).get( "nestedkeyname" );

try this
contentMap.putAll((Map<? extends String, ? extends Object>) entry.getValue());

using your variable naming, try this
entry.iterator().next()
So if you have hashmap A:
{"key1":"value1",
"key2":"value2",
"key3":"value3"}
given the entryset of this hashMap "entrySet" you could do
entrySet.iterator().next()
which if used in a while loop can iterate throught all the key and values in the hashmap

Related

Problem with retrieving data from firebase

This is the error log
i have a problem in retrieving data from firebase realtime database. java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map
E/AndroidRuntime: FATAL EXCEPTION: main
Process: root.example.com.chatrack, PID: 31556
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map
at root.example.com.chatrack.ChatActivity.AmbilDataGroup(ChatActivity.java:156)
at root.example.com.chatrack.ChatActivity.access$200(ChatActivity.java:48)
at root.example.com.chatrack.ChatActivity$2.onDataChange(ChatActivity.java:140)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.6:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.6:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.6:55)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
i dont know what's gone wrong
this the code i'm using for retrieving data
DatabaseReference add = mFirebaseDatabase.getReference().child("CHATRACK").child("USER").child(Child);
Log.d(TAG, "getFriendsInfo() returned: " + add);
add.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange() returned: " + dataSnapshot);
Log.d(TAG, "onDataChange() returned: " + Child.size());
AmbilDataGroup((Map<String, Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
private void AmbilDataGroup(Map<String, Object> dataSnapshot) {
final ArrayList<String> Nama = new ArrayList<>();
for (Map.Entry<String, Object> entry : dataSnapshot.entrySet())
{
Map nama= (Map) entry.getValue();
Nama.add((String) nama.get("Nama"));
}
}
why this is happen. in other activity the same code was fine and no problem.
i don't understand. please help
edit
here my database structure
enter image description here
String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
add this code in
DatabaseReference add = mFirebaseDatabase.getReference().child("CHATRACK").child("USER").child(Child);
Log.d(TAG, "getFriendsInfo() returned: " + add);
add.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange() returned: " + dataSnapshot);
Log.d(TAG, "onDataChange() returned: " + Child.size());
String value = dataSnapshot.getValue();
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
AmbilDataGroup(map);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
private void AmbilDataGroup(Map<String, Object> dataSnapshot) {
final ArrayList<String> NamaGroup = new ArrayList<>();
for (Map.Entry<String, Object> entry : dataSnapshot.entrySet()) {
Map namaGroup = (Map) entry.getValue();
NamaGroup.add((String) namaGroup.get("GroupName"));
}
final ArrayList<String> GroupMember = new ArrayList<>();
for (Map.Entry<String, Object> entry : dataSnapshot.entrySet()) {
Map groupMember = (Map) entry.getValue();
GroupMember.add((String) groupMember.get("GroupMember"));
}
final ArrayList<String> GroupId = new ArrayList<>();
for (Map.Entry<String, Object> entry : dataSnapshot.entrySet()) {
Map groupId = (Map) entry.getValue();
GroupId.add((String) groupId.get("GroupId"));
}
String[] member = GroupMember.toString().split(",");
String memberId;
if (GroupId != null) {
int i = 0;
while (GroupId.size() > i) {
memberId = GroupMember.get(i).replace("[", "").replace("]", "");
Log.d(TAG, "AmbilDataGroup() returned: " + GroupMember.get(i).split(","));
if (memberId.contains(UserId)) {
}
Log.d(TAG, "AmbilDataGroup() returned: int i" + i);
i++;
}
}
}

Spark save Kafka InputDStream as Json file

I just wondered whether there is a method in Spark, so I can save a JavaInputDStream as a Json file, or generally as any file.
And if not, whether there is an other possibility to save the content of
a kafka topic as a file in Spark.
Thank you very much!
As you map your JavaInputDStream to a stream you could do as follow:
stream.foreachRDD(rdd -> {
OffsetRange[] offsetRanges = ((HasOffsetRanges) rdd.rdd()).offsetRanges();
rdd.mapToPair(new PairFunction<ConsumerRecord<String, String>, String, String>() {
#Override
public Tuple2<String, String> call(ConsumerRecord<String, String> record) {
return new Tuple2<>(record.key(), record.value());
}
}).foreachPartition(partition -> {
OffsetRange o = offsetRanges[TaskContext.get().partitionId()];
System.out.println(o.topic() + " " + o.partition() + " " + o.fromOffset() + " " + o.untilOffset());
if (partition.hasNext()) {
PrintWriter out = new PrintWriter("filename.txt");;
out.println(text);
try {
while (partition.hasNext()) {
Tuple2<String, String> message = partition.next();
out.println(message);
}
} catch (Exception e) {
e.printStackTrace(
}
});
});
ssc.start();
ssc.awaitTermination();
Just don't forget that if you have multiple partitions inside your Kafka topic, you are going to write a file per partition following the approach above.

ArrayList, print only the value

I have a contactList = new ArrayList<>(); where I store information in this format: "name", value_for_name.
I populate my contactList inside this function:
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("results");
// looping through All Results
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String icon = c.getString("icon");
String id = c.getString("id");
String name = c.getString("name");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
// contact.put("id", id);
contact.put("name", name);
// contact.put("email", icon);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
The problem is that when I try to print a value:
System.out.println(contactList.get(position));
The output is in this format:
{name="Foo"}
I only want to print Foo
I tried also with: System.out.println(String.valueOf(contactList.get(position)));
but I always get the whole string: {name="Foo"}
Can you help me, please?
Do I really need to parse the string?
Try:
System.out.println(contactList.get(position).get("name"));
I see you have a hashmap into an array list so you want to get the object from "X" position from array and after that get the value from the hashmap by property name.

How to map JSON (custom)

I'm a beginner and I need to sort from a JSON to be analyzed later.
I need to know the JSON fields and if it has arrays or subcategories.
I have to map JSON input, for example:
{
"car":"Audi",
"model":"2010",
"price":"30000",
"colors":[
"Grey",
"White",
"Black"
],
"otro":{
"a":1,
"b":2,
"c":[
{
"c11":"c11",
"c12":"c12"
},
{
"c21":"c21",
"c22":"c22"
}
]
}
}
Waiting as output mapping:
car
model
price
colors[]
otro.a
otro.b
otro.c[].c11
otro.c[].c12
otro.c[].c21
otro.c[].c22
This is my code:
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"car\":\"Audi\",\"model\":\"2010\",\"price\":\"30000\",\"colors\":[\"Grey\",\"White\",\"Black\"],\"otro\":{\"a\":1,\"b\":2,\"c\":[{\"c11\":\"c11\", \"c12\":\"c12\"},{\"c21\":\"c21\", \"c22\":\"c22\"}]}}";
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue().getClass());
if (entry.getValue() instanceof List) {
for (Object object : ((List)entry.getValue())) {
System.out.println("\t-- " + object.getClass());
}
}
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
You can make a POJO and map the JSON to the POJO and do whatever you would like with it. Another option that is pretty powerful is using the JsonNode objects. They have lots of helper methods for figuring out the types of each node. Here are some quick examples https://www.stubbornjava.com/posts/practical-jackson-objectmapper-configuration#jsonnodes-and-nested-objects

how to solve.. abstract class? generics?

In my current setup I have a centralized helper class like the following:
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(task == null) {
return;
}
Gson gson = new GsonBuilder().create();
ResponseJson p = null;
try {
p = gson.fromJson(result, ResponseJson.class);
} catch(JsonSyntaxException e) {
//Toast.makeText(getApplicationContext(), getApplicationContext().getResources().getString(R.string.toast_sync_completed), Toast.LENGTH_SHORT).show();
Log.e("", e.getMessage() + " got '" + result + "'");
}
Log.i("", p.toString());
Log.i("", result);
if(p.status.equals(ResultStatus.SUCCESS.toString())) {
task.success(p.data);
} else if (p.status.equals(ResultStatus.FAIL.toString())) {
task.fail(p.data);
} else if (p.status.equals(ResultStatus.ERROR.toString())) {
task.error(p.message);
} else {
throw new UnsupportedOperationException();
}
}
the problem is i want to make the ResponseJson class to be dynamic and the data attribute to be unique (sometimes i need ArrayList<Something> other times HashMap<String, String>) works for converting my JSON result. can i achieve this using generics or some other means?
If you set Object as type of data,
class ResponseJson {
Object data;
}
Later you can get the results as ArrayList or Hashmap as follows;
if (responseJson.data instanceof ArrayList<?>) {
ArrayList<String> arrayList = (ArrayList<String>) responseJson.data;
} else if(responseJson.data instanceof HashMap<?, ?>) {
HashMap<String, String> hashmap = (HashMap<String, String>) responseJson.data;
}
Due to type erasure, the parameterised type cannot be known at runtime. But if you know the type you can do an unchecked cast.

Categories

Resources