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.
Related
i have an static hashmap :
private static HashMap<String, byte[]> mDrawables = new HashMap<>();
by thread I download an image as a byte[] and i want add this new hashmap to static hashmap.
protected void onResult(String srv, HashMap<String, byte[]> drawables) {
super.onResult(srv, drawables);
mDrawables.putAll(drawables);
}
but every time that invoked putAll ,all info on mDrawables is cleared .
how could i add new map key, value to static once??
Well, accordint to JavaDoc:
/**
* Copies all of the mappings from the specified map to this map.
* These mappings will replace any mappings that this map had for
* any of the keys currently in the specified map.
*
* #param m mappings to be stored in this map
* #throws NullPointerException if the specified map is null
*/
So, the same keys will be replaced. You can use Map#put() in a cycle and check it by yourself like this:
for (Map.Entry<String, byte[]> entry : drawables.entrySet()) {
if (mDrawables.containsKey(entry.getKey())) {
// duplicate key is found
} else {
mDrawables.put(entry.getKey(), entry.getValue());
}
}
I'm new in Multiplayer programming. How to set String into hashmap value ? I want to call hashmap properties from RoomListActivity and set it's value on QuizMaintain activity and also I want to set hashmap value from QuizMaintain class to textview. Here's my sample code
RoomListActivity
public void onJoinNewRoomClicked(View view){
progressDialog = ProgressDialog.show(this,"","Please wait...");
progressDialog.setCancelable(true);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("timer", "");
properties.put("question", "");
properties.put("answer", "");
properties.put("foulanswer", "");
theClient.createRoom(""+System.currentTimeMillis(), "Yoshua", 2, properties);
}
Then I want to set it's value from QuizMaintain activity
public class QuizMaintain extends Activity implements RoomRequestListener, NotifyListener {
private WarpClient theClient;
private HashMap<String, Object> properties;
private TextView txttimer,txtquestion;
private String roomId = "";
private HashMap<String, User> userMap = new HashMap<String, User>();
String string="5x5#5x4#150:3#500:20#536+59";
String[] questions = string.split("#");
String question1 = questions[0];
String question2 = questions[1];
String question3 = questions[2];
String question4 = questions[3];
String question5 = questions[4];
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_maintain);
txttimer = (TextView)findViewById(R.id.timer);
txtquestion = (TextView)findViewById(R.id.questionview);
try{
theClient = WarpClient.getInstance();
}catch(Exception e){
e.printStackTrace();
}
theClient.getLiveRoomInfo("143680827");
Intent intent = getIntent();
roomId = intent.getStringExtra("roomId");
init(roomId);
//setquestionview();
}
private void init(String roomId){
if(theClient!=null){
theClient.addRoomRequestListener(this);
theClient.addNotificationListener(this);
theClient.joinRoom(roomId);
}
}
#Override
public void onGetLiveRoomInfoDone(LiveRoomInfoEvent event) {
properties = event.getProperties();
properties.put("question", question1);
}
I want to set hashmap value where is the key are "question". And the value that i want to set are from split string.When I ask their support team if I want to get room properties I should call getLiveRoomInfo method and pass roomID as argument. A bit confused here. Thanks.
But it seems my problem are not solved yet. After call method updateRoomProperties but I got another error here. It's say WarpClient.AddZoneRequestListener(this) return null pointer exception
When you are creating a room you are passing a hashmap. This hashmap is stored as a JSON document inside the room on server. AppWarp calls it Room Properties.
Now to retrieve these properties you have to call getLiveRoomInfo method. This will present you the room properties. Here you are adding/changing some key-value again. But you haven't told the server that you are updating these room properties. Therefore your changes remain local and that too limited to the scope of function.
So, when you call the getLiveRoomInfo method, you won't see the changes as you haven't updated them on server. To update on server, you need to call updateRoomProperties method. In this method you can add or change your hashmap.
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...
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)
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