DBCollection.count doesn't count all its DBObjects - java

I have some pretty big DBObjects of which I want to store basic information in an array. I count them, initialize the array in the correct size and then fill it with their basic information. Right now, the count method gives back 5, but there are 6 objects and the iteration finds them all.
public DBObject[] allDbObjects() {
long count = dbc.coll.count();
System.out.println(count + " results found");
DBObject[] results = new DBObject[(int) count];
int i=0;
DBCursor cursor = dbc.coll.find();
for (DBObject o: cursor) {
System.out.println("Found one project:");
results[i] = new BasicDBObject();
System.out.println(o.get("name"));
results[i].put("name", o.get("name"));
results[i].put("id", o.get("_id"));
results[i].put("description", o.get("description"));
i++;
}
return results;
}
Obviously, this gives me an ArrayIndexOutOfBoundsException for the last object. It tries to access results[5], which doesn't exist.
This has worked fine before and according to the mongodb docs, the find method works with the cursor. So basically the cursor thinks it has 5 objects first and then it gives me 6.
Where did I go wrong?
UPDATE: I changed this one to an ArrayList and it works, but I do the same thing at another place. That one worked just fine yesterday. Today it doesn't, I get the same error as I did in the code above.

Related

Java Mysql table data output formatting

Here is my MySql table:
I want to show the output of the query in commandline as below:
I have written the code below to loop but I am getting only the first row, What i have to modify ??
ResultSet rs2 = stmt.executeQuery(table_retrive);
String[] cols = new String[itemList.size()];
int[] rec =new int[itemList.size()];
for (int i = 0; i < itemList.size(); i++) {
while (rs2.next()) {
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.println(rec[i]+" ");
}
}
Your two loops are wrong. Start at i=0 and then iterate once over the whole ResultSet, filling yor first array position. When this is done, i is incremented and you try to iterate the ResultSet a second time but the cursor is at the end of the ResultSet, so rs2.next() returns false and the code will not be executed.
So you have two Solutions:
Handle the loops correctly. Unfortunately I do not know, what you are trying to do anyways because this is some C-like code without OOP, which doesn't show semantics and then you have this itemList which seems to hold preset values and you read out of this list, which column to take for the i-th position. This seems odd. Maybe switching the loops does the desired: Start with the while and nest the for.
Reset the cursor of the ResultSet after the while with rs2.beforeFirst(). WARNING: This could throw a SQLFeatureNotSupportedException. Not all Databases can move the cursor backwards. This is of course a very ugly solution, since you should first parse the whole row a once.
Try to use printf() Or format() method. It is same as printf method in c lang. you can pass parameters and difference. Look at link1
And link 2
Example : System.out.printf("%d%5s%10d", 5,"|",10);
output : 5 | 10
Using this the I got all the values but in one row :
while (rs2.next()) {
for (int i = 0; i < itemList.size(); i++) {
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.print(rec[i]+" ");
}
}
But I need to divide like the rows.
Usage of the inner loop is your problem.
You can enhance your code to remove the usage of the second loop in your code, it basically does nothing. You can loop over your result set and in the same loop using the incremented variable to persist the values accordingly.
The code shown half implemented in your question, hence it will be difficult to give you exactly what need to be done. Nevertheless, here's an attempt to resolve the problem for you:
while (rs2.next()) {
System.out.println(rs2.getInt(1) + "\t |" + rs2.getString(2) + "\t |" + rs2.getString(3));
}
Based on the column names from the table in the question, assuming that column2 and column3 are String's.
You can add the necessary details to this code to complete it according to your usecase, but I've just taken the example of showing a record in one line.
EDIT:
OP has his own way of programming, but to satisfy his question in the comment - this is how you can do it.
while (rs2.next()) {
for (int i = 0; i < itemList.size(); i++)
{
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.print(rec[i]+"\t |");
}
System.out.println();
}

A print statement is speeding up my A * search?

