Is there anything like NSDictionary in android? - android

I'm new to Android. I did search around but couldn't find anything work like NSdictionary of iOS in Android. For example in iOS I can create SIMPLE array of dictionary like this format
Array
idx1: [objA1 for keyA],[objB1 for keyB],[objB1 for keyC]
idx2: [objA2 for keyA],[objB2 for keyB],[objB2 for keyC]
idx3: [objA3 for keyA],[objB3 for keyB],[objB3 for keyC]
I know I can create string-array that work similar like that in android
<string-array name="list_obj1">
<item>ObjA1</item>
<item>ObjB2</item>
<item>ObjC3</item>
</string-array>
<string-array name="list_obj2">
<item>ObjB1</item>
<item>ObjB2</item>
<item>ObjB3</item>
</string-array>
<string-array name="list_obj3">
<item>ObjC1</item>
<item>ObjC2</item>
<item>ObjC3</item>
</string-array>
My question is if there is anything else used to create AN array of dictionary in Android like iOS.
Thank you for your help.

First, I think there are many tutorial about this stuff then you can search for more info.
Since you are new to android you might not know the "name" to search. For this case, "HashMap" is what you looking for. It works like NSdictionary.
//Create a HashMap
Map <String,String> map = new HashMap<String,String>();
//Put data into the HashMap
map.put("key1","Obj1");
map.put("key2","Obj2");
map.put("key3","Obj3");
// Now create an ArrayList of HashMaps
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Add the HashMap to the ArrayList
mylist.add(map);
Now you have st like an array of dictionary.
Hope this help.

You could put what #user1139699 said into an ArrayList.
ArrayList<HashMap> list = new ArrayList();
Map <String, String> map = new HashMap<String,String>();
map.put("key","Obj");
list.add(map);

also if you want to load a file like this:
property.key.1=value of 1st key
property.key.2=value of 2nd key
prompt.alert = alert
etc you may use java Properties(); Then you can instantly get the value of each key.
Explanation:
You have for example a file myTranslations.txt . In that file you write pairs of keys/values in the format:
property.key.1=value of 1st key
property.key.2=value of 2nd key
prompt.alert = alert
where the part before the "=" is the key, and the part after is the value.
Then in your code you do:
Properties properties = new Properties();
File propertiesFile = new File (filePath);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(propertiesFile);
properties.load(inputStream);
} catch (IOException ioe) {
ioe.printStackTrace();
}
where filePath is the path to file above.
Then you can get the value of each key as:
properties.get("prompt.alert")
which will return the string:
alert
as it is in the txt file.
If it helps please upvote.

Related

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?

Android mapping does not work

Hi I have to send map to server and the server will get information from that. I'm having two piece of code for mapping first is(name and key are variables)
String user = "{ 'id':" + userId +","+"'response':{'id':"+userId+",'access':"+"'"+name+":"+key+"'"+"}}";
Map<String, Object> userMap = new Gson().fromJson(user, new TypeToken<HashMap<String, Object>>() {}.getType());
Set<String> keys = userMap.keySet();
for (String i:keys){
Log.d("user",i+" "+userMap.get(i));
}
here I concat required string and parse it and then convert it into map . This piece of code had worked. And my second set of code is
String user1 = "{id="+userId+", access="+""+name+":"+key+""+"}";
Map<String,Object> tuc = new HashMap<>();
tuc.put("id",userId);
tuc.put("access","");
Set<String> key = tuc.keySet();
for (String i:key){
Log.d("user",i+" "+tuc.get(i));
}
this code is not working,that mean server is not accepting this code. But when I print key value pairs the results are same for both codes. My lead doesn't like to use first piece of code. Can any one explain why,I'm struck in this for past two days. Thank you.Sorry for my poor English.
In Java, HashMap can only accept <key, value> pairs. It is not like Json, which in your case is in {key1:value1, key2:value2, ...} format.
Therefore, if you are intended to convert its format from {key1:value1, key2:value2, ...} into <key, value>. My suggestion is combining value2, value3, ... into an object (like String) as the value and value1 as the key.
See https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html for more details.

Json object to json array Java (Android)

It's been a while and i'm trying to ignore some frustrating issue i'm having with json things in java, i'm new to this and read alot however, parsing json in javascript or php was alot better (or easier i dunno) but now in java i cannot convert a jsonobject to jsonarray if it doesn't have a parent, cuz it uses .getJsonArray('array)
BUT what IF i have this :
{"49588":"1.4 TB","49589":"1.4 TB MultiAir","49590":"1.4 TB MultiAir TCT","49591":"1.6L MultiJet","49592":"1750 Tbi","49593":"2.0L MultiJet","49594":"2.0L MultiJet TCT"}
i'm not succeeding in anyway to convert it to array
what i want is to convert this JSONObject to JSONArray loop within its items and add them to a Spinner, now that's the first issue, the second question is: if i convert this to JSONArray how can i add the ID, Text to the spinner? just like the HTML Select tag
<option value="0">Item 1</option>
so it's an issue and a question hope someone can find the solution for this jsonarray thing, without modifying the json output from the website, knowing that if i modify and add a parent to this json, the JSONArray will work. but i want to find the solution for that.
Nothing special i have in the code:
Just a AsynTask Response, a log which is showing the json output i put at the beginning of this question
Log.d("response", "res " + response);
// This will work
jsonCarsTrim = new JSONObject(response);
// This won't work
JSONArray jdata = new JSONArray(response);
Thanks !
How about this:
JSONObject json = new JSONObject(yourObject);
Iterator itr = json.keys();
ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
ArrayList<Integer> links = new ArrayList<Integer>();
int i = 0;
while(itr.hasNext()) {
String key = itr.next().toString();
links.add(i,Integer.parseInt(key));
entries.add(i, (CharSequence) json.getString(key)); //for example
i++;
}
//this is the activity
entriesAdapter = new ArrayAdapter<CharSequence>(this,
R.layout.support_simple_spinner_dropdown_item, entries);
//spinner is the spinner the data is added too
spinner.setAdapter(entriesAdapter);
this should work (works for me), you may have to modify the code.
The way shown, i am adding all entries of the json object into a Spinner, where my json key is the index value and the linked String value of the json object will be shown as Spinner entry (title) in my activity.
Now when an Item is selected, fetch the SelectedItemPosition and you can look it up in the "links" array list, to get the real value.
I'm not sure if this is thing you want but give it a try. There is tutorial to convert the Json to Map. After you convert it, you can iterate through the map.
http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
What you have is a JSON object type, not an array type. To iterate you can get the Iterator from the keys method.

