How to get the keys from ContentValues? - java

My ContentValues object has string keys, and I would like to get a String[] result having all the keys in it?
How do I iterate a ContentValues object?
EDIT 1
After getting two responses I came up with this, do you see problems with it?
ArrayList<String> ar = new ArrayList<String>();
ContentValues cv=data;
Set<Entry<String, Object>> s=cv.valueSet();
for (Entry<String, Object> entry : s) {
ar.add(entry.getKey());
}
String[] projection=new String[ar.size()];
ar.toArray(projection);

Try this code. Just pass your ContentValues into the method.
public void printContentValues(ContentValues vals)
{
Set<Entry<String, Object>> s=vals.valueSet();
Iterator itr = s.iterator();
Log.d("DatabaseSync", "ContentValue Length :: " +vals.size());
while(itr.hasNext())
{
Map.Entry me = (Map.Entry)itr.next();
String key = me.getKey().toString();
Object value = me.getValue();
Log.d("DatabaseSync", "Key:"+key+", values:"+(String)(value == null?null:value.toString()));
}
}

According to the doc, the "valueSet()" method returns a set of all keys and values. You can then use an iterator on the resultant Set and getKey() on each of the iterated Entry elements to collect into a String array.

You can try this one also:
String ar [] = {};
ContentValues cv=new ContentValues();
int i=0;
for(String key: cv.keySet()){
ar[i] = key;
}

Related

java.util.ConcurrentModificationException, but I'm iterating over a copy, not the collection I'm modifying

Please read the description of my problem before marking duplicate.
private void cleanTrash() {
HashMap<String, OutfitInfo> tempOutfits = outfits;
Iterator iter = tempOutfits.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapElement = (Map.Entry) iter.next();
String key = (String) mapElement.getKey();
OutfitInfo info = (OutfitInfo) mapElement.getValue();
if (info.getParentID().equals(trashID)) {
outfits.remove(key);
}
}
HashMap<String, ItemInfo> tempItems = items;
iter = tempItems.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapElement = (Map.Entry) iter.next();
String key = (String) mapElement.getKey();
ItemInfo info = (ItemInfo) mapElement.getValue();
if (info.getParentID().equals(trashID)) {
items.remove(key);
}
}
}
In the above code I am getting the concurrent modification exception. I understand that this error means that I can't modify a collection while I'm iterating over it. HOWEVER, I made a copy of the collection before assigning the iterator, and the collection being modified is not the one that's being iterated over. So why am I still getting this message, and how do I fix it?
HashMap<String, OutfitInfo> tempOutfits = outfits; does not create a copy. Both varaibles tempOutfits and outfits point to the same instance.
If you actually want to copy you can do:
HashMap<String, OutfitInfo> tempOutfits = new HashMap<>(outfits);
This line creates a new HashMap and initializes it with the content of outfits
As you already have the Iterator, instead of removing the entry directly from the collection. Call iterator.remove(); to remove the item the iterator currently references. No need to copy the collection.
So:
private void cleanTrash() {
Iterator iter = outfits.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapElement = (Map.Entry) iter.next();
String key = (String) mapElement.getKey();
OutfitInfo info = (OutfitInfo) mapElement.getValue();
if (info.getParentID().equals(trashID)) {
iter.remove();
}
}
iter = items.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapElement = (Map.Entry) iter.next();
String key = (String) mapElement.getKey();
ItemInfo info = (ItemInfo) mapElement.getValue();
if (info.getParentID().equals(trashID)) {
iter.remove();
}
}
}
You can use clone() to create a copy of the HashMap, clone()#Oracle doc
Map<String, String> copy = (Map<String, String>) outfits.clone();
public static void main(String[] args) {
HashMap<String, String> outfits = new HashMap<>(Map.of("1", "11", "2", "22"));
Map<String, String> copy = (Map<String, String>) outfits.clone();
Iterator<Entry<String, String>> iterator = copy.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> next = iterator.next();
if (next.getKey().equals("1"))
outfits.remove(next.getKey());
}
}

Java - passing in a list of string to a hashmap's value

