Empty page using sendIntent.putExtras(bundle), page not filled Android studio - javascript

I'm trying to send some stuff via mail or Bluetooth etc but not working very well.
I would like to see a text like this:
" Respiration Rate: 0 2.0 5.0 16.0 "...
To do that I've implemented a button and Resut.java stuff. When I try to click on the button and I choose e-mail, app open a mail and the text is only "Respiration Rate"
here click-button:
SRR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bundle bundle = new Bundle();
bundle.putDoubleArray("TryThis",plot_array);
sendIntent.putExtras(bundle);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " );
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
result.java:
package com.google.android.gms.samples.vision.face.rPPG;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.PointsGraphSeries;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class RespirationResult extends AppCompatActivity {
private String Date;
int RR;
int il_risultato;
double [] plot_array;
int[] intArray;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
java.util.Date today = Calendar.getInstance().getTime();
private String[] RRtoSent=new String[300];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_respiration_result);
Date = df.format(today);
TextView RRR = (TextView) this.findViewById(R.id.RRR);
ImageButton SRR = (ImageButton)this.findViewById(R.id.SendRR);
//-------------------------------------------------------------------------risutato
Bundle b = getIntent().getExtras();
double result = b.getDouble("key");
plot_array=b.getDoubleArray("array");
il_risultato=(int) Math.round(result);
RRR.setText(String.valueOf(il_risultato)); //prima era RR, da mettere successivamente
RRtoSent = new String[plot_array.length];
for (int i = 0; i < RRtoSent.length; i++) {
RRtoSent[i] = String.valueOf(plot_array[i]);
}
//grafico
GraphView graph;
LineGraphSeries<DataPoint> series; //an Object of the PointsGraphSeries for plotting scatter graphs
graph = (GraphView) findViewById(R.id.graphico);
series= new LineGraphSeries<>(data()); //initializing/defining series to get the data from the method 'data()'
graph.addSeries(series); //adding the series to the GraphView
//series.setShape(PointsGraphSeries.Shape.POINT);
// activate horizontal and vertical zooming and scrolling
graph.getViewport().setScalableY(true);
graph.getGridLabelRenderer().setGridColor(Color.DKGRAY);
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.DKGRAY);
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.DKGRAY);
// graph.setTitle("Respiration Rate/min");
graph.getGridLabelRenderer().setHorizontalAxisTitle("time(sec)");
graph.getGridLabelRenderer().setVerticalAxisTitle("RR");
// set manual X bounds
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0.5);
graph.getViewport().setMaxX(100);
SRR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bundle bundle = new Bundle();
bundle.putDoubleArray("TryThis",plot_array);
sendIntent.putExtras(bundle);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " );
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
}
public DataPoint[] data(){
DataPoint[] values = new DataPoint[plot_array.length]; //creating an object of type DataPoint[] of size 'n'
for(int i=0;i<plot_array.length;i++){
DataPoint v = new DataPoint(i,plot_array[i]);
values[i] = v;
}
return values;
}
#Override
public void onBackPressed() {
Intent i = new Intent(RespirationResult.this, SplashScreen.class);
startActivity(i);
finish();
super.onBackPressed();
}
}
Does anyone have an idea about it?
what's wrong or missing?
Thanks in advance

From Android official site:
public static final String EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent. Note that this may
be a styled CharSequence, so you must use Bundle.getCharSequence() to
retrieve it.
So you should convert your double array to String first before calling email app.
Step 1: Write a method which convert a double array to a string.
private String convertDoubleArrayToString(double[] array) {
StringBuilder sb = new StringBuilder();
for (double number: array) {
sb.append(number).append(" ");
}
return sb.toString();
}
Step 2: Change your code to
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " + convertDoubleArrayToString(plot_array));
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));

