This question already has answers here:
Java ResultSet how to check if there are any results
(23 answers)
Closed 8 years ago.
I am using HSQLDB in my program. I want to check if my Result Set is empty or not.
//check if empty first
if(results.next() == false){
System.out.println("empty");
}
//display results
while (results.next()) {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
}
The above method is not working properly. According to this post I have to call .first() or .beforeFirst() to rest the cursor to the first row, but .first() and .beforFirst() are not supported in HSQL. I also tried to add connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
but I still get the same outcome (I get the message empty and the data from the DB!!!)
What am I doing wrong here?
If I understand your objective, you could use do while loop
if (!results.next()) {
System.out.println("empty");
} else {
//display results
do {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
} while (results.next());
}
Or, you could just keep a count like so,
int count = 0;
//display results
while (results.next()) {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
count++;
}
if (count < 1) {
// Didn't even read one row
}
Related
I'm trying to fetch from mysql table multiple lines data, for example:
1 car
2 shop
3 dress
But for now it's only fetch the first line.
My code so far:
case "2":
ResultSet rsl2 = stmt.executeQuery("SELECT payments FROM payment;" );
while(rsl2.next()) {
String sqlRes = rsl2.getString("payments");
System.out.println(sqlRes);
if (sqlRes != null) {
System.out.println("OK");
return sqlRes;
}
}
You may either append all your data to the sqlRes variable
sqlRes += rsl2.getString("payments");
and change your if statement to
if (sqlRes == null)
return sqlRes;
or place your return statement after the while loop. Either way, you should append the data in the sqlRes variable if you finally want the returned value to hold all the values in your DB.
Here's my current code snippet:
Iterable<HashMap<String, EntityProperty>> results =
cloudTable.execute(query, propertyResolver);
if (results == null) {
System.out.println("No files processed");
exit_code = "exit_code=1";
} else {
for (HashMap<String, EntityProperty> entity : results) {
// don't know how to start the loop here
}
}
I have a query for retrieving a list of certain files in Microsoft Azure. Now I just need to show the number of files processed result.
I know the concept of what I should be doing, create a counter within the for loop, and then after the Iterations in that loop, whatever the value of that counter variable, it should also give me the count of files right? I just don't know how to start :( I've been reading so much about Iterable in Java but still can't get a grasp on how it would work.
Any inputs would be greatly appreciated
Like this?
Iterable<HashMap<String, EntityProperty>> results =
cloudTable.execute(query, propertyResolver);
int counter;
if (results == null) {
System.out.println("No files processed");
exit_code = "exit_code=1";
} else {
counter = 0;
for (HashMap<String, EntityProperty> entity : results) {
// don't know how to start the loop here
counter++;
}
//int size = results.size();
}
This question already has answers here:
Java - adding elements to list while iterating over it
(5 answers)
Closed 5 years ago.
am trying to add objects to an arraylist after verifying either that object already exits in the list or not. But am getting a ConcurrentModificationException and I don't know how to fix it.
Any help?
here is the code that throws the exception:
List<ContexteNb> projets = service.findByprojet(p);
List<ProjetVTO> models = new ArrayList<>();
for (ContexteNb contexteNb : projets) {
ProjetVTO model = new ProjetVTO();
model.setNbillets(contexteNb.getNbBillet());
model.setAnnee(contexteNb.getDimDate().getAnnee());
model.setPriorite(contexteNb.getDimPriorite().getPriorite());
if (models.isEmpty()) {
models.add(model);
}
else{
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee())
&& (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
} else {
models.add(model);
}}}}
thanks,
The exception results from adding an element to the models List while iterating over it.
You have to change your logic. I suspect the logic of your inner loop is wrong anyway, and fixing it will also solve your problem. You probably want to search first if the List contains any element matching model and modify it if found, and only add a new instance to the List if you don't find a match (i.e. after the loop is over).
Your inner loop would look like this:
if (models.isEmpty()) {
models.add(model);
} else {
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}
}
or simply (you can eliminate the outer condition):
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have method which returns List of objects, I m facing a problem while fetching a data from list, I m getting null pointer exception when i am trying to fetch the data.
method which returns List:
public List <EstimationResivion> getEstimationRevision(double rev_id){
List<EstimationDetailRevision> estDetail=estDetailRev(rev_id);
List<EstimationPanelRev> estPanelrev=estPanelRev(rev_id);
List<EstimationPannelDetailRevision> estimationpaneldetailrev=estPanelDetailRev(rev_id);
List<EstimationResivion> estRev=estRevision(rev_id);
EstimationResivion ed= new EstimationResivion();
ed.setEstimationdetailRev(estDetail);
ed.setEstimationpanelRev(estPanelrev);
ed.setEstimationpaneldetailRev(estimationpaneldetailrev);
System.out.println("Size before: "+estRev.size());
estRev.add(ed);
return estRev;
}
estDetailRev code:
private List<EstimationDetailRevision> estDetailRev(double d){
return getJdbcTemplate().query("SELECT * FROM estimation_detail_rev WHERE rev_id=?", new Object[] {d }, new EstimationDetailRevRowMapper());
}
estRevision code
private List<EstimationResivion> estRevision(double d){
return getJdbcTemplate().query("SELECT * FROM estimation WHERE est_revision=?", new Object[] {d }, new EstimationRevRowMapper());
}
estRevision will return list of List<EstimationResivion> which i am storing in estRev.
code from where i am calling getEstimationRevision and trying to fetch data from list
public void getRevision(){
double d=0;
List<EstimationResivion> est=estimationdao.getEstimationRevision(d);
for(EstimationResivion er:est){
System.out.println(er.getEstContactPerson());
System.out.println(er.getEstCustomer());
System.out.println(er.getRevId());
// epd=er.getEstimationpaneldetailRev();
List<EstimationDetailRevision> edr=er.getEstimationdetailRev();
for(EstimationDetailRevision estimaitonDetail:edr){
estimaitonDetail.getCompCategory();
estimaitonDetail.getCompMake();
}
}
I am getting null value when i call er.getEstimationdetailRev();
if i specify the index i am able to getdata something like this:
List<EstimationDetailRevision> edr=est.get(64).getEstimationdetailRev();
My question is how can i fetch data without specifying index ?
One of your elements is null (not a value). Let's find out which,
// for(EstimationResivion er:est){
for (int index = 0; index < est.size(); index++) {
EstimationResivion er = est.get(index);
if (er == null) {
System.out.println("element at index " + index + " is null");
continue; // <-- move to the next index
}
// ...
List<EstimationDetailRevision> edr=er.getEstimationdetailRev();
if (edr == null) {
System.out.println("edr at index " + index + " is null");
continue; // <-- move to the next index
}
Also, you could (and should) use a debugger on your code.
I have following code in android:
protected void onPostExecute(ResultSet rsData)
{
try
{
int size=0;
while(rsData.next())
{
size++;
}
mlst = new String[size];
int i=0;
while(rsData.next())
{
String mid = rsData.getString(rsData.findColumn("mid"));
String uid = rsData.getString(rsData.findColumn("uid"));
String messages = rsData.getString(rsData.findColumn("message"));
String read=rsData.getString(rsData.findColumn("rstamp"));
mdb.addMessage(new Contact(mid, uid, messages, read));
mlst[i]=mid;
i++;
}
con.UpdateMessage(mlst);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In this i kept debugger on each line.
I found that in first while loop value of size becomes 7.
Means there are 7 rows in rsData ResultSet.
But as soon as it comes on second while loop, it suddenly does not enters in while loop and control directly goes to line : con.UpdateMessage(mlst);
I am not able to understand why its happening so?
If resultset has 7 rows in it, then it should enter in it 7 times, but its not entering a single time.
Please help me.
The problem is that with
while(rsData.next())
{
size++;
}
you move the cursor to the end of the result set. Thus, when you try to run the second while loop, the cursor is already at the end, so the loop is not executed.
You have to set the cursor to the start again, with rsData.beforeFirst();. The resulting code should look like this:
protected void onPostExecute(ResultSet rsData)
{
try
{
int size=0;
while(rsData.next())
{
size++;
}
rsData.beforeFirst();
mlst = new String[size];
int i=0;
while(rsData.next())
{
String mid = rsData.getString(rsData.findColumn("mid"));
String uid = rsData.getString(rsData.findColumn("uid"));
String messages = rsData.getString(rsData.findColumn("message"));
String read=rsData.getString(rsData.findColumn("rstamp"));
mdb.addMessage(new Contact(mid, uid, messages, read));
mlst[i]=mid;
i++;
}
con.UpdateMessage(mlst);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You may want to do
rsData.beforeFirst();
just before the second while loop.
You have gone through the whole result set once and have just passed the last record. You have not told the ResultSet you want to start another iteration from the beginning again.
rsData.next() changes the cursor position. Calling it twice causes the error.
You can use List<String> instead of String array so you won't need to get the size before the data. This way you can use only the second loop.
ResultSet#next -
Moves the cursor froward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
So you first while loop move the cursor at last row. so at second while loop it is already at last, so it escapes.
You could use ResultSet#beforeFirst before second while-loop which move your cursor back to normal but It would be better if you use ArrayList insteads of array it dynamically resizable, so no need to care about size, it enhance you code performance.
List<String> mlst = new ArrayList<>();
...
mlst.add(mid);
while(rsData.next())
{
size++;
}
After this, you're already on the last row of the resultSet. Nothing is next to it.
Try this, while creating the statement:
connection.prepareStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);