I am trying to set a hashmap to have key as string and a list array as value. Is it possible? and how do I set the list into the value?
HashMap<String, List<String>> foo = new HashMap<String, List<String>>();
foo.put("key1",{"key1_value1","key1_value2"});
You can do the following
Map<String, List<String>> foo = new HashMap<String, List<String>>();
List<String> list = new ArrayList<String>();
list.add("key1_value1");
list.add("key1_value2");
foo.put("key1",list);
foo.put("key", Arrays.asList("key1_val1", "key1_val2"));
You have to use a data structure like ArrayList or just an array maybe to represent the list of strings as value.
You can use the following with a List;
foo.put("key", Arrays.asList("key1_val1", "key1_val2"));
where foo is of type Map<String, List<String>>
Or you the following with an array;
foo.put("key", new String[]{"key1_val1", "key1_val2"});
where foo is of type Map<String, String[]>
Map<String, List<String>> foo = new HashMap<String, List<String>>();
List<String> list = new ArrayList<String>();
list.add("value1");
list.add("value2");
foo.put("key1", list);
for (Entry<String, List<String>> entry : foo.entrySet()) {
String key = entry.getKey();
List<String> valueList = entry.getValue();
System.out.println("key = " + key);
for (String value : valueList) {
System.out.println("value = " + value);
}
}
Output
key = key1
value = value1
value = value2

java assign map each value into an String array