That's because all you want to show must be part of the EXTRA_TEXT:
sendIntent.putExtra(Intent.EXTRA_TEXT, "EVERYTHING YOU WANT TO PRINT HERE" );
So you have to build a string with your data, then you create the extra with the complete string.

Related

Print multiple texts from multiple elements with same class name

Im trying to print all the product names from an e commerce website in selenium using java but its printing only the first name of the product from the first class it finds. How to print all the product names from all the classes with same class name?
This is my code:
package introduction;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Getproductnames {
private static int i;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:/Temp/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.get("https://www.fipola.in/chicken");
driver.findElement(By.id("DelLocation")).sendKeys("600020");
driver.findElement(By.className("top_pincode_select")).click();
Thread.sleep(3000);
List<WebElement> products=driver.findElements(By.cssSelector("a.product-item-link"));
for(int i=0; i<products.size(); i++);
{
String[] names = new String[]{products.get(i).getText()};
System.out.println(names[i] + "");
}
}
}
You can use the below to print all the products name
List<WebElement> products=driver.findElements(By.cssSelector("a.product-item-link"));
for(int i =0;i<products.size();i++) {
String elementText = products.get(i).getText();
System.out.println(elementText);
}

how to send base64 string in android?

I am trying to make hydrid application in which there is a "button" on HTML page .whenever I click on that button i want to call android code function (which is working fine when I called test function from javascript) .Now I want to capture image on button click
I take help from below url.
Capture Image from Camera and Display in Activity
I do like this
package com.example.myapp.myapplication;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webview);
// webView.loadUrl("http://1.5.20.97:3671");
webView.loadUrl("http://15.16.74.160:6019");
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.addJavascriptInterface(jsInterface, "JSInterface");
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
// Log.d("My map",photo,"");
}
}
public void checkTest(){
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
}
class JavaScriptInterface {
private MainActivity activity;
public JavaScriptInterface(MainActivity activity) {
this.activity = activity;
}
#JavascriptInterface
public void test() {
this.activity.checkTest();
}
#JavascriptInterface
public String bitMapToBase64()
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//add support for jpg and more.
bitMap.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
}
I am getting import error
I am trying to call a android function which open camera and capture image and return to javascript.
on javascript I am calling function like this
console.log(window.JSInterface.test())
So to go back to your webView when you capture the image from camera, change your onActivityResult method to this
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
if (webView != null)
webView.loadUrl("http://125.16.74.160:30019");
}
}
Also you should declare you bitmap as a global static variable like this
public static Bitmap photo;
Then bitMapToBase64 become like this
#JavascriptInterface
public String bitMapToBase64()
{
if (MainActivity.photo != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//add support for jpg and more.
MainActivity.photo.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
return "null image";
}
In the javascript side you check if bitMapToBase64 function has a return value different than "null image" you convert the base64 image to a blob or image object and show it in a div for example.
Here is an example how to convert your base64 string to an image object and append it to your body
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

Error to access a .xls file in android studio

I've a file named "question.xls". I'm trying to generate a two dimensional string array with that sheet.I've add the jxl.jar as resource library.Here's my code and problem.Here's the MainActivity.java.I've just tried to acces each cell then assigning them into two dimensional array
package com.example.bhagyo.excell;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class MainActivity extends AppCompatActivity {
String[] str;
String zz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readQuestion();
}
private void readQuestion() {
try{
AssetManager assetManager = getAssets();
InputStream inputStream = assetManager.open("question.xls");
Workbook workbook = Workbook.getWorkbook(inputStream);
Sheet sheet = workbook.getSheet(0);
int k=0;
int row = sheet.getRows();
int col = sheet.getColumns();
Log.d("Result","table details: "+row+" "+col);
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
Cell cell = sheet.getCell(j,i);
zz="";
if(j==5){
zz=zz+"Answer: "+(cell.getContents()).toString();
}
else if(j==0){
zz=(cell.getContents()).toString()+" ";
}
else{
zz=zz+" "+(cell.getContents()).toString();
}
}
str[k++]=zz;
Log.d("MyActivity","Dekhi "+zz);
}
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
}
}
My verbose log is full of empty the error is mainly caused bu null array but where is it
10-27 15:29:50.631 2719-2719/? D/Result: table details: 970 7
10-27 15:29:50.632 2719-2719/? D/AndroidRuntime: Shutting down VM
10-27 15:29:50.633 2719-2719/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bhagyo.excell, PID: 2719
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bhagyo.excell/com.example.bhagyo.excell.MainActivity}: java.lang.NullPointerException: Attempt to write to null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to write to null array
at com.example.bhagyo.excell.MainActivity.readQuestion(MainActivity.java:55)
at com.example.bhagyo.excell.MainActivity.onCreate(MainActivity.java:29)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
You haven't initialized your str array. Initialize it after you define row:
int row = sheet.getRows();
str = new String[row];
That will get rid of the NullPointerException.
However, you're not creating a 2-dimensional array, either. You're creating a single-dimensional array with each index holding a single string containing the data of the last column only.
Change your code a bit:
Change
String[] str;
To
String[][] str;
Initialize it after initializing row and col:
int row = sheet.getRows();
int col = sheet.getColumns();
str = new String[row][col];
Then change your loops a bit:
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
Cell cell = sheet.getCell(j,i);
String column;
if (j == 5) {
column = "Answer: " + cell.getContents();
} else {
column = cell.getContents().toString();
}
str[i][j] = column;
}
}