Getting a hashmap to print out in sequence

I have retrieved data from a 2-column CSV file using HashMap. This is for use in a dictionary-style app - one column contains terms and the second contains definitions, which are linked to the terms by the HashMap.
The first thing my app does is print out the list of terms as a list. However, they seem to all come out in a random order.
I'd like them to remain in the same order that they were in in the CSV file (I won't rely on any alphabetising methods, since I have the occasional non-standard characters and would prefer to alphabetise at the source)
Here's my code, which extracts the data from the CSV file and prints it to a list:
String next[] = {}; // 'next' is used to iterate through dictionaryFile
final HashMap<String, String> dictionaryMap = new HashMap<String, String>(); // initialise a hash map for the terms
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("dictionaryFile.csv")));
while((next = reader.readNext()) != null) { // for each line of the input file
dictionaryMap.put(next[0], next[1]); // append the data to the dictionaryMap
}
} catch (IOException e) {
e.printStackTrace();
}
String[] terms = new String[dictionaryMap.keySet().size()]; // get the terms from the dictionaryMap values
terms = dictionaryMap.keySet().toArray(terms);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, terms));
ListView lv = getListView();
This causes the app to load, with the terms in place, but they are in a completely obscure order. How do I get them to print in the same order they originally were in?
The problem is that a normal HashMap does not guarantee the order. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Try using a LinkedHashMap, it will maintain the insertion order.
From the documentation - Hash table and linked list implementation of the Map interface, with predictable iteration order
Here is a link to the docs - http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

Android sharedpreferences into arraylist

I created a simple game. At the end the user's name and score is supposed to get into a highscore list. For this i would like to store these data in sharedpreferences. I saw a post and i am trying to apply it to my app but it force closes. I don't even know if this is the right thing i am doing. So i put these keypairs (player, score) into an arraylist. From there i can get the values out into a listview.
This is just an example.
SharedPreferences.Editor scoreEditor = myScores.edit();
scoreEditor.putString("PLAYER", "Thomas");
scoreEditor.putString("SCORE", "5");
scoreEditor.commit();
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
Map<String, ?> items = myScores.getAll();
for(String s : items.keySet()){
HashMap<String,String> hmap = new HashMap<String,String>();
hmap.put("PLAYER", s);
hmap.put("SCORE", items.get(s).toString());
LIST.add(hmap);
}
Toast.makeText(Start.this, "LIST size: "+LIST.size(), Toast.LENGTH_LONG).show();
For me it would also be okay if i store these data like this:
scoreEditor.putString("DATA", "Thomas" + "-" + "5");
and put that into ArrayList<String> LIST = new ArrayList<String>();
but i don't know how to do it.
Could you guys help me with this?
Edit: So i could go another way as Haphazard suggested. I put together this code, but i don't know if this is the way to do it. I haven't tested it yet, as sg is wrong with the sharedpreferences and i am still trying to figure it out.
SharedPreferences.Editor scoreEditor = myScores.edit();
scoreEditor.putString("DATA", "Thomas" + "-" + "5");
scoreEditor.commit();
HashSet<String> hset=new HashSet<String>();
hset.addAll((Collection<? extends String>) myScores.getAll());
ArrayList<String> LIST = new ArrayList<String>(hset);
The SharedPreferences Editor does not accept Lists but it does accept Sets. You could convert your List into a HashSet or something similar and store it like that. When your read it back, convert it into an ArrayList, sort it if needed and you're good to go.
Please note that the Set has to be a set of Strings so you will have to stick with your "Thomas" + "-" + "5" setup.
Edit: To your new update, I was thinking more of something like
//Retrieve the values
Set<String> set = new HashSet<String>();
set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
That code is untested, but it should work
EDIT: If your API level is below the get/setStringSet() level then you can try this:
1) Turn your list of high scores into a delimited string. That means if you had ["Tom, 1", "Ed, 5"] you could loop through it and turn it into a String like "Tom, 1|Ed, 5". You can easily store that using setString(..).
2) When you want to read the values back, perform a getString(..) and then String.split("|") to get the original list back. Well, it returns an array but that can be converted to a list easily enough.

Categories

Resources