I want to call JasperFillManager.fillReport(filePath+".jasper", param, con); where param is supposed to accept type Map. is there any solution
4 Answers
Simply use the constructor taking another map as an argument:
Map<String, Object> map2 = new HashMap<String, Object>(map);
See this example:
import java.util.HashMap;
import java.util.Map;
public class Test5 {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("1", 1);
Map<String, Object> map2 = new HashMap<String, Object>(map);
// etc...
}
}
Comments
If you have a HashMap<String,Integer> and you need to convert it to a HashMap<String,Object>, then the following should work:
HashMap<String, Object> objParams = new HashMap<String, Object>();
for (String key : intParams.keyValues()) {
Integer intValue = intParams.get(key);
objParams.put(key, intValue);
}
Where the intParams is your HashMap<String,Integer>.
There might be some typos in there as this is purely off the cuff.
Then you can pass the objParams to fillReport.
1 Comment
Guillaume Polet
When iterating over a Map, consider iterating over the entrySet() instead of the keySet(). It is much more efficient as it does not requires the hashCode() and equals() methods of the key to be evaluate everytime to find the corresponding value.
Your .java file
String url="jdbc:mysql://127.0.0.1:3306/database";
String username="root";
String password="";
String database="database";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url, username, password);
JasperReport jc=JasperCompileManager.compileReport("F:\\pro\\report.jrxml"); //give your report.jrxml file path
//create hashmap to send data to report.key should same to report parameter
HashMap para = new HashMap();
para .put("name", "chamod");
para .put("email", "[email protected]");
JasperPrint print = JasperFillManager.fillReport(jc,para,new JREmptyDataSource());
JasperViewer.viewReport(print);
con.close();
Your report.jrxml file text fields should be like this
<textFieldExpression class="java.lang.String"><![CDATA[$P{name}]]></textFieldExpression>
<textFieldExpression class="java.lang.String"><![CDATA[$P{email}]]></textFieldExpression>
HashMap<String,Integer>that you want to pass tofillReport?