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()
Related
I am trying to add Objects from MySQL database on ArrayList Object but result gives me only one row
i am using custom adapter on my ListView, i think i could use loop multiple objects to ArrayList object but i failed , please help me,
my code :
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Looks like you are creating an ArrayList everytime you parse an object. If I understand correctly, your code should be something like that:
// ArrayList will be created only once for a json response.
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
//Now parse add all elements in json response and add to list.
for(all items in your jsonResponse List ) {
//Parse fields from json object
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
//create object
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
//Now list will have all the items, Add this list to adapter.
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<>(getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Suppose Your Server gives a result in JSONArray say response as a String Try the following
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
JSONArray jsonArray = new JSONArray(response);
int size = jsonArray.length();
if (size > 0)
{
for (int i = 0; i < size; i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
You must use JSONArray for getting list of items from JSON. And then populate your ArrayList with them and pass to your adapter.
I have a pojo class named "Performance" like this
public class Performance {
String productId;
String productBrand;
String productGraph;
//getters and setters
And I saved it to arraylist named "performanceList" like this:
JSONArray dataGraph=null;
JSONObject obj = new JSONObject(response);
dataGraph = obj.getJSONArray("product_list");
performanceList.clear();
for(int i=0;i<dataGraph.length(); i++){
JSONObject jsonObject = dataGraph.getJSONObject(i);
Performance performance = new Performance();
if(!jsonObject.isNull("id")){
performance.setProductId(jsonObject.getString("id"));
}
if(!jsonObject.isNull("brand")) {
performance.setProductBrand(jsonObject.getString("brand"));
}
if(!jsonObject.isNull("sales")){
performance.setProductGraph(jsonObject.getString("sales"));
}
performanceList.add(i, performance);
}
And now, can you please help me fetch the data from arraylist and be converted into array just like this
String []brand = {/*getProductBrand from arraylist*/};
String []id = {/*getProductId from arraylist*/};
String []id = {/*getProductGraph from arraylist*/};
Use foreach or for loop
String[] brand = new String[performanceList.size()];
for(int i=0;i<performanceList.size();i++)
{
brand[i] = performanceList.get(i).getBrand();
.....
......
}
Similary for other fields as well.
you could use stream.map() in java8
List<String> productBrands = performanceList
.stream()
.map(el-> el.getProductBrand())
.collect(Collectors.toList());
repeat same for el.getId() or any other data you need to collect from Performance objects
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
}
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
I'm using a simple php API (that I wrote) that returns a JSON formatted string such as:
[["Air Fortress","5639"],["Altered Beast","6091"],["American Gladiators","6024"],["Bases Loaded II: Second Season","5975"],["Battle Tank","5944"]]
I now have a String that contains the JSON formatted string but need to convert it into two String arrays, one for name and one for id. Are there any quick paths to accomplishing this?
You can use the org.json library to convert your json string to a JSONArray which you can then iterate over.
For example:
String jsonString = "[[\"Air Fortress\",\"5639\"],[\"Altered Beast\",\"6091\"],[\"American Gladiators\",\"6024\"],[\"Bases Loaded II: Second Season\",\"5975\"],[\"Battle Tank\",\"5944\"]]";
List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
JSONArray array = new JSONArray(jsonString);
for(int i = 0 ; i < array.length(); i++){
JSONArray subArray = (JSONArray)array.get(i);
String name = (String)subArray.get(0);
names.add(name);
String id = (String)subArray.get(1);
ids.add(id);
}
//to convert the lists to arrays
String[] nameArray = names.toArray(new String[0]);
String[] idArray = ids.toArray(new String[0]);
You can even use a regex to get the job done, although its much better to use a json library to parse json:
List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
Pattern p = Pattern.compile("\"(.*?)\",\"(.*?)\"") ;
Matcher m = p.matcher(s);
while(m.find()){
names.add(m.group(1));
ids.add(m.group(2));
}