How to do a select all using GreenDAO? - java

Does anyone know how to do a simple select * from table in greenDAO and place it into an entity? I have done some research on this and I am unable to get any simple example. This is what I have so far:
public void storeAppTimeUsageData(AppTimeUsage stats) {
List<AppTimeUsage> items = new ArrayList<>();
//appTimeUsageDao = DeviceInsightApp.getSession(this, true).getAppTimeUsageDao();
try {
// master
appTimeUsageDao.insertOrReplace(stats);
//} catch (IOException e) {
} catch (Exception e) {
Log.e("Error", "Some exception occurred", e);
Log.e("APP_TAG", "STACKTRACE");
Log.e("APP_TAG", Log.getStackTraceString(e));
}
String sql = "SELECT * FROM APP_TIME_USAGE ";
Cursor c = appTimeUsageDao.getDatabase().rawQuery(sql, null);
int offset = 0;
int d ;
int cd ;
String e = "";
while (c.moveToNext()) {
AppTimeUsage atu AppTimeUsage(
c.getLong(0);
//long b = c.getInt(0);
d = c.getInt(2);
e = c.getString(3);
break;
);
items.add(atu);
}
}

GreenDAO already comes with a built-in method for achieve this task. In your case:
List<AppTimeUsage> items = appTimeUsageDao.loadAll();
This will select all records from APP_TIME_USAGE and return a List<AppTimeUsage> containing the entities.

Related

Strings can not be converted to DAO Receiver