Drag and drop testing in selenium on html5 (Using java)

This is my first question ever so please go light on me. I am trying to test the drag and drop feature on HTML5 using selenium and java as my main language. However I am fully aware that it is not supported by selenium webdriver itself but there is a workaround on the stackoverflow forum where a user used a javsacript file to simulate the drag and drop action.
The link to that javascript workaround is HERE
I have tried to follow the instructions but since i am quite new to coding, I am wasting my time messing around. However, I have tried my best but now i am having problems with loading scripts. Thanks.
(Turned out that I was not correctly executing the drop.js script. The working code is below:)
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class check {
public static void main(String[] args) throws InterruptedException, IOException {
System.setProperty("webdriver.Firefox.driver", "Path_executable");
WebDriver driver= new FirefoxDriver();
driver.get("http://html5demos.com/drag#");
final String JQUERY_LOAD_SCRIPT = ("C:\\jQuerify.js");
String jQueryLoader = readFile(JQUERY_LOAD_SCRIPT);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(
jQueryLoader /* , http://localhost:8080/jquery-1.7.2.js */);
// ready to rock
js.executeScript("jQuery(function($) { " + " $('input[name=\"q\"]').val('bada-bing').closest('form').submit(); "
+ " }); ");
String filePath = "C://drop.js";
String source = "#one";
String target = "#bin";
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
while((line = br.readLine())!=null)
buffer.append(line);
String javaScript = buffer.toString();
javaScript = javaScript + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
((JavascriptExecutor)driver).executeScript(javaScript);
}
private static String readFile(String file) throws IOException {
Charset cs = Charset.forName("UTF-8");
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
stream.close();
}
}
}
My code is:-
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import javax.script.ScriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class drag {
public static void main(String[] args) throws ScriptException, NoSuchMethodException, IOException {
System.setProperty("webdriver.Firefox.driver", "Address_Executable");
WebDriver driver = new FirefoxDriver();
driver.get("http://html5demos.com/drag");
final String JQUERY_LOAD_SCRIPT = ("C:\\jQuerify.js");
String jQueryLoader = readFile(JQUERY_LOAD_SCRIPT);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(
jQueryLoader /* , http://localhost:8080/jquery-1.7.2.js */);
// ready to rock
js.executeScript("jQuery(function($) { " + " $('input[name=\"q\"]').val('bada-bing').closest('form').submit(); "
+ " }); ");
final String DROP = ("C:\\drop.js");
String scriptLoader = readFile(DROP);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js1 = (JavascriptExecutor) driver;
js1.executeScript(
scriptLoader /* , http://localhost:8080/jquery-1.7.2.js */);
((JavascriptExecutor) driver).executeScript(js1 + "$('#one').simulateDragDrop({ dropTarget: '#bin'});");
}
private static String readFile(String file) throws IOException {
Charset cs = Charset.forName("UTF-8");
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
stream.close();
}
}
}

