How to optimize a loop in java? - java

How can I optimize this following code. I want to display per colleges, departments, courses and students who are currently taking up such courses on my JTable.
public void display(){
...
for(College co: collegeDao.getColleges().stream().sorted(Comparator.comparing(College::getName)).collect(Collectors.toList())){
dtm.addRow(new Object[]{co.getName()});
for(Department department: deptDao.getDepartments().stream().sorted(Comparator.comparing(Department::getName)).collect(Collectors.toList())){
if(Objects.equals(department.getCollege().getId(), co.getId())){
dtm.addRow(new Object[]{null, department.getName()});
for(Course c: courseDao.getCourses().stream().sorted(Comparator.comparing(Course::getName)).collect(Collectors.toList())){
if(Objects.equals(c.getDepartment().getId(), department.getId())){
dtm.addRow(new Object[]{null, null, c.getName()});
for(Student st: cTakenDao.getCoursesTaken(c).stream().sorted(Comparator.comparing(Student::getName)).collect(Collectors.toList())){
dtm.addRow(new Object[]{null, null, null, st.getName()});
counter++;
}
}
}
dtm.addRow(new Object[]{null, null, null, null, "Maxumim Population Allowed "+department.getPopulation()});
dtm.addRow(new Object[]{null, null, null, null, "Remaining Slot "+(department.getPopulation()-counter)});
counter = 0;
}
}
}
...
It actually works, but it takes time to load my data on the table. If I use LEFT JOIN on my sql query, all of my data were being repeated on upon display on my JTable.
Hope someone can suggest better solution of it, thank you in advance.

Related

UNION in SQLiteDatabase?

I need to execute the following query, and return a Cursor, using SQLiteDatabase class:
SELECT DISTINCT sender
FROM messages;
UNION
SELECT DISTINCT recipient
FROM messages;
(the fields sender and recipient are of the same type.)
I know how to execute the SELECT DISTINCT and get 2 cursors holding sender and recipient columns:
c1 = db.query(
true, //distinct
Messages.TABLE_NAME, //table name
senderColumn, //columns
null, //where clause
null, //where args
null, //group
null, //having
sortOrder, //sorting order
null //limit of rows number
);
c2 = db.query(
true, //distinct
Messages.TABLE_NAME, //table name
recipientColumn, //columns
null, //where clause
null, //where args
null, //group
null, //having
sortOrder, //sorting order
null //limit of rows number
);
But I can't figure how to UNION them (and return a Cursor). Also, I may want to specify a sorting order on the result. How can I do that? I can't find any mention of UNION in the API.

How can I get a value from database that has the soonest time to current time?

I keep getting a NullPointerException when I try this query:
Cursor cursor = sqLiteDatabase.query("collection", new String[] { "SELECT interval WHERE MIN(time) FROM collection" }, null, null,
null, null, null); // This is where the NPE is.
cursor.moveToFirst(); //ADD THIS!
Integer collectionInterval = cursor.getInt(0);
Is my select query right or the way I'm setting this up?
Basically above I want to select an interval where the soonest time to current time from a table. How can I do that?
In a query, FROM comes before WHERE. Also, I think you need an equality test there
SELECT interval FROM collection WHERE time = (SELECT MIN(time) FROM collection)

Android SQLite query rows from bottom to top with timestamp to equal current date

I am using SQLite for my app and I kind of have a large database. The database has 3 columns:
id(int auto incerement)|timestamp(int)|value(string)
I want to have the latest records, which have timestamp (millisec) of the current day.
At the I have a code to query all the records in the table, but it is awfully slow:
public List<PhysicalActivity> getAllPhysicalActivities(){
List<PhysicalActivity> all = new ArrayList<PhysicalActivity>();
Cursor cursor = mDatabase.query(PhysicalActivityDatabaseHelper.TABLE_NAME, mColumns
, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
PhysicalActivity pa = cursorToPhysicalActivity(cursor);
all.add(pa);
cursor.moveToNext();
}
cursor.close();
return all;
}
I want to do ORDER BY id DESC as you would do in MySQL...I need to have something like this code:
public List<PhysicalActivity> getPhysicalActivitiesForDate(Date date){
List<PhysicalActivity> activities = new ArrayList<PhysicalActivity>();
Cursor cursor = mDatabase.query(PhysicalActivityDatabaseHelper.TABLE_NAME, mColumns
, null, null, null, null, "ORDERBY " + PhysicalActivityDatabaseHelper.COLUMN_ID +
" DESC");
cursor.moveToFirst();
while(!cursor.isAfterLast()){
PhysicalActivity pa = cursorToPhysicalActivity(cursor);
Date d = new Date(pa.getTimestamp());
if(d.getDay() == date.getDay()){
activities.add(pa);
}
cursor.moveToNext();
}
cursor.close();
return activities;
}
Another problem is that getDay() method is deprecated...what should I replace with that to have the same effect (compare the day the row's timestamp represents to the day in the date that passed as an argument).
This query should solve your problem. I´ll explain it.
long curretTime = System.currentTimeMillis()
Cursor cursor = mDatabase.query(
PhysicalActivityDatabaseHelper.TABLE_NAME, //Table name
mColumns, //Queryed columns
PhysicalActivityDatabaseHelper.TIMESTAMP + " = " currentTime, //Select
null, null, null,
PhysicalActivityDatabaseHelper.TIMESTAMP + " DESC" //Order By
);
First of all you're going to get the current time in milis so you can compare it. Then you'll retrieve all the fields of the table (only if you want), then you will retrieve only the rows matching the Select part and order that resulset in base of the Order By.
Hope it helps!

How can I read only 10 rows from my Sql Database?

Hey I have a question:) How can I read only ten rows from my sql db?
here is my code:
openDB();
Cursor c = myDb.getSpalte();
List<Integer> valueList = new ArrayList<Integer>(c.getCount());
while (c.moveToNext()) {
valueList.add(c.getInt(1));
}
c.close();
closeDB();
And if it helps you here is my getSpalte method:
public Cursor getSpalte(){
String where = null;
String Order = "_id DESC";
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Thank yout for helping! And sorry for my bad englsih;P
Set the last null argument to "10". This argument is for LIMIT which limits the number of rows returned by the query.
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, "10");
Remember though that limiting must be accompanied by appropriate logic to sort the result set. Otherwise, you can get any 10 rows, which may not always be what you want.
Reference
Change your db query in your getSpalte function like this:
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, "10");
You can do this by using select TOP, limit or using ROWNUM depending on the DB you use, or you can simple handle it using a simple for loop instead of while.
You can use LIMIT for that as last argument. Here 10.
Refer here
limit - Limits the number of rows returned by the query, formatted as
LIMIT clause. Passing null denotes no LIMIT clause.

