Its not compiling and i have no idea why... New to sqlite and tried to follow some question's answer on stack overflow but not able to figure it out. Modal class is MainDataHelper
Code
MainDataHelper myDatabaseHelper = new MainDataHelper(getActivity());
myDatabaseHelper.openDataBase();
String text = myDatabaseHelper.getMostMessagesSent(); //this is the method to query
myDatabaseHelper.close();
mMostMessagesSent.setText(text);
mMostMessagesSent.setTextColor(Color.WHITE);
Helper
public class MainDataHelper extends Activity {
private int TotalMessagesSent;
private int TotalMessagesRecieved;
private int TotalMessages;
private String TotalTimeSpent;
private String MostMessagesSent;
private String MostMessagesRecieved;
private String MostTexted;
private String MostTimeSpent;
private int QuizTaken;
private int QuizTakers;
private int Reviewed;
private int Reviews;
public MainDataHelper() {
TotalMessagesSent = 0;
TotalMessagesRecieved = 0;
TotalMessages = 0;
TotalTimeSpent = "";
MostMessagesSent = "";
MostMessagesRecieved = "";
MostTexted = "";
MostTimeSpent = "";
QuizTaken = 0;
QuizTakers = 0;
Reviewed = 0;
Reviews = 0;
}
public MainDataHelper( int TotalMessagesSent, int TotalMessagesRecieved, int TotalMessages, String TotalTimeSpent,String MostMessagesSent, String MostMessagesRecieved, String MostTexted, String MostTimeSpent,int QuizTaken, int QuizTakers, int Reviewed, int Reviews) {
TotalMessagesSent = TotalMessagesSent;
TotalMessagesRecieved = TotalMessagesRecieved;
TotalMessages = TotalMessages;
TotalTimeSpent = TotalTimeSpent;
MostMessagesSent = MostMessagesSent;
MostMessagesRecieved = MostMessagesRecieved;
MostTexted = MostTexted;
MostTimeSpent = MostTimeSpent;
QuizTaken = QuizTaken;
QuizTakers = QuizTakers;
Reviewed = Reviewed;
Reviews = Reviews;
}
public int getTotalMessagesSent() {
return TotalMessagesSent;
}
public int getTotalMessagesRecieved() {
return TotalMessagesRecieved;
}
public int getTotalMessages() {
return TotalMessages;
}
public String getTotalTimeSpent() {
return TotalTimeSpent;
}
public String getMostMessagesSent() {
return MostMessagesSent;
}
public String getMostMessagesRecieved() {
return MostMessagesRecieved;
}
public String getMostTexted() {
return MostTexted;
}
public String getMostTimeSpent() {
return MostTimeSpent;
}
public int getQuizTaken() {
return QuizTaken;
}
public int getQuizTakers() {
return QuizTakers;
}
public int getReviewed() {
return Reviewed;
}
public int getReviews() {
return Reviews;
}
public void setTotalMessagesSent(int TotalMessagesSent) {
TotalMessagesSent = TotalMessagesSent;
}
public void setTotalMessagesRecieved(int TotalMessagesRecieved) {
TotalMessagesRecieved = TotalMessagesRecieved;
}
public void setTotalMessages(int TotalMessages) {
TotalMessages = TotalMessages;
}
public void setTotalTimeSpent(String TotalTimeSpent) { TotalTimeSpent = TotalTimeSpent; }
public void setMostMessagesSent(String MostMessagesSent) {
MostMessagesSent = MostMessagesSent;
}
public void setMostMessagesRecieved(String MostMessagesRecieved) {
MostMessagesRecieved = MostMessagesRecieved;
}
public void setMostTexted(String MostTexted) {
MostTexted = MostTexted;
}
public void setMostTimeSpent(String MostTimeSpent) { MostTimeSpent = MostTimeSpent; }
public void setQuizTaken(int QuizTaken) {
QuizTaken = QuizTaken;
}
public void setQuizTakers(int QuizTakers) {
QuizTakers = QuizTakers;
}
public void setReviewed(int Reviewed) { Reviewed = Reviewed; }
public void setReviews(int Reviews) {
Reviews = Reviews;
}
}
......................................................................................................................................................................................................................
It's not compiling due to a few reasons.
First MainDataHelper does not have a constructor that accepts/takes an Activity. MainDataHelper has two constructors one takes no parameters, the other takes 12 parameters. You have to use one of the available constructors when instantiating a MainDataHelper object.
e.g. MainDataHelper myDatabaseHelper = new MainDataHelper(); would compile.
There is no openDatabase method in MainDataHelper, you would either have to add such a method or do away with the line myDatabaseHelper.openDataBase();
There is no close method in MainDataHelper, you would either have to add such a method or do away with the line myDatabaseHelper.close();
Considering that you want to use an SQLite database then you will use a sub-class of the SQLiteOpenHelper class that would be invoked from an Activity or a Fragment (or even many of these).
Before even considering writing a line of code you would need to understand you requirements for the database and have some sort of design (schema). Ignoring that and assuming (for demonstration) that you want a simple database with one table called questions and has one column called question then the following could be such a class (in this case MainDataBaseHelper.java) :-
public class MainDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "question.db"; //<<<<<<<<<< name of the database
public static final int DATABASEVERSION = 1; //<<<<<<<<<< version number of the database
public static final String TABLE_QUESTION = "question"; //<<<<<<<<<< name of the quiz table
public static final String COLUMN_QUESTION_QUESTION = "question";
public MainDatabaseHelper(Context context) {
super(context, DATABASENAME, null, DATABASEVERSION);
}
//<<<<<<<<<< Called ONCE when the database is first created (first time an attempt is made to open if)
#Override
public void onCreate(SQLiteDatabase db) {
String crt_questiontable_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUESTION + "(" +
COLUMN_QUESTION_QUESTION + " TEXT" +
")";
db.execSQL(crt_questiontable_sql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addQuestion(String question) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_QUESTION_QUESTION,question);
return this.getWritableDatabase().insert(TABLE_QUESTION,null,cv);
}
public Cursor getAllQuestions() {
return this.getWritableDatabase().query(TABLE_QUESTION,null,null,null,null,null,null);
}
}
With the above class existing your code could then be (as a simple example) :-
MainDatabaseHelper myDBHlpr = new MainDatabaseHelper(getActivity()); // Instantiate a MainDatabasehelper object called myDBHlpr
// Add some questions to the questions table
myDBHlpr.addQuestion("This is the first question");
myDBHlpr.addQuestion("This is another question");
myDBHlpr.addQuestion("Yet another question");
// Now get all of the questions
Cursor csr = myDBHlpr.getAllQuestions();
Log.d("DBINFO","There are " + String.valueOf(csr.getCount()) + " questions in the database.");
// Loop through all the questions
while (csr.moveToNext()) {
Log.d("DBINFO",
"Question " +
String.valueOf(csr.getPosition() + 1) +
" is " + csr.getString(csr.getColumnIndex(MainDatabaseHelper.COLUMN_QUESTION_QUESTION))
);
mMostMessagesSent.setText(csr.getString(csr.getColumnIndex(MainDatabaseHelper.COLUMN_QUESTION_QUESTION));
}
csr.close(); //<<<<<<<<<< Should always close Cursor when done with it.
//mMostMessagesSent.setText(text); //<<<<<<<<<< done in the loop through the cursor (for demonstration very likely only the last question will be seen)
mMostMessagesSent.setTextColor(Color.WHITE);
When run (for the first time) the log would then include :-
11-12 20:17:16.345 1376-1376/? D/DBINFO: There are 3 questions in the database.
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 1 is This is the first question
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 2 is This is another question
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 3 is Yet another question
Additionally the last question (which may or may not be the last question added) will be displayed in the TextView.
Note 3 rows would be added to the table each time the above is run.
Note this is purely intended as an introduction/demonstration there is a great deal more that needs to be done, such as designing the database.
Related
I'm trying to update the informations on my listview by using sqlitedatabase, so in my update class I'm getting an error which is here on the pic http://prntscr.com/djbe3i
Here's the dbhelper method code:
public int updateInformation(String old_name, String new_name,String old_hours, String new_hours, String old_department,String new_department,SQLiteDatabase sqLiteDatabase) {
ContentValues contentValues = new ContentValues();
contentValues.put(UserContract.NewUserInfo.Name,new_name);
contentValues.put(UserContract.NewUserInfo.RenderedHours,new_hours);
contentValues.put(UserContract.NewUserInfo.Department,new_department);
String selection = UserContract.NewUserInfo.Name + " LIKE ?";
String[] selection_args = {old_name};
int count = sqLiteDatabase.update(UserContract.NewUserInfo.TABLE_NAME,contentValues,selection,selection_args);
return count;
}
Update class code:
public void updateContact(View view) {
userDBHelper = new UserDBHelper(getApplicationContext());
sqLiteDatabase = userDBHelper.getWritableDatabase();
String name,hours,department;
name = new_name.getText().toString();
hours = new_hours.getText().toString();
department = new_department.getText().toString();
int count = userDBHelper.updateInformation(search_id,NewName,NewHours,NewDepartment,sqLiteDatabase);
}
}
EDIT: I changed the code into:
public void updateContact(View view) {
userDBHelper = new UserDBHelper(getApplicationContext());
sqLiteDatabase = userDBHelper.getWritableDatabase();
String name,hours,department;
name = new_name.getText().toString();
hours = new_hours.getText().toString();
department = new_department.getText().toString();
int count = userDBHelper.updateInformation(search,name,hours,department,sqLiteDatabase);
}
and I'm still getting error I don't understand.
2ND EDIT: I get it now okay, I just mistyped the string and the arguments that i needed for the update contact i replaced the code into:
int count = userDBHelper.updateInformation(search_id,name,hours,department,sqLiteDatabase);
DBHelper.updateInformation code:
public int updateInformation(String old_name, String new_name, String new_hours,String new_department,SQLiteDatabase sqLiteDatabase)
I got it now my parameters doesn't match and I fixed it by changing the code into:
public int updateInformation(String old_name, String new_name, String new_hours,String new_department,SQLiteDatabase sqLiteDatabase)
Then changing the code in update class:
int count = userDBHelper.updateInformation(search_id,name,hours,department,sqLiteDatabase);
Hi I'm working on an android studio project using global arrays,
I can read from the global arrays fine, and have no problem writing
to the global integers ,But i cannot figure out how to set the global
array from code, this is the important parts of the project:
added this under application tag in the android manifest xml:
android:name=".Globals"
java class Globals:
import android.app.Application;
public class Globals extends Application {
public int empnum=13;
public int getData3() {
return empnum;
}
public void setData3(int empnum) {
this.empnum = empnum;
}
public String[] passw = {"0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123"};
public String[] getData4() {
return passw;
}
public void setData4(String[] passw) {
this.passw = passw;
}
public int login=0;
public int getData5() {
return login;
}
public void setData5(int login) {
this.login = login;
}
public String[] empname = {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Not logged in"};
public String[] getData6() {
return empname;
}
public void setData6(String[] empname) {
this.empname = empname;
}
Here is the block of code I'm having trouble with
inner class of java class TimeIn:
final Globals g = (Globals) getApplication();
final String[] empname = g.getData6();
final String[] passw = g.getData4();
public void onClick(View v) {
i = 0;
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && h == 0) {
g.setData3(getemn);
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
i = 1;
h = 1;
}
}
I have no problems getting and using a String array, this is how it works to get
an array value and compare it to a string:
public void onClick(View v) {
i = 0;
String getemp = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && getemp.equals(passw[getemn])) { // All of this works perfectly
g.setData3(getemn);
g.setData5(0);
tfone.setText("Empoyee " + getemn);
tftwo.setText("Logged in");
i = 1;
}
if (i == 0 && getemp != (passw[getemn])) {
tfone.setText("No matches found");
edit2.setText("Not logged in");
i = 1;
}
}
So I know this line of code is wrong:
g.setData6(String[getemn], empname);
but for
the life of me I can't figure out how it should be written, the only error hint is I
get from hovering over the line-
array type expected; found 'java.lang.String'
Anyone know what I'm doing wrong?
In Global class, you declare the method with one parameter
public void setData6(String[] empname) {
this.empname = empname;
}
but when you call, you put 2 parameters g.setData6(String[getemn], empname);
You should remove one parameter
or add another method with 2 parameters in Globals class
Also
You are wrong in here
...
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
...
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
The setData6 function now require 2 parameters, one is String array and the other is String
but the way you put the String array to the function is wrong
Here is a simple example that show how to pass the String array to function
public class Test {
public static void setData6(String[] empnameList, String empname) { // with the `String array` you should declare the variable name like `empnameList` or `arrEmpname` NOT `empname` because `empname` make confusing when you read code
this.empnameList = empnameList;
this.empname = empname;
}
public static void main(String[] args) {
String[] strArray = new String[]{"Name1","Name2","Name2"};
String empName = "Na";
setData6(strArray,empName); // call method with 2 parameters here
}
}
Hope this help
Solved!! it turns out I had to modify my setter part of my Globals class, so this first part (the getter method) in the Globals class is correct:
public String[] compname = {"Manager's company", "Company2", "Company3", "Company4", "Company5", "Company6", "Company7", "Company8", "Company9", "Company10", "Company11", "Company12", "Company13", "Not punched in"};
public String[] getData7() {
return compname;
}
I had to change the getter part of my Globals class to this:
public int setcmpn = 0; // <-- Edited, this should equal some integer value
public void setData7(int setcmpn, String compname) { // removed [] from 2nd argument
this.setcmpn = setcmpn;
this.compname[setcmpn] = compname; // added in [] after array's name and fill it with the first argument from setData7 method
}
And to set the value of the desired index from any class just use:
Globals g = (Globals) getApplication();
g.setData7(getemn, getemp);
where getemn is an integer and getemp is a string.
I have a class Components:
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
}
Inside another class I created an arraylist of Components class:
List<Components> compList = new ArrayList<Components>();
Later in the code, I am adding the elements in List in this way:
compList.add(new Components(0,compName,partName,0));
See, here numberOfNets and numOfPin variables in Components class are initiated with 0 values. But these values are getting calculated/incremented in a later part of code and hence I need to update the new values of only these two variables in each list element. Now from ArrayList doc I get the idea of updating a list element using its index by set operation. But I am confused how to set/update a particular variable of a class in an ArrayList of a class. I need to update only these two mentioned variables, not all of the four variables in Components class. Is there any way to do that?
You should add getter/setter to your component class so that outer class can update component's members
public class Components {
private int numberOfNets;
private String nameOfComp;
private String nameOfCompPart;
private int numOfPin;
public components(int i, String compName, String partName, int pin) {
setNumberOfNets(i);
setNameOfComp(compName);
setNameOfCompPart(partName);
setNumOfPin(pin);
}
public void setNumberOfNets(int numberOfNets) {
this.numberOfNets = numberOfNets;
}
// Similarly other getter and setters
}
You can now modify any data by using following code because get() will return reference to original object so modifying this object will update in ArrayList
compList.get(0).setNumberOfNets(newNumberOfNets);
Example code.
public class Main {
public static void main(String[] args) {
List<Components> compList = new ArrayList<Components>();
compList.add(new Components(0, "compName", "partName", 0));
System.out.println(compList.get(0).toString());
compList.get(0).numberOfNets = 3;
compList.get(0).numOfPin = 3;
System.out.println(compList.get(0).toString());
}
}
Your class.
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public Components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
public String toString() {
return this.numberOfNets + " " + nameOfComp + " " + nameOfCompPart
+ " " + numOfPin;
}
}
The output:
0 compName partName 0
3 compName partName 3
I've been stuck at a seemingly simple problem for hours and I just can't find the solution. I'm trying to implement a very simple Forum in Java and I'm trying to load the entrys at the moment.
My forum is a JList that is filled with JPanels and that accepts entries via the JLists DefaultListModel and the addMessage method. So if I add an entry without the database it looks like this:
MessageList m = new MessageList();
m.addMessage("NAME AUTOR", "<html><body style='width: 675px;'>Lorem ipsum dolor sit amet.", "22.01.13", "SOA");
The messageList class looks like this:
public class MessageList extends JList{
DefaultListModel messageModel = new DefaultListModel();
MessageRenderer messageRenderer = new MessageRenderer();
public MessageList( ){
this.setCellRenderer(messageRenderer);
this.setModel(messageModel);
}
public void addMessage(String author, String text, String date, String tag){
messageModel.addElement(new Message(author, text, date, tag));
}
}
I've also written the Code for getting an ArrayList (called allBtr) with the Message Objects (called ConBeitrag) from the database:
ArrayList<ConBeitrag> allBtr = new ArrayList<ConBeitrag>();
ConBeitrag conBtr = new ConBeitrag();
try {
allBtr = conBtr.getAllBtr();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The message objects look like this:
public class ConBeitrag {
private int beitragid;
private int projektid;
private int mitarbeiterid;
private String beitragText;
private String erstellt_am;
private String geaendert_am;
private String schlagwort1;
private String schlagwort2;
private MdBeitrag mdBtr = new MdBeitrag();
public ConBeitrag (){
}
public ConBeitrag(int beitragid, int projektid, int mitarbeiterid, String beitragText, String erstellt_am, String geaendert_am){
this.beitragid = beitragid;
this.projektid = projektid;
this.mitarbeiterid = mitarbeiterid;
this.erstellt_am = erstellt_am;
this.geaendert_am = geaendert_am;
this.beitragText = beitragText;
this.schlagwort1 = schlagwort1;
this.schlagwort2 = schlagwort2;
}
public ArrayList<ConBeitrag> getAllBtr() throws SQLException{
MdBtrInterface modInt;
modInt = new MdBeitrag();
ArrayList<ConBeitrag> AlBtr = modInt.getAllBtr();
for(ConBeitrag object: AlBtr){
System.out.println(object.beitragText);
}
return AlBtr;
}
}
Now what would be the smartest way to get the ArrayList into a form that I can pass into the addMessage method? I've kind of approached this from the GUI end, then from the database end, and now I'm stuck in the middle.
Overwritten toString() method:
#Override
public String toString() {
return mitarbeiterid + beitragstext + erstellt_am + schlagwort1 + schlagwort2;
}
"The messages are stored inside the ArrayList as Objects if that helps. So if I run "System.out.println(allBtr);" it gives me "[ConBeitrag#48f4104f, ConBeitrag#f5ad7f4, ConBeitrag#1517dc0c]"
You need to override the toString method in your ConGeitrag class. Something like this.
public class ConBeitrag {
...
#Override
public String toString(){
return author + ", " + text + ", " + date + ", " + tag;
}
}
You can make the return any format you want. Test this one out and make changes as desired to the format.
Try this out as a Helper method (after you've overridden the toString)
public JList createJList(ResultSet rs){
DefaultListModel model = new DefaultListModel();
while (rs.next()){
String author = rs.getString("author"); // Just an example. You may
String text = rs.getString("text"); // need to retrieve your
String date = rs.getString("date"); // data differently
String tag = rs.getString("tag");
Message message = new Message(author, text, date, tag);
model.addElement(message);
}
JList list = new JList(model);
return list;
}
I don't really see a need for a Custom JList for this situation.
Test run: output : 3testtestnullnull. Besides the formatting, it works fine
public class ConBeitragTest {
public static void main(String[] args) {
ConBeitrag con = new ConBeitrag(1, 2, 3, "test", "test", "test");
System.out.println(con);
}
}
class ConBeitrag {
private int beitragid;
private int projektid;
private int mitarbeiterid;
private String beitragText;
private String erstellt_am;
private String geaendert_am;
private String schlagwort1;
private String schlagwort2;
public ConBeitrag() {
}
public ConBeitrag(int beitragid, int projektid, int mitarbeiterid, String beitragText, String erstellt_am, String geaendert_am) {
this.beitragid = beitragid;
this.projektid = projektid;
this.mitarbeiterid = mitarbeiterid;
this.erstellt_am = erstellt_am;
this.geaendert_am = geaendert_am;
this.beitragText = beitragText;
this.schlagwort1 = schlagwort1; // This is null
this.schlagwort2 = schlagwort2; // This is null
}
#Override
public String toString() {
return mitarbeiterid + beitragText + erstellt_am + schlagwort1 + schlagwort2;
}
}
I'm currently trying to use jasper to help me create reports. I have the information and data that I want displayed in this method:
private void writeToFile(final List<ScenarioLoadModel> sceneLoadModel) throws Exception {
final BufferedWriter bw = new BufferedWriter(new FileWriter("/Uma/nft/result.psv"));
for (final ScenarioLoadModel slm : sceneLoadModel) {
bw.write(slm.getScenarioId() + PSP + slm.getScenarioId() + PSP + slm.getScenarioConfig().getName() + PSP + slm.getLoad() + PSP + "" + EOL);
if (!slm.getScenarios().isEmpty()) {
final int tempCount = slm.getScenarios().get(0).getTemplates().size();
final int sceneCount = slm.getScenarios().size();
for (int tempIdx = 0; tempIdx < tempCount; tempIdx++) {
String id = null;
int pass = 0;
int fail = 0;
final Map<String, BigDecimal> metricMap = new HashMap<String, BigDecimal>();
final DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset();
for (int sceneIdx = 0; sceneIdx < sceneCount; sceneIdx++) {
final Template temp = slm.getScenarios().get(sceneIdx).getTemplates().get(tempIdx);
if (temp.isError()) {
fail++;
} else {
pass++;
}
if (sceneIdx == 0) {
id = temp.getId();
}
final MetricGroupModel mgm = slm.getScenarios().get(sceneIdx).getMetricGroupModel().get(tempIdx);
if (mgm != null) {
for (final MetricModel mm : mgm.getMetricModel()) {
for (final MetricValue mv : mm.getMetricValue()) {
dataset.add(mv.getValue(), new BigDecimal(0.0), mv.getType(), id);
}
}
}
}
final TemplateConfig tc = TemplateManager.getTemplateConfig(id);
bw.write(slm.getScenarioId() + PSP);
bw.write(id + PSP + tc.getName() + PSP + 1 + PSP + pass + "/" + fail);
for (final Object row : dataset.getRowKeys()) {
final Number mean = dataset.getValue((String) row, id);
bw.write(PSP + row + PSP + mean);
}
bw.write(EOL);
}
}
}
bw.close();
}
From my understanding I create Beans and then put them all in a Bean Factory, to create my object that will be ready to be passed to iReport.
How can I put all this information into a Bean? I essentially want the bean to include the scenario/test case and whether or not it passed. (This is for test automation)
I tried to read your code to make a a best guess at what columns you would want, but with no context, I have no clue. All the bean is a pojo, with private fields and public getters and setters.
Assuming there is no grouping and essentially each ScenarioLoadModel will correspond to one row in the report you would end up with a bean like this:
public class ScenariaResults {
private String id;
private String name;
private String load;
private int passCount;
private int failCount;
public ScenariaResults(String id, String name, String load, int passCount,
int failCount) {
super();
this.id = id;
this.name = name;
this.load = load;
this.passCount = passCount;
this.failCount = failCount;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLoad() {
return load;
}
public void setLoad(String load) {
this.load = load;
}
public int getPassCount() {
return passCount;
}
public void setPassCount(int passCount) {
this.passCount = passCount;
}
public int getFailCount() {
return failCount;
}
public void setFailCount(int failCount) {
this.failCount = failCount;
}
#Override
public String toString() {
return "ScenariaResults [id=" + id + ", name=" + name + ", load="
+ load + ", passCount=" + passCount + ", failCount="
+ failCount + "]";
}
}
So basically in the code you have above you build instances of ScenarioResults and add them to a list. Once you have the list, all you need to do is create a JRDataSource:
List<ScenarioResults> dataBeanList = ...call your method to get the list of results
//create the datasource
JRDataSource dataSource = new JRBeanCollectionDataSource(dataBeanList);
Now when designing the report in iReport it can be a little tricky to get the fields imported automatically. Basically first add your project with the bean to the classpath in iReports (could just point it to the bin folder or jar file`): Tools -> options -> classpath tab. Now follow these steps to add the fields.
Click the following icon:
Select the JavaBean Datasource tab.
Enter the classname of your bean. (ex. ScenarioResults)
Click Read attributes
Highlight the fields you want in the report and click Add Selected Field(s).
Click OK.
Now if you want to test what the report looks like with data, and not just an empty datasource, this is where the Factory comes in. It is only for testing while using iReport. You need to create a class that will essentially create a dummy data set for you. It should look something like:
import java.util.ArrayList;
import java.util.List;
public class ScenarioResultsFactory {
public static List<ScenarioResults> createBeanCollection() {
List<ScenarioResults> list = new ArrayList<ScenarioResults>();
list.add(new ScenarioResults("1", "test", "load", 10, 5));
//add as many as you want
return list;
}
}
Now you need to create a Datasource pointing to it in iReport.
Next to the Datasource dropdown in the toolbar click the icon with the tooltip `Report Datasources.
Click New.
Select JavaBeans set datasource. Click Next.
For name enter ScenarioResultsFactory.
For the Factory class you need to put the classname including package. So if the class is in the com package you should have com.ScenarioResultsFactory here.
For the static method put createBeanCollection if not already there.
Check the Use field description check box. Click Test to make sure it worked.
Click Save.