I'm creating an A* search at the moment ( wiki page with pseudocode ) and I've been spending the last hour or so coming up with heuristic equations. When I think I finally found a good one, I removed the print statement that was allowing me to see what states were being visited. For some reason, that made my search go much much slower. If I add the print back in, it becomes fast again. What could possibly be going on?
I even tried changing what it prints. No matter what I am printing (as long as it is 2 characters or more), the result is the same.
Some of the code:
I apologize beforehand for messy code, this is my first time working with something like this:
while(!toVisit.isEmpty()){//toVisit is a set of states that need to be visited
int f = Integer.MAX_VALUE;
State temp;
State visiting = new State();
Iterator<State> it = toVisit.iterator();
while(it.hasNext()){//find state with smallest f value
temp = it.next();
if(temp.getF() < f){
f = temp.getF();
visiting = temp;//should be state with smallest f by end of loop
}
}
System.out.println("Visiting: ");//THIS LINE HERE
//LINE THAT MAGICALY MAKES IT FAST ^^^^
if(numConflicts(visiting.getList()) == 0){//checking if visiting state is the solution
best = visiting.getList();//sets best answer
return visiting;//ends algorithm
}
........
info on toVisit and visiting.getList():
HashSet<State> toVisit = new HashSet<State>();//from Java.util
public ArrayList<Node> State.getList(){return list;}
Node is my own class. It only contains some coordinates
This consistently solves the problem in about 6 seconds. If I change that line to print nothing or something shorter than about 2 characters, it takes anywhere from 20 to 70 seconds

Android database cursor behaving oddly

I have two buttons. One for previous and one for next sqlite database record.
Here is how i am trying to get the next record from the database.
public long getNext(int id,DataBaseHelper helper){
Story story = new Story();
Cursor cursor = story.getStories(helper, 0);
//Updated code
cursor.moveToPosition(id);
cursor.moveToNext();
return cursor.getLong(1);
//Updated code
}
The problem is that if the previous position i pass it is "1", the next position i get is "3". Why does it skip one record? It keeps on skipping one record every time. Please tell me if i'm doing something wrong since i'm new at this and i have looked everywhere but this specific issues seems to be happening to me.
UPDATE : Code edited to show a better approach(perhaps)
Remember that Cursor.getPosition() starts to count from 0. So, the first record is at index #0, the second one at index #1, ...
Take a look at the official documentation : Cursor.moveToPosition(int position)
Let take a look at your code :
(id = 1, for the example)
cursor.moveToPosition(id);
// Cursor is now on the record #1, so the second one of the list
cursor.moveToNext();
// Cursor is now on the record id+1 = #2, so the third one of the list
return cursor.getLong(1);
// Returns the value of the colon #1 of the third record
// of the list : so the record at the index #2
Ok. I have been a little wrong with the approach here. I was ignoring the fact that the cursor index starts from -1 and that the database index of my table starts from 1. So i had to subtract -1 from the id variable and it solved the problem :) Here is the code that worked for me.
public long getNext(int id,DataBaseHelper helper){
id = id - 1;
Story story = new Story();
Cursor cursor = story.getStories(helper, 0);
//Updated code
cursor.moveToPosition(id);
cursor.moveToNext();
return cursor.getLong(1);
//Updated code
}

Insertion of strings into an ArrayList using a binary search in Java?