How to get data in MySQL table into Java JTable?

I'm working on Java project, and I need to load a particular set of data in to JTable. Can someone explain to me how to do this? These are my fields in the "mrnform" table in database called "order_processing".
`Date` varchar(10) NOT NULL,
`RegNo` int(11) NOT NULL,
`Description` varchar(50) NOT NULL,
`ItemNo` int(11) NOT NULL,
`Unit` varchar(10) NOT NULL,
`Quantity` int(11) NOT NULL,
`Delivery_Date` varchar(10) NOT NULL,
`Delivery_Address` varchar(10) NOT NULL,
`Site_Name` varchar(30) NOT NULL,
1) construct JDBC Connection for MySql, examples here
2) load data to the JTable by using TableModel, examples here
3) if you'll reall question, post this question here in sscce from
Pseudo code
Design the TableModel (or Vector)
Establish the db connection and retrieve result.
Store database result into TableModel object.
Construct the JTable(tableModel).
Read the manual for the JTable:
http://download.oracle.com/javase/tutorial/uiswing/components/table.html
visit
http://netshor.blog.com/2013/12/31/how-to-get-data-from-mysql-to-jtable/
'//initialize row of jTable int row=0; //start try-catch try{
//create connection with database //execute query //no start loop
while(rs.next()){jTable1.setValueAt(rs.getString(1), row, 0);
jTable1.setValueAt(rs.getString(2), row, 1);
jTable1.setValueAt(rs.getString(3), row, 2);
jTable1.setValueAt(rs.getString(4), row, 3);
jTable1.setValueAt(rs.getString(5), row, 4);
jTable1.setValueAt(rs.getString(6), row, 5);
jTable1.setValueAt(rs.getString(7), row, 6);
//increament in row of jtable. row++; } } catch(Exception e) {
}'

Categories

Resources