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
Related
I use SimpleExpandableListAdapter to create ExpandableListView for my application. I want to know better how to work with lists and maps and what they are in practice.
//collection for elements of a single group;
ArrayList<Map<String, String>> childDataItem;
//general collection for collections of elements
ArrayList<ArrayList<Map<String, String>>> childData;
Map<String, String> m;
I know how to iterate over ArrayList of Maps, it is not a problem for me, but I got stuck.
childData = new ArrayList<>();
childDataItem = new ArrayList<>();
for (String phone : phonesHTC) {
m = new HashMap<>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
childDataItem = new ArrayList<>();
for (String phone : phonesSams) {
m = new HashMap<String, String>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
// создаем коллекцию элементов для третьей группы
childDataItem = new ArrayList<>();
for (String phone : phonesLG) {
m = new HashMap<String, String>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
And I want to Log what childData contains (<ArrayList<Map<String, String>>), but I don't sure that I did that right. ( 2nd loop is a simple ArrayList of Map iteration)
for (ArrayList<Map<String, String>> outerEntry : childData) {
for(Map<String, String> i:outerEntry ) {
for (String key1 : i.keySet()) {
String value1 = i.get(key1);
Log.d("MyLogs", "(childData)value1 = " + value1);
Log.d("MyLogs", "(childData)key = " + key1);
}
}
for (Map<String, String> innerEntry : childDataItem) {
for (String key : innerEntry.keySet()) {
String value = innerEntry.get(key);
Log.d("MyLogs", "(childDataItem)key = " + key);
Log.d("MyLogs", "(childDataItem)value = " + value);
}
}
}
If you want to log all the elements for childData then there is no need for the last loop, you are already fetching them in the first loop. Please remove below code from the program and it will log all items of childData.
for (Map<String, String> innerEntry : childDataItem) {
for (String key : innerEntry.keySet()) {
String value = innerEntry.get(key);
Log.d("MyLogs", "(childDataItem)key = " + key);
Log.d("MyLogs", "(childDataItem)value = " + value);
}
}
Above loop is iterating over childDataItem and you are using the same reference again and again in your code so in this case above loop will contain only most recent map items.
For simplicity, I changed your log statements to sysout and here's the example and output:
ArrayList<Map<String, String>> childDataItem;
//general collection for collections of elements
ArrayList<ArrayList<Map<String, String>>> childData;
Map<String, String> m;
childData = new ArrayList<>();
childDataItem = new ArrayList<>();
m = new HashMap<>();
m.put("phoneName", "HTC");
m.put("phoneName1", "HTC1");
childDataItem.add(m);
childData.add(childDataItem);
childDataItem = new ArrayList<>();
m = new HashMap<String, String>();
m.put("phoneName", "Samsung");
childDataItem.add(m);
childData.add(childDataItem);
// создаем коллекцию элементов для третьей группы
childDataItem = new ArrayList<>();
m = new HashMap<String, String>();
m.put("phoneName", "LG");
childDataItem.add(m);
childData.add(childDataItem);
for (ArrayList<Map<String, String>> outerEntry : childData) {
for(Map<String, String> i:outerEntry ) {
for (String key1 : i.keySet()) {
String value1 = i.get(key1);
System.out.println("MyLogs (childData)value1 = " + value1);
System.out.println("MyLogs (childData)key = " + key1);
}
}
}
Output
MyLogs (childData)value1 = HTC1
MyLogs (childData)key = phoneName1
MyLogs (childData)value1 = HTC
MyLogs (childData)key = phoneName
MyLogs (childData)value1 = Samsung
MyLogs (childData)key = phoneName
MyLogs (childData)value1 = LG
MyLogs (childData)key = phoneName
So as you probably know, an array list is just a sequential store of data objects. And a map is a key-value pair mapping where the key is used as the lookup and must be unique. That is to say in a Map you may have many duplicate values but only one key.
As for iterating over a Map you can use an entry set which makes it a little easier. So if you wanted to iterate over an object of type <ArrayList<Map<String, String>> it would look something like this for your childDataItem class.
for(Map<String, String> map : childDataItem){
//Take each map we have in the list and iterate over the keys + values
for(Map.Entry<String, String> entry : map){
String key = entry.getKey(), value = entry.getValue();
}
}
And in your other case, the example is the same except you have another layer of array list.
for(List<Map<String, String>> childDataItemList : childData){
for(Map<String, String> map : childDataItemList){
//Take each map we have in the list and iterate over the keys + values
for(Map.Entry<String, String> entry : map){
String key = entry.getKey(), value = entry.getValue();
}
}
}
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
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()
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
}
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;
}