I am trying to perform batch insertion operation with a list object but while inserting I am getting String cannot be converted to DAO.The receiver in the iterator loop.
I have tried to list the list object, at that time it is printing values from the list. but, when I use generics are normal list it is showing error and I don't find any solution to insert
From this method I am reading the excel file and storing into list
public List collect(Receiver rec)
{
//ReadFromExcel rd = new ReadFromExcel();
List<String> up = new ArrayList<String>();
//List<String> details = rd.reader();
//System.out.println(details);
try( InputStream fileToRead = new FileInputStream(new File(rec.getFilePath())))
{
XSSFWorkbook wb = new XSSFWorkbook(fileToRead);
wb.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
XSSFSheet sheet = wb.getSheetAt(0);
DataFormatter fmt = new DataFormatter();
String data ="";
for(int sn = 0;sn<wb.getNumberOfSheets()-2;sn++)
{
sheet = wb.getSheetAt(sn);
for(int rn =sheet.getFirstRowNum();rn<=sheet.getLastRowNum();rn++)
{
Row row = sheet.getRow(rn);
if(row == null)
{
System.out.println("no data in row ");
}
else
{
for(int cn=0;cn<row.getLastCellNum();cn++)
{
Cell cell = row.getCell(cn);
if(cell == null)
{
// System.out.println("no data in cell ");
// data = data + " " + "|";
}
else
{
String cellStr = fmt.formatCellValue(cell);
data = data + cellStr + "|";
}
}
}
}
}
up = Arrays.asList(data.split("\\|"));
// System.out.println(details);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
Iterator iter = up.iterator();
while(iter.hasNext())
{
System.out.println(iter.next());
}
String row="";
Receiver info = null;
String cid = "";
String cname = "";
String address = "";
String mid = "";
boolean b = false;
List<Receiver> res = new ArrayList<Receiver>();
int c = 0;
try
{
String str = Arrays.toString(up.toArray());
//System.out.println(str);
String s = "";
s = s + str.substring(1,str.length());
// System.out.println("S:"+s);
StringTokenizer sttoken = new StringTokenizer(s,"|");
int count = sttoken.countTokens();
while(sttoken.hasMoreTokens())
{
if(sttoken.nextToken() != null)
{
// System.out.print(sttoken.nextToken());
cid = sttoken.nextToken();
cname = sttoken.nextToken();
address = sttoken.nextToken();
mid = sttoken.nextToken();
info = new Receiver(cid,cname,address,mid);
res.add(info);
System.out.println("cid :"+cid+ " cname : "+cname +" address : "+address+" mid : "+mid);
c = res.size();
// System.out.println(c);
}
else
{
break;
}
}
System.out.println(count);
// System.out.println("s");
}
catch(NoSuchElementException ex)
{
System.out.println("No Such Element Found Exception" +ex);
}
return up;
}
with this method I'm trying to insert into database
public boolean insert(List res)
{
String sqlQuery = "insert into records(c_id) values (?)";
DBConnection connector = new DBConnection();
boolean flag = false;
// Iterator itr=res.iterator();
// while(it.hasNext())
// {
// System.out.println(it.next());
// }
try( Connection con = connector.getConnection();)
{
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(sqlQuery);
Iterator it = res.iterator();
while(it.hasNext())
{
Receiver rs =(Receiver) it.next();
pstmt.setString(1,rs.getcID());
pstmt.setString(2,rs.getcName());
pstmt.setString(3,rs.getAddress());
pstmt.setString(4,rs.getMailID());
pstmt.addBatch();
}
int [] numUpdates=pstmt.executeBatch();
for (int i=0; i < numUpdates.length; i++)
{
if (numUpdates[i] == -2)
{
System.out.println("Execution " + i +": unknown number of rows updated");
flag=false;
}
else
{
System.out.println("Execution " + i + "successful: " + numUpdates[i] + " rows updated");
flag=true;
}
}
con.commit();
} catch(BatchUpdateException b)
{
System.out.println(b);
flag=false;
}
catch (SQLException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
flag=false;
}
return flag;
}
I want to insert list object using JDBC batch insertion to the database.
Your method collect(Receiver rec) returns the List of strings called up.
return up;
However (if you are really using the method collect to pass the List into insert(List res) method), you are expecting this list to contain Receiver objects. Which is incorrect, since it collect(..) returns the list of Strings.
And that causes an error when you try to cast Receiver rs =(Receiver) it.next();
You need to review and fix your code, so you will pass the list of Receiver objects instead of strings.
And I really recommend you to start using Generics wherever you use List class. In this case compiler will show you all data-type errors immediately.

Mysql table not found

here is my query along with the java code..
public ArrayList getProductinfo(int id){
try{
String query="SELECT product_name,product_description FROM product WHERE category_id = "+id;
statement = connect.createStatement();
result = statement.executeQuery(query);
System.out.println("Successfull Query for info..");
}catch(Exception e){
System.out.println("Error in Query..");
e.printStackTrace();
}
ArrayList<String> columnName = null;
try{
columnName = new ArrayList<String>();
for(int i = 1 ; i <= result.getMetaData().getColumnCount(); i++){
columnName.add(result.getMetaData().getColumnName(i));
}
}catch(Exception e){
e.printStackTrace();
}
return columnName;
}
this function was called from this one:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTable1.removeAll();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
null
));
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
MyDatabaseHandler db=new MyDatabaseHandler();
db.setConnection(null, null, null);
ArrayList content=db.getProductinfo(1);
model.addColumn("Image");
model.addColumn("Description");
Object[] rows=new Object[2];
ResultSet result=db.getRset();
try{
while(result.next()){
String ss="";
int m=0;
for(Object c : content){
m++;
if(m==1){
//rows[0]=result.getBlob(c.toString());
rows[0]=result.getString(c.toString());
}else if(m==2){
ss+="Name:"+result.getString(c.toString()+"\n");
}else if(m==3){
ss+="Description:"+result.getString(c.toString()+"\n");
}else if(m==4){
ss+="Price:"+result.getString(c.toString()+"\n");
}else if(m==5){
ss+="Quantity:"+result.getString(c.toString());
}
}
rows[1]=ss;
//System.out.println(ss);
model.addRow(rows);
}
}catch(Exception e){
e.printStackTrace();
}
}
this executes as it should be in cmd but whenever I run this from the java class it gives me this error:
java.sql.SQLException:Column'product_description' not found
note: This very query works in cmd just fine and the column product_description is there and there is no mistake in spelling.if I give only one column name after the SELECT string such as SELECT product_description only then it executes normally...What am I doing wrong? Thanks in Advance.
'product_description' is a column name - not table name. You apparently either don't have such column or have a mistake in its name.
Try this:
String query="SELECT `product_name`,`product_description` FROM product WHERE category_id = "+id;

How to customize the TotalRecordCount and Paging after filter in jTable jquery (Java-JSP)

