How to use Dictionary (like iphone NSDictionary) in android? - android

I have worked in soap message, and to parse the value from Webservice, the values are stored in ArrayList.
Example:
values are Employee name (Siva) and Employee id (3433fd), these two values are stored in arraylist, but I want to stored in Dictionary, How?

you can use HashMap like this
Map <String,String> map = new HashMap<String,String>();
//add items
map.put("3433fd","Siva");
//get items
String employeeName =(String) map.get("3433fd");

You can use Bundle.
as it offers String to various types of Mapping.
Bundle b = new Bundle();
b.putInt("identifier", 121);
b.putString("identifier", "Any String");
b.putStringArray("identifier", stringArray);
int i = b.getInt("identifier");
...

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText textview = (EditText) findViewById(R.id.editTextHash);
EditText textviewNew = (EditText) findViewById(R.id.editTextHash2);
Map<String, String> map = new HashMap<String,String>();
map.put("iOS", "100");
map.put("Android", "101");
map.put("Java", "102");
map.put(".Net", "103");
String TextString = "";
// Set<E> keys = map.keySet();
Set keys = map.keySet();
System.out.println("keys "+keys);
for (Iterator i = keys.iterator(); i.hasNext();)
{
String key = (String) i.next();
System.out.println("key "+key);
String value = (String) map.get(key);
System.out.println("value "+value);
textview.append(key + " = " + value);
TextString+=(key + " = " + value);
}
//textviewNew.setText(TextString);
// Iterator iterator = map.keySet().iterator();
//
// while (iterator.hasNext())
// {
// String object = (String) iterator.next();
// textview.setText(object);
// }
//
// //textview.setText(map.get("Siva"));
//
// System.out.println(map);
}
}

A Dictionary is an abstract class that maps keys to values and there is Dictionary Class in android refer link you can find a note at Class Overview
Do not use this class since it is obsolete. Please use the Map
interface for new implementations.
An attempt to insert either a null key or a null value to a dictionary will result to a NullPointerException,but you can use Map interface,it provides the exact same functionality of a dictionary.you can use it as bellow
//put values
Map Message = new HashMap();
Message.put("title", "Test message");
Message.put("description", "message description");
Message.put("email", "email#gmail.com");
//get values
Log.d("get Message","Message title -"+Message.get("title"));
you can also use A custom class as below
public class MessageObject {
String title;
String description;
String email;
}
you can use Getters and Setters to get and put values,not needed to remember the key names every time you may get some other advantages by this way.

Related

Android: Set edittext with arraylistvalue

Hi i am converting from kilo to stone-pounds, i want to place stones in one edittext and pounds in one edittext , below is my method
public ArrayList<HashMap<String, Integer>> kiloTostomepound(int s) {
int stone = (int) (s * 2.2);
int stonevalue = stone/14;
int spound = (stone % 14);
arrayList = new ArrayList<HashMap<String,Integer>>();
HashMap<String, Integer> h1 = new HashMap<String, Integer>();
h1.put(STONE,stonevalue);
h1.put(STONEPOUND, spound);
arrayList.add(h1);
return arrayList;
}
i want to get values from the arryalist and set it to edittext.
Doing a below but givinf nullpointerexception
edt2.setText(String.valueOf(kiloTostomepound(arrayList.get(0).get(STONE))));
edt3.setText(String.valueOf(kiloTostomepound(arrayList.get(1).get(STONEPOUND))));
The below code traverses through the list and prints key and value.
for (int a =0; a<myList.size();a++)
{
HashMap<String, Integer> tmpData = (HashMap<String, Integer>) myList.get(a);
Set<String> key = tmpData.keySet();
Iterator it = key.iterator();
while (it.hasNext()) {
String hmKey = (String)it.next();
Integer hmData = (Integer) tmpData.get(hmKey);
System.out.println("Key: "+hmKey +" & Data: "+hmData);
it.remove(); // avoids a ConcurrentModificationException
}
}
So if you need the first value try following.
HashMap<String, Integer> tmpData = (HashMap<String, Integer>) myList.get(0);
Set<String> key = tmpData.keySet();
Iterator it = key.iterator();
// Get the first element
String hmKey = (String)it.next();
Integer hmData = (Integer) tmpData.get(hmKey);
// Set the key and value to Edit text
edt2.setText(hmKey+" "+hmData);
Seems like your assigning the value to the arrayList variable inside of the method. Hence the
kiloTostomepound(arrayList.get(0).get(STONE))
Will throw a nullpointer for arrayList.
If I understand your code correctly, the below code should do the trick. But I don't know the input for the kiloTostomepound method.
edt2.setText(String.valueOf(kiloTostomepound("INPUT TO METHOD").get(0).get(STONE)));
edt3.setText(String.valueOf(kiloTostomepound("INPUT TO METHOD").get(1).get(STONEPOUND)));
This is because your method returns the arrayList with the hashmaps inside.

