Hi im trying to create an array of the keys/values in a Object from a map. i have a function in a global actions class that formulates a url by passing in Objects with values in breaking them up to form a string to add to my url. does anyone know how to map an object and extract all the keys/values to a string?
heres what i have so far
public final static void startAPICallRequest(Context activityContext, String request, String apiLocation, Object postVarsObj, JSONObject getVarsObj){
long unixTimeStamp = System.currentTimeMillis() / 1000L;
Log.v("globals", "getVarsObj: " + getVarsObj);
if(getVarsObj != null){
Map map = (Map) getVarsObj;
for (Object key : map.keySet()) {
((Object) getVarsObj).toString();
}
Log.v("globals","map=" + map);
}
}
Try using parameters when you declare your Map
Map<K,V> map = new Map<K,V>();
Where K is the data type you want to use for your key and V is the data type you will use for your value in the Map. Looks like your value will be an Object and your key maybe a String. Then add your objects to the Map with map.put(k,v)
Related
Every 3 seconds, I am receiving text messages containing latitude and longitude. To send the coordinates from my SmsReceiver.class to my MapActivity.class, I used intent, which causes my Google Map to refresh every time I receive the coordinates. Every time I receive a message, it intents another MapActivity.class. How do I pass HashMap values without using intent?
This is how I save my HashMap values which is stored on my SMSReceiver.class.
private HashMap<String, Double> coordinates = new HashMap<String, Double>();
DatabaseReference mRef = databaseLocation.push();
double latitudedb = Double.parseDouble(separatedSMS[1]);
double longitudedb = Double.parseDouble(separatedSMS[3]);
coordinates.put("latitude", latitudedb);
coordinates.put("longitude", longitudedb);
I wanted to get the HashMap values to my MapActivity.class so I would be able to place a marker on my map which positions to actual coordinates I am receiving.
you can use a class and static value for this :
public class CommunActivit {
private static HashMap<String, Float> ListOf;
static {
ListOf = new HashMap<>();
}
public static HashMap<String, Float> getListOf() {
return ListOf;
}
public static void setListOf(HashMap<String, Float> listOf) {
ListOf = listOf;
}
}
Create an instance of CommunActivit in your activity
By exemple :
CommunActivit obj = new CommunActivit();
When you get your coordinates, you can simply call the obj.setListOf(yourhashmap) and when you want to get it, simply call yourhashmap = obj.getListOf();
I use this in my app and it works fine.
Hello can some one please explain me the below code of video id of Youtube integration android Json for Video ID.
String videoID = (String) ((JSONObject) ((JSONObject) jsonObject.getJSONArray("items").get(0)).get("id")).get("videoId");
This is a one liner using java's object casting.
Instead of using the specific functions getJSONObject / getJSONArray / getString, is it only using get + type casting.
An easier (and longer) version would be:
// Get the items array from the json object
JSONArray items = jsonObject.getJSONArray("items") // equivalent of (JSONArray) jsonObject.get("item")
// Get the first item at index 0
JSONObject item0 = items.getJSONObject(0) // equivalent of (JSONObject) items.get(0)
// Get the object "id" from the first item
JSONObject idObj = item0.getJSONObject("id") // equivalent of (JSONObject) item0.get("id")
// Get the string video from the object "id"
String videoId = idObj.getString("videoId") // equivalent of (String) idObj.get("videoId")
Or a one line :
String videoId = jsonObject.getJSONArray("items")
.getJSONObject(0)
.getJSONObject("id")
.getString("videoId")
Hi the below is my response from format
object {6}
csdfgi_fgid : 4casdff9743a1-3f9asdf2-4
fesdfgedVsdfgersionsfdg : 7
sdfg : 28
feesdfgdStart : 0
fesdfedCsdfgoudfsgnt : 28
discover[28]
0{4}
DiscCat : Tip
templateCat{2}
name : tip.tp
version : 2
timestamp : 1421146871251
content{1}
I am getting these values using Serializable in class like below
#SerializedName("csdfgi_fgid")
public String sCdfsisdfId;
#SerializedName("feedVersion")
public Long lFesdfgedVsdfgfsersdfsion;
#SerializedName("feed")
public ArrayList<DiscoverModel> discover;
Now in the array list again there is a Json Object "templateCat" which has two parameters "name , version". Now how to get values from this JSON Object
First of all you need to assign all the JSONObject that you are getting in a POJO class. After that getting JSONObject(templateCat) from JSONArray(discover) you have to do looping. For example:
for(int i=0;i<discover.size();i++){
TemplateCat templateCat = discover.get(i).getTemplateCat();
String strName = templateCat.getName();
String strVersion = templateCat.getVersion();
//If you want to get all name and version as list. Add strName and strVersion to ArrayList. <br>
For Example : nameArray.add(strName);
versionArray.add(strVersion);
}
You'll have to get that JSON array first, iterate thru it and then use Gson to convert it into your desired object.
JSONObject rootJson = /* Get your JSON object here */;
JSONArray nestedArray = rootJson.getJsonArray("your_nested_json_array_name");
List<YourObject> objects;
for(int i = 0; i < nestedArray.size(); i++) {
String objectJsonString = nestedArray.get(i);
YourObject o = new Gson().fromJson(objectJsonString, YourObject.class);
objects.add(o);
}
..the last thing you'd need to do is to set our objects list to your desired instance.
Currently working on an app that takes results from a search, parses the JSON object returned, and then adds the resulting pieces into a few ArrayLists within a class created called VenueList.
Here is the method that receives the results from the service and parses the JSON:
private static List<String> getResultsFromJson(String json) {
ArrayList<String> resultList = new ArrayList<String>();
try {
JSONObject resultsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = resultsWrapper.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
resultList.add(result.getString("text"));
}
}
catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
return resultList;
}
What results of this becomes a List variable call mResults (to clarify: mResults = getResultsFromJson(restResult);. That is then used, among other places, in the following loop that puts the results into an ArrayAdapter that is used for displaying them in a ListFragment:
for (String result : mResults) {
VenueList.addVenue(result, "HELLO WORLD");
adapter.add(result);
}
I also add the result to a class called VenueList that manages the results and makes them accessible for multiple views. It essentially just holds multiple ArrayLists that hold different types of details for each venue returned in the search. The method I use to add a venue to VenueList is below (and you can see it used in the for loop above):
public static void addVenue(String name, String geo) {
venueNames.add(name);
venueGeos.add(geo);
}
I want the addVenue method to be able to take multiple arguments and update the VenueList class. Yet, when I call the addVenue method in the for loop, I can only pass it String result (from the parameters of the loop) and can't figure out how to pass it a second argument (which should also come from the JSON parsed by getResultsFromJson) so I've used "HELLO WORLD" as a placeholder for now.
I realize getResultsFromJson only has one list returned. I need to be able to take multiple elements from the JSON object that I parse, and then add them to VenueList in the right order.
So my questions are:
1) Given the getResultsFromJson method and the for loop, how can I use the addVenue() method as designed? How do I parse multiple elements from the JSON, and then add them to the VenueList at the same time? I plan on adding more arguments to it later on, but I assume if I can make it work with two, I can make it work with four or five.
2) If that's not possible, how should the getResultsFromJson, the for loop, and the addVenue method be redesigned to work properly together?
Please let me know if you need more detail or code - happy to provide. Thank you!
EDIT - Full VenueList class:
public class VenueList {
private static ArrayList<String> venueNames;
private static ArrayList<String> venueGeos;
public VenueList() {
venueNames = new ArrayList<String>();
venueGeos = new ArrayList<String>();
}
public static void addVenue(String name, String geo) {
venueNames.add(name);
venueGeos.add(geo);
}
public static String getVenueName(int position) {
return venueNames.get(position);
}
public static String getVenueGeo(int position) {
return venueGeos.get(position);
}
public static void clearList() {
venueNames.clear();
venueGeos.clear();
}
}
Clarification: I will have additional ArrayLists for each element of data that I want to store about a venue (phone number, address, etc etc)
1) I don't think methods getResultsFromJson(String json) and addVenue(String name, String geo) fit your needs.
2) I would consider rewriting method getResultsFromJson(String json) to something like this:
private static SortedMap<Integer, List<String>> getResultsFromJson(String json) {
Map<Integer, String> resultMap = new TreeMap<Integer, String>();
//...
return resultMap;
}
where the number of keys of your map should be equal to the number of objects you're extracting info, and each one of them will properly have their own list of items just in the right order you extract them.
With this approach you can certainly change your logic to something like this:
// grab your retuned map and get an entrySet, the just iterate trough it
SortedMap<Integer, String> result = returnedMap.entrySet();
for (Entry<Integer, String> result : entrySet) {
Integer key = result.getKey(); // use it if you need it
List<String> yourDesiredItems = result.getValue(); // explicitly shown to know how to get it
VenueList.addVenue(yourDesiredItems);
}
public static void addVenue(List<String> yourDesiredItems) {
// refactor here to iterate the items trough the list and save properly
//....
}
EDIT -- as you wish to avoid the go-between map i'm assuming you need nothing to return from the method
First i'm providing you with a solution to your requirements, then i'll provide you with some tips cause i see some things that could smplify your design.
To save VenueList things directly from getResultsFromJSON do something like this:
private static void getResultsFromJson(String json) {
try {
JSONObject resultsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = resultsWrapper.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
//FOR EXAMPLE HERE IS WHERE YOU NEED TO EXTRACT INFO
String name = result.getString("name");
String geo = result.getString("geo");
// and then...
VenueList.addVenue(name, geo, ..., etc);
}
} catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
}
This implies that your addVenue method should know receive all params needed; as you can see this is just a way (that you can consider a workaround to your needs), however as i don't know all requirements that lead you to code this model, i will point to a few things you might consider:
1. If there's a reason for VenueList class to use everything static, consider doing this:
static{
venueNames = new ArrayList<String>();
venueGeos = new ArrayList<String>();
//....
}
private VenueList(){
}
This way you won't need to get an instance every time and also will avoid null pointer exceptions when doing VenueList.addVenue(...) without previous instantiation.
2. Instead of having an ArrayList for every characteristic in VenueList class consider defining a model object for a Venue like this:
public class Venue{
String name;
String geo;
//... etc
public Venue(){
}
// ... getters & setters
}
then if you need that VenueList class you will just have a list o Venue objects (List<Venue>), this means that instead of calling the method addVenue, you will first create a brand new instance of Venue class and will call the setter method of each characteristic, as an example of the refactored for loop from the workaround i provided you you'd be using something like this:
List<Venue> myListOfVenues = new ArrayList<Venue>();
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
// THIS WOULD REMAIN THE SAME TO EXTRACT INFO
String name = result.getString("name");
String geo = result.getString("geo");
// and then instead of calling VenueList.addVenue(name, geo, ..., etc)...
Venue v = new Venue();
v.setName(name);
v.setGeo(geo);
// ...etc
myListOfVenues.add(v);
}
// Once you're done, set that List to VenueList class
VenueList.setVenueList(myListOfVenues);
So VenueList class would now have a single property List<Venue> venueList; and would suffer minor tweeks on methods getVenueName, etc... and everything would be more readable... i hope this helps you to get another approach to solve your problem, if i still don't make my point let me know and i'll try to help you out...
I have a problem on arraylist and hashmap
As according to my requirement, I am storing the data into HashMap and after that I have created a List as List>.
HashMap<String,String> hashmap;
static List<HashMap<String,String>> hashmap_string;
And while retrieving the value from database and putting it on HashMap and ArrayList like:
contract_number=c.getString(c1);
Log.i("c1.getString,contract_number", contract_number);
String service_level=c.getString(c2);
hashmap=new HashMap<String, String>();
hashmap.put(contract_number, service_level);
hashmap_string.add(hashmap);
And now I want to retrieve the value as String,String
And when I am applying the code as:
for(int i=0;i<hashmap_string.size();i++)
{
Log.i("arraylist", ""+hashmap_string.get(i));
}
I am getting a single string value in the formet as
{Contract,ServiveValue}
but I want to split this into 2 string values...Also these values are redundant and if am using hashMap then it will not showing me the redundant value.
Please help me on this..
It seems you are missing something. When you execute hashmap_string.get(i), you will get the <HashMap<String,String>. So, This is the right value from code.
What you can do is :
HashMap<String, String> hashMap2 = hashmap_string.get(i);
String value = hashMap2.get("your_key");
Other way, you already have two splited string values. you can get that by using keySet() and values() methods over hashMap2 Object.
HashMap (and Maps in general) are used for multiple one-to-one mappings of keys and values. Are you sure you need that? Looking at your code it appears you're using the map as a "Pair" class. I would skip the list, and put everything in the same map, and then iterate over the pairs in the map:
// using tree map to have entries sorted on the key,
// rather than the key's hash value.
Map<String, String> data = new TreeMap<String, String>();
data.put("c1", "s1");
data.put("c2", "s2");
for (Map.Entry<String, String> entry : data.entrySet()) {
String contract = entry.getKey();
String level = entry.getValue();
Log.i("data", contract + " : " + level");
}
would output (assuming TreeSet):
c1 : s1
c2 : s2
Alternatively, create e.g. a ContractServiceLevel class that holds two strings (the contract number and the service level), and put instances of that class in your list.
EDIT:
public final class ContractServiceLevel {
public final String number;
public final String serviceLevel;
public ContractServiceLevel(String c, String s) {
number = c;
serviceLevel = s;
}
}
List<ContractServiceLevel> contracts = new ArrayList<ContractServiceLevel>();
contracts.add(new ContractServiceLevel("c1", "s1.1"));
contracts.add(new ContractServiceLevel("c1", "s1.2"));
contracts.add(new ContractServiceLevel("c2", "s2.1"));
for (ContractServiceLevel contract : contracts) {
Log.i("data", contract.number + ":" + contract.servicveLevel);
}
would output:
c1 : s1.1
c1 : s1.2
c2 : s2.1
String value = hashmap.get("contract");
u will be getting the value as ServiveValue