Jasper Report : "Document has no pages"

I have a problem when I run this code. I get always this message : "Document has no pages" with a blank page in the pdf file .
Note: I'm using NetBeans IDE 7.2 Beta.
Jar files imported are:
com.lowagie.text-2.1.7.jar
commons-beanutils-1.5.jar
commons-collections-2.1.jar
commons-digester-2.1.jar
commons-javaflow.jar
commons-logging-1.3.jar
jasperreports-5.5.1.jar
javax.servlet.jar
I need your help,please.
this is my code :
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Currency;
import java.util.HashMap;
import javax.swing.JFrame;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.swing.JRViewer;
public class Report extends JFrame{
public Report(String month,int year){
try{
//load the driver
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/motor";
String user="root";
String pass="";
Connection cn=DriverManager.getConnection(url,user,pass);
System.out.println("connected in report");
PreparedStatement ps = cn.prepareStatement("select number,title,name,ikar,echtirak,price,tarakom from users order by number asc");
ResultSet rs;
rs=ps.executeQuery();
JasperPrint jasperPrint=null;
HashMap<String, Object> mapParameters = new HashMap <String, Object>();
// jrxml compiling process
JasperReport jasperReport = JasperCompileManager.compileReport("C:/Users/user/Documents/NetBeansProjects/MotorApp/MyReports/motorReport.jrxml");
int i=1;
while(rs.next()){
mapParameters.put("Name", rs.getString("title")+" "+rs.getString("name"));
mapParameters.put("Number",rs.getString("number"));
mapParameters.put("Ikar",rs.getString("ikar"));
mapParameters.put("Amperage",rs.getString("echtirak")+" A");
mapParameters.put("tarakom",rs.getString("tarakom")+" $");
mapParameters.put("monthPrice",rs.getString("price")+" $");
Integer total=Integer.parseInt(rs.getString("price"))+Integer.parseInt(rs.getString("tarakom"));
mapParameters.put("totalPrice",total+" $");
mapParameters.put("monthYear",year+" "+month);
try{
System.out.println("Filling report...");
jasperPrint = JasperFillManager.fillReport(jasperReport, mapParameters,cn);
JRViewer viewer = new JRViewer(jasperPrint);
System.out.println("Done!");
JasperExportManager.exportReportToPdfFile(jasperPrint,"C:/Users/user/Desktop/"+month+" "+year+".pdf");
}catch(JRException elle){
System.out.println(elle.getMessage());
}
}
}catch(Exception ev){
System.out.println(ev.getMessage());
}
}
}
I truly appreciate your help.
My first thought is on the motorReport.jrxml file. It may have some issues on its content. Try reducing the contents of the report to a point where the code works and the reports can display properly. It may give you a clue to the cause of the problem. Then get back here with more specifics if you still can't solve this problem.
mapParameters in your code is not records of DataSource. It is parameters of report, therefore report haven't records.
One of the possible solutions: convert ResultSet into BeanCollection, make JRBeanCollectionDataSource and pass it into fillReport.
Make bean for saving result of query.
public class UserBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
....
}
For example result is
List myList = new ArrayList<UserBean>();
Convert into collection example here stackoverflow.com/questions/17206523/put-resultset-values-into-collection-object-then-add-to-arraylist
After convert you must call fillReport like this:
jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String,Object>, new JRBeanCollectionDataSource(myList));

Categories

Resources