Appwarp Android Programming get Property from Room List Activity

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.

how to extract contents of sharedpreference (string array)

I have this arraylist hashmap
tasklist = new ArrayList>();
then I store its contents to a preference
temp = new HashMap<String, String>();
temp.put("action", spinnerAction.getSelectedItem().toString());
temp.put("task", spinnerCourse.getSelectedItem().toString() + ": " + spinnerChapter.getSelectedItem().toString());
tasklist.add(temp);
adapterShowTask.notifyDataSetChanged();
editor.putString("taskpref", tasklist.toString());
editor.commit();
here is how I retrieve it:
String storedCollection = sPrefs.getString("taskpref", "");
the contents of storedCollection looks like this:
["{action= some text, task= some text}", "{action= some text 2, task= some text 2 }" ]
My question is, how do I retrieve the specific string (Action and task) and load it again to the arraylist hashmap?
That's the JsonString you need to get using jsonparser,I suggested you to learn How to parse the String json,There is been a lot of great tutorial online
String storedCollection = sPrefs.getString("taskpref", "");
JSONArray jarray=new JSONArray(stroredCollection);
ArrayList<String> action=new ArrayList<String>();
ArrayList<String> task=new ArrayList<String>();
for(i=0;i<jarray.length();i++){
String action=jarray.getJSONObject(i).getString("action");
String task=jarray.getJSONObject(i).getString("task");
}

Intent.EXTRA_SUBJECT multiple values in Android

I want to display multiple values in the text message body, however the following code below display no body message even when the textArray has values. Is there any way of adding values to a body of an email through a loop?
public void onClick(View v) {
// TODO Auto-generated method stub
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Example");
int sizeOfArray = list.size();
String textArray [] = new String[sizeOfArray];
for(int i = 0;sizeOfArray > i;i++)
{
HashMap<String, String> arrayString = list.get(i);
String user = arrayString.get("user");
String book = arrayString.get("book");
textArray[i] = user + " - " + book;
}
sharingIntent.putExtra(Intent.EXTRA_TEXT, textArray);
startActivity(Intent.createChooser(sharingIntent,"Share using"));
}
});
It's difficult to get proper documentation on what Intent Receivers are expecting as extra values, but I'm pretty sure you need to pass a String and not a String[] to putExtra, since the Receiver will anyway end up converting the value to a String, so better to control that.
Thats being said, your implementation of the loop is weird. Do you really have a list of HashMap<String, String>as input ?
I would do :
StringBuffer sb = new StringBuffer();
for(HashMap<String, String> item: list){
String user = item.get("user");
String book = item.get("book");
sb.append(user + " - " + book+", ");
}
String value = sb.substring(0, Math.max(0,sb.length()-2));
Intent.EXTRA_TEXT expects CharSequence according to the documentation:
http://developer.android.com/reference/android/content/Intent.html#EXTRA_TEXT
I would guess as you are passing in an array, the receiving activity doesn't know what to do with it and just skips over it.
Trying joining your array values and passing them in as a String.
String arg = org.apache.commons.lang.StringUtils.join (textArray, '\n');
sharingIntent.putExtra(Intent.EXTRA_TEXT, arg);

HashMap and ArrayList confusion in retrieval

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

Categories

Resources