I want to save data into master - details table.First portion is for master table and last portion is for details table.I have got java.lang.String cannot be cast to [Ljava.lang.String .How to recover from this problem.How to assign map.get("step_id[]") into a string array String[] WfIds. I want to assign each value into distinct string array.
Controller Code
Map<String,Object> wfManager = new HashMap<String,Object>();
//************************Master data sent from view******************************//
wfManager.put("workflow_code",(request.getParameter("workflow_code")).toUpperCase());
wfManager.put("workflow_name",request.getParameter("workflow_name"));
wfManager.put("workflow_descr",request.getParameter("workflow_descr"));
wfManager.put("object_type_code",request.getParameter("object_type_code"));
//*********************Detail item data sent from view********************************//
wfManager.put("wf_block_id[]", request.getParameter("wf_block_id[]"));
wfManager.put("step_code[]" , request.getParameter("step_code[]"));
wfManager.put("step_name[]", request.getParameter("step_name[]"));
wfManager.put("doa_type_code[]", request.getParameter("doa_type_code[]"));
wfManager.put("doa_type_name[]", request.getParameter("doa_type_name[]"));
Service Code
public Map<String, String> insert(Map<String, Object> map) {
//************************Master data sent from view******************************//
Map<String, String> data = new HashMap<String, String>();
Workflow wf = new Workflow();
wf.setWorkflowCode((String)map.get("workflow_code"));
wf.setWorkflowName((String)map.get("workflow_name"));
wf.setWorkflowDescr((String)map.get("workflow_descr"));
wf.setObjectTypeCode((String)map.get("object_type_code"));
String[] WfIds = (String[]) map.get("step_id[]");
String[] wfBlockIds = (String[]) map.get("wf_block_id[]");
String[] wfsCodes = (String[]) map.get("step_code[]");
String[] stepNames = (String[]) map.get("step_name[]");
String[] doaTypeCodes = (String[]) map.get("doa_type_code[]");
String[] doaTypeNames = (String[]) map.get("doa_type_name[]");
List<WorkflowDetails> wfDetailsList = new ArrayList<WorkflowDetails>();
for(int i = 0; i< wfsCodes.length; i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails.setWorkflowCode(wf.getWorkflowCode());
wfDetails.setWorkflowName(wf.getWorkflowName());
wfDetails.setWorkflowDescr(wf.getWorkflowDescr());
wfDetails.setWorkflowObjectTypeCode(wf.getObjectTypeCode());
wfDetails.setWorkflowObjectTypeName(wf.getObjectTypeName());
wfDetailsList.add(i,wfDetails);
}
wf.setSteps(wfDetailsList);
id = workflowManagerDAO.insertDoc(wf);
data.put("id", id);
return data;
}
Code for DAO:
#Transactional
#Override
public String insertDoc(Workflow wfManager) {
for(int i = 0; i < wfManager.getSteps().size(); i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails = wfManager.getSteps().get(i);
sessionfactory.getCurrentSession().save(wfDetails);
sessionfactory.getCurrentSession().flush();
}
String id = (String) sessionfactory.getCurrentSession().save(wfManager);
sessionfactory.getCurrentSession().flush();
return id;
}
If you absolutely need to use request.getParameter(), you will have to convert your arrays to strings using a delimiter character, e.g. convert this
String[] array = { "John", "Peter", "Paul" };
to this
String plainTextArray = "John#Peter#Paul";
Then you will be able to pass you array values as String (the only type that getParameter() understands).
You can then restore them like this
String[] restoredArray = request.getParameter("plainTextArray").split("#");
Maybe you want to have a look at setAttribute() and getAttribute() which let you store any objects (including arrays). You can start here Difference between getAttribute() and getParameter()

How to get the keys from a LinkedHasMap?

I have a code populating a listView:
JSONArray data = responseData.getJSONArray("data");
String[] values = new String[data.length()];//I wanna get rid of this
LinkedHashMap<String, String> helpData = new LinkedHashMap();
for (int i = 0; i < data.length() ; i++) {
String header = data.getJSONObject(i).getString("glossary_header");
String description = data.getJSONObject(i).getString("gloassary_description");
helpData.put(header, description);
values[i] = header;
Log.d("mylog", "counter" + i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
I want to pass the keys to Arrayadapter, I was hoping to find a getKeys() method that could magically return an array of key from the map.
KeySet() was close but did not work, what is the proper way to do this. I don't want to use string array. I want to have my pair values together.
You can get like this
Collection<String> values = helpData.keySet();
for (String string : values) {
//
}
Set<String> keys = myArray.keySet();
String[] keysAsArray = keys.toArray(new String[0]);
More detail on the toArray method can be found at http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray(T[])
for (final String key : helpData.keySet()) {
// print data...
}
or
final Iterator<String> cursor = helpData.keySet().iterator();
while (cursor.hasNext()) {
final String key = cursor.next();
// Print data
}

I could not cast integer values to string

Query query = s.createQuery("from ClientList");
List <String> results = query.list();
Iterator<String> it = results.iterator();
while(it.hasNext())
{
Object[] row = (Object[]) it.next();
System.out.println("ReturnValues==========" + results);
Map<String, String> jsonObject = new HashMap<String, String>();
jsonObject.put("Record_Id", (String) row[0]);
jsonObject.put("Client_Code", (String)row[1]);
jsonObject.put("Client_Description", (String)row[2]);
returnValues.add(jsonObject);
}
The first column of my table contains an integer value. I'm getting this error message:
Exception===java.lang.ClassCastException: cannot be cast to [Ljava.lang.Object;
Your itetator returns a string. You can't cast it to an array of object.
There is a split method in string, it splits your string by given regex and returns a String[] containing the split parts.
Since you provided no more information on that, I'm going to assume that the data in your row is separated by spaces.
String row = ll.next() // I assume row = "1234 5678 Description_No_Spaces"
String[] data = row.split("\\s+");
String record_Id = data[0];
You don't need an iterator, you can loop through results with foreach loop.
List <String> results =query.list();
for(String result: results) {
String[] row = /* user result.split(...) to get attributes*/
System.out.println("ReturnValues=========="+results);
Map<String, String> JSonObject=new HashMap<String, String>();
JSonObject.put("Record_Id", row[0]);
JSonObject.put("Client_Code", row[1]);
JSonObject.put("Client_Description",row[2]);
ReturnValues.add(JSonObject);
}
Check out String.split(String regex) docs.
Query query = s.createQuery("from ClientList");
List <String> results = query.list();
Iterator<String> it = results.iterator();
while(it.hasNext())`enter code here`
{
Object[] row = (Object[]) it.next();
System.out.println("ReturnValues==========" + results);
Map<String, String> jsonObject = new HashMap<String, String>();
jsonObject.put("Record_Id", String.valueOf(row[0]));
jsonObject.put("Client_Code", row[1]);
jsonObject.put("Client_Description", row[2]);
returnValues.add(jsonObject);
}
Hope this solves your problem

Categories

Resources