I use a jTable jquery for jsp page, it work very well. It can display the showing count records in bottom right of table well (e.g. Showing 1-10 of 22). When I insert the Filtering into the page, the showing count record is not correctly.
I follow this for Filtering: http://www.jtable.org/Demo/Filtering
How to customize the code for showing count record (I use java-jsp and sql server). Sorry for my English language :))
Here is the code I am using right now in controller.
if (action.equals("list")) {
try {
int startPageIndex = Integer.parseInt(request.getParameter("jtStartIndex"));
int numRecordsPerPage = Integer.parseInt(request.getParameter("jtPageSize"));
String jtSorting = null;
//Fetch Data from Rejected_Product Table
lstSite = dao.**getAllSite**(filter_site, startPageIndex, numRecordsPerPage, jtSorting);
//Get Total Record Count for Pagination
int siteCount = dao.**getSiteCount**();
//Convert Java Object to Json
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(lstSite, new TypeToken<List<Site>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String listData = jsonArray.toString();
//Return Json in the format required by jTable plugin
listData = "{\"Result\":\"OK\",\"Records\":"+listData+",\"TotalRecordCount\":"+siteCount+"}";
response.getWriter().print(listData);
System.out.println(listData);
} catch (Exception ex) {
String error = "{\"Result\":\"ERROR\",\"Message\":" + ex.getStackTrace() + "}";
response.getWriter().print(error);
ex.printStackTrace();
}
}
and here method getAllSite:
public List<Site> getAllSite (FilterSite filter_site, int jtStartIndex, int jtPageSize, String jtSorting) {
List<Site> siteList = new ArrayList<Site>();
String query = "";
String siteQ = filter_site.getSite();
String clientQ = filter_site.getClient(); // wait
String locationQ = filter_site.getLocation();
if (locationQ.isEmpty()) {
locationQ = "";
} else {
locationQ = "and location like '%"+locationQ+"' ";
}
String site_idQ = filter_site.getSite_id();
if (site_idQ.isEmpty()) {
site_idQ = "";
} else {
site_idQ = "and site_id = '"+site_idQ+"' ";
}
String divisionQ = filter_site.getDivision();
if (divisionQ.isEmpty()) {
divisionQ = "";
} else {
divisionQ = "and division = '"+divisionQ+"' ";
}
int range = jtStartIndex+jtPageSize;
query = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY CODE) as row FROM [site]) a "
+ "WHERE (code like '%"+siteQ+"' "+locationQ+site_idQ+divisionQ+") "
+ "and row > "+jtStartIndex+" and row <= "+range;
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
System.out.println("query : "+query);
while (rs.next()) {
Site sitebean = new Site();
sitebean.setName(rs.getString("name"));
sitebean.setCode(rs.getString("code"));
.....
siteList.add(sitebean);
}
} catch (SQLException e) {
e.printStackTrace();
}
return siteList;
}
and here method getSiteCount :
public int getSiteCount () {
int count = 0;
String query = "SELECT COUNT(*) as count FROM [site] ";
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
count = rs.getInt("count");
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
If you mean by "not correctly" that the row count is larger than expected, then the solution would be to include the where clause in the siteCount query.
WHERE (code like '%"+siteQ+"' "+locationQ+site_idQ+divisionQ+")

J2ME , Quizz using choiceGroups

I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}

Java: Check auto-generated ID

My Java program adds items into database. I have a code for generating random string that will be used as an item ID. I want to make IDchecker(id) that will check whether the ID already exists into database.
If I have codeIDgenerator() and IDchecker(id) methods, how do I make a loop that will generate new code if the ID already exists, or will exit the loop if the ID is unique and doesn't come up in the database?
Also I'm having trouble with my IDchecker(id) method, I'm using ResultSet to bring back the data from SQL, but I can't find a way to determine how many rows does ResultSet has (if at all). There is no isEmpty() for resultSet?
Here's the code:
public void AddItem() {
boolean checkCode = false;
while (checkCode == false) {
Random r = new Random();
int numbers = 100000 + (int) (r.nextFloat() * 899900);
String ID= Integer.toString(numbers);
try {
if (DatabaseConnection.checkID(ID) == false) {
checkCode = true;
System.out.println("ID is unique");
} else if (DatabaseConnection.checkID(ID) == true) {
System.out.println("ID is NOT unique");
}
} catch (SQLException ex) {
Logger.getLogger(ModelTabeleIntervencija.class.getName()).log(Level.SEVERE, null, ex);
}
}
And here is the ckeckID(ID) method
public boolean CheckID(String ID) throws SQLException {
String query = "SELECT itemId FROM items WHERE itemID= '"+ID+"'";
Statement dbStatement = connection.createStatement();
ResultSet rsItems= dbStatement .executeQuery(query);
if (rsItems.isEmpty( )== true){
return false;
// ID not found - is unique
} else{
return true;
// ID found - is not unique
}
}
Thanks
While generating unique id is best done in your database, I can help you simplify your code. You shouldn't need to check your database twice.
private final Random r = new Random();
public String getUniqueId() {
try {
while (true) {
int n = r.nextInt(1000 * 1000) + 1000 * 1000;
String id = ("" + n).substring(1); // number between 000000 and 999999
if (DatabaseConnection.checkID(id))
return id;
}
} catch (SQLException ex) {
throw new IllegalStateException("Cannot access database", ex);
}
}
However, instead of generating a random id, you could just get the next id.
public String getUniqueId() {
try {
String maxId = DatabaseConnection.selectMaxId();
int n = Integer.parseInt(maxId) + 1;
return ("" + n).substring(1); // number between 000000 and 999999
} catch (SQLException ex) {
throw new IllegalStateException("Cannot access database", ex);
}
}

Categories