So here is my problem: I am trying to do a form of insertion sort. Actually, I am trying to search through an ArrayList using a Binary Search algorithm and find where to insert a string. What I have so far sort of works. It is in partial order. I have been stumped on this for over a week! Below is my code:
EDIT: Sorry I think I confused people. My question is how can I edit this to work properly. It inserts my objects in partial order. I need it to be complete order! I do not know where this is happening. I have far too much data being parsed to debug this line for line too.
private void insertOrdered(int frontParameter, int endParameter, TwitterData user) {
int front = frontParameter;
int end = endParameter;
int mid = (front+end)/2;
if (front > end) {
if (user.getUsername().equalsIgnoreCase(users.get(mid).getUsername()))
users.get(mid).addTweet(user.getTweets().get(0));
else
users.add(mid, user);
}
if (user.getUsername().toLowerCase().compareTo(users.get(mid).getUsername().toLowerCase()) < 0) {
insertOrdered(front, mid - 1, user);
}
else if (user.getUsername().toLowerCase().compareTo(users.get(mid).getUsername().toLowerCase()) > 0) {
insertOrdered(mid + 1, end, user);
}
else { //will get to this case if the usernames being tested are equal
users.get(mid).addTweet(user.getTweets().get(0)); //if the user is already in the list, just add the tweet. It is assumed that the user being passed in will only have one tweet tied to their information hence the get(0)
}
}
Just for some background information, I am using this for an ArrayList of Twitter usernames and their associated tweets. The parameter passed, user, is a TwitterData object of a class I wrote. For all intensive purposes all you need to know if I can retrieve the username and a list of tweets that user may have tweeted. Below is a test output of the first 100 users of the list to show you what I mean by it partially working.
First 100 users output:
4colorrebellion
50BandBuckie
2996mymy
20120040
_littlethugg
_IndyaWithaWHY_
__PrettyMistake
__Mannyy24
_MikeFishh
_NikeDeshaun_
_TinaBeana
_PrincesaNessa
_LoveInPaaaris
_Victoria_Ortiz
adriannstacey21
ahansen718
action_packed_
Alicemegan93
alexgracehunter
AlishaaShaffer
arowsey_15
Amy_Vee
allycolucci
AmbiTious___xO
aguss__A
averybrownn
babbyyy_itsREAL
ando775
bburns1117
amberdorais
AshMarieMonica
Ashton_45
_SarahJustine
BlasianCocaine
belieber_pride
AyeeIts_DeeDee
BrianHodges
BritFranceNews
Big_Red911
BiteMy_SlimJim
BadGirlYon
Cemonee_Allisse
cathy_riveros
byby_35
CEOSIXX
busybeekatie
ChelsiKatherine
BOOBtifulJohnny
Coolie_Mackin
coralreefer420
CrashBandaCooch
codyalexander23
cubanrice
corrinea143
Cyndi_R82
danny728_
dbangin
ASNievera
DeAndre_Johnson
Deion_Hungry
DStudmuffin
cowellEmma
expired_data
Dr_drew_V93
feather_hinn
DominiqueQ2
getbackamistake
Da_Dirty_Dern
dudeimisaac
elennatalbert
evillurking
fANNcy_
covolm4
HimOverHere
DameLush
erinnnroach
freaky_fahfah
freesugardaddy
elhotpocket
FollowMandy
HaileyySorenson
DomoNinjaSwagg
IamSalinaScott
fredthemarauder
IAmTHATguy_1
facucuellar
iDream_Mindless
hirschy_kiss94
freshmoney5
HannahMcC_x
GarrieBrocato
AyeeeCali
iSexTattedDudes
Illumi_Lani
itsyunk
jahzzi
Jamie_Hill101
iHeartAudiooooX
jaymethornley
JasonMyers18
One more thing, the last else case does work properly. I have eliminated any kind of dual users being submitted to the ArrayList.
Any ideas?
This would be a lot simpler if you just inserted elements anywhere in the list and called Collections.sort() it would take the same amount of work as you already calculated for your insertion O(n*logn)

Function works only with hard coded values

This is the code I am working on:
if(connection.doDatabaseRead(findSQL))
{
ResultSet retRES = connection.getResultSet();
int i = 0;
// did we find anything
while( retRES.next() )
{
//read result from query
suiteNum.add(retRES.getString(i)); // this is the problem
i++;
//let other threads breathe
Thread.yield();
}
}
suiteNum is a string vector
When I try to add the database results to the vector the code crashes with this error.
java.sql.SQLException: Column Index out of range, 0 > 1.
I have the same piece of code working elsewhere in the program but I use real numbers like 0, 1 and 2 instead of i and it works fine.
As I do not know how many results the database request will have I need it to be dynamic but it will only work hard coded.
How can I make it work with i ?
The argument to getString is the column index, not the row index as you seem to think. The function returns the value of the given column in the current row, while next advances the cursor to the next row.
You probably mean:
suiteNum.add(retRES.getString(1));
in which case you can lose i altogether.
Java ResultSet objects are 1-indexed in this regard. The first element is at 1, not 0. See the javadoc.
EDIT: That's true too, but indeed the problem is this appears to be used as a row index! it's certainly the column.
This is your problem:
i = 0;
...
retRES.getString(i);
ResultSet.getString(i) gets a String from column number i
You want something like
while(retRes.next()) {
add(retRes.getString(1);
}
column index starts from 1
As I do not know how many results the database request will have I need it to be dynamic but it will only work hard coded. How can I make it work with i
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
See Also
ResultSetMetaData
Let your i start with 1 as specified in the API docs
if(connection.doDatabaseRead(findSQL))
{
ResultSet retRES = connection.getResultSet();
int i = 1;
// did we find anything
while( retRES.next() )
{
//read result from query
suiteNum.add(retRES.getString(i)); // this is the problem
i++;
//let other threads breathe
Thread.yield();
}
}

Categories

Resources