I am trying to implement a data structure which allows me to keep track of an index (so I can blindly access the data points), a key (which needs to be there to identify the data in the rest of the program), and a value.
I've looked at a map, but that does not allow me to access the data points without any key. I need some combination of a Queue and a Map. Does this exist and I'm just missing it? Thanks for the help.
I believe what you are looking for is a LinkedHashMap. It will return an ordered collection and you can access values via a key.
LinkedHashMap<Key, Value> myMap = new LinkedHashMap<Key, Value>();
myMap.put(aKey, aValue); //adds to map.
myMap.values(); //returns collection of values
aValue = myMap.get(Key); //returns a value with the given key
Related
Is it possible to get the values in a map associated to a key, without using the key?
I have this code.
val map = prices.associateBy({it.productName},{it.productPrice})
which gives me this
{Coffee=3.0, Gum=0.5, Beer=18.0}
I want to be able to just grab all the prices (3.0, 0.5, etc.) and save them to a list.
Any help is appreciated!
So to get all the values from a map, you can just use the built-in values property on the map like this.
val map = prices.associateBy({it.productName},{it.productPrice})
val values = map.values
It returns a read-only Collection of all values in this map. Note that this collection may contain duplicate values.
I am making an app which downloads LatLngs from firebase and shows them as markers in google maps API, users can add new LatLngs.
In my database I also have the pricepoint and types of markers. In the main screen the user can choose what types of marker he wants to see on the map.
So my application does something like this:
locations.orderByChild(pricepoint).equalTo(choosenPricepoint);
and then I check programmatically if types match those chosen by the user
int type = Integer.parseInt(locations.child("restaurantType").getValue().toString();
if(type == funCode|| type == runingCode|| type == sportsCode
{
mMap.addMarker(new MarkerOptions().position(snapshot.getLatlng);
}
And it works fine with 250 records, but I'm expecting over 10,000 of them in my database so I am worried that it will be too slow.
I don't know if showing markers only where user's maps camera is and deleting other will be faster. What do you suggest?
You can use GeoFire , a firebase library that uses GeoHashes to merge lat+lon into a single property.That way you can do the distance filtering directly on the database.
You should have 2 entries in firebase database,one for setting your object location and one for setting your object with its fields.
As you can see they have the same id.So first you are queriing for nearby object by GeoFire in geo_data entry,and you will get the ids of the object which are nearby,then you can retreive object with its properties directly from database using the ids in my case in user_data entry
I want to append two different hash map pairs on a particular node one with key value both being String and other String and Array List. But problem is Later one is replacing first one in Fire base database. what should i do? I cant use push() all the time.Link of my code. Please help
You can achieve this if you generate a unique random key. This can be done using push() method.
As we know, in the case of HashMap, it replaces the old value with the new one.
Don't forget to use updatechildren() method, and not setValue() method directly on the refrence when you want to update data.
Hope it helps.
Just use 1 Map<String, Object> instead of 2 different ones.
then you put all the data in that single map, string, arraylist
This question is about Parse
From what I've found,
Each ParseObject contains key-value pairs of JSON-compatible data. This data is schemaless, which means that you don't need to specify ahead of time what keys exist on each ParseObject. You simply set whatever key-value pairs you want.
However as a learner, I got multiple questions :
Can I set my own objectID while saving data?
Does the objectID varies when pushed from different devices? If so, how to retrieve those data?
Can I set my own objectID while saving data?
yes you can
ParseObject parseObject = new ParseObject("<ClassName>");
parseObject.setObjectId("<ObjectId>");
Does the objectID varies when pushed from different devices?
every object has unique ID even if they created by the same device.
I'm unsure how I'm supposed to save the game state of my game that I'm developing. Should I save a instance/object containing all the game information? If yes, how? Or should I save all the relative information in a .txt file and save/load information when needed?
How do you do this and what do you think of my proposals?
You can't save an Instance / Object unless you serialize it and save it to some text/binary/database file. Your two options are kind of identical therefore.
What you need to save is all information that you need to reconstruct your game state. There are probably some information that you can derive from here.
If you have just a small fixed set of variables that define your gamestate then use SharedPreferences.
If you want to keep more than one state and / or it is more complex to save use some text (xml, json, ...)/binary/database/.. representation and store that.
I can suggest to use Parse.
https://parse.com/docs/android_guide#objects
The ParseObject
Storing data on Parse is built around the ParseObject. Each ParseObject contains key-value pairs of JSON-compatible data. This data is schemaless, which means that you don't need to specify ahead of time what keys exist on each ParseObject. You simply set whatever key-value pairs you want, and our backend will store it.
For example, let's say you're tracking high scores for a game. A single ParseObject could contain:
score: 1337, playerName: "Sean Plott", cheatMode: false
Keys must be alphanumeric strings. Values can be strings, numbers, booleans, or even arrays and objects - anything that can be JSON-encoded.
Each ParseObject has a class name that you can use to distinguish different sorts of data. For example, we could call the high score object a GameScore. We recommend that you NameYourClassesLikeThis and nameYourKeysLikeThis, just to keep your code looking pretty.
Saving Objects
Let's say you want to save the GameScore described above to the server. The interface is similar to a Map, plus the save method:
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
try {
gameScore.save();
} catch (ParseException e) {
// e.getMessage() will have information on the error.
}
After this code runs, you will probably be wondering if anything really happened. To make sure the data was saved, you can look at the Data Browser in your app on Parse. You should see something like this:
objectId: "xWMyZ4YEGZ", score: 1337, playerName: "Sean Plott", cheatMode: false,
createdAt:"2011-06-10T18:33:42Z", updatedAt:"2011-06-10T18:33:42Z"
There are two things to note here. You didn't have to configure or set up a new Class called GameScore before running this code. Your Parse app lazily creates this Class for you when it first encounters it.
There are also a few fields you don't need to specify that are provided as a convenience. objectId is a unique identifier for each saved object. createdAt and updatedAt represent the time that each object was created and last modified on the server. Each of these fields is filled in by the server, so they don't exist on a ParseObject until a save operation has completed.
Retrieving Objects
Saving data to the cloud is fun, but it's even more fun to get that data out again. If you have the objectId, you can retrieve the whole ParseObject using a ParseQuery:
ParseQuery query = new ParseQuery("GameScore");
ParseObject gameScore;
try {
gameScore = query.get("xWMyZ4YEGZ");
} catch (ParseException e) {
// e.getMessage() will have information on the error.
}
To get the values out of the ParseObject, there's a getX method for each data type:
int score = gameScore.getInt("score");
String playerName = gameScore.getString("playerName");
boolean cheatMode = gameScore.getBoolean("cheatMode");
If you don't know what type of data you're getting out, you can call get(key), but then you probably have to cast it right away anyways. In most situations you should use the typed accessors like getString.
The three special values have their own accessors:
String objectId = gameScore.getObjectId();
Date updatedAt = gameScore.getUpdatedAt();
Date createdAt = gameScore.getCreatedAt();
If you need to refresh an object you already have with the latest data that is on the server, you can call the refresh method like so:
myObject.refresh();
You could use an SQLite database to save the important variables in your game. If the game is started from one class you could provide that class with two constructors, one which instantiates a normal game from the beginning and another which accepts all of the variables from your game and creates the game object from the save point.
This will allow you to have more than one game save (by saving the id along with any data) and game saves will not be lost if you ever update your game (Assuming you don't alter the database).
Do a quick search for "constructor overloading" to find out more.
If your game is not data intensive and if serializing and saving to Shared Preferences is enough, you can check out the GNStateManager component of the library I wrote to make it easy to store and retrieve the required fields of the activity marked my #GNState annotation. It is dead simple to use. Other singleton class object states can be saved too. See here for Setup and Usage information: https://github.com/noxiouswinter/gnlib_android/wiki/gnstatemanager