All
I want logical help. I have 100 row in database and get all rows random ally without duplication I have used below code.
public ArrayList<Rows> getRows(){
ArrayList<Rows> myRaw=new ArrayList<Rows>();
Cursor rawCursor=this.db.query(DB_TABLE, null, null, null, null, null, null);
if(rawCursor.getCount()>0){
Random rng = new Random();
rawCursor.moveToFirst();
do {
// Ideally just create one instance globally
ArrayList<Rows> generated = new ArrayList<Raws>();
for (int i = 0; i < 371; i++)
{
while(true)
{
Integer next = rng.nextInt(371) + 1;
rawCursor.moveToPosition(next);
Rows raw=new Raws(rawCursor.getInt(rawCursor.getColumnIndex("_id")),rawCursor.getString(rawCursor.getColumnIndex("raw")),rawCursor.getInt(rawCursor.getColumnIndex("fav")));
if (!generated.contains(raw))
{
// Done for this iteration
generated.add(raw);
break;
}
}
}
myRaw=generated;
} while (rawCursor.moveToNext());
rawCursor.close();
}
return myRaw;
}
Thanks All
You can tell the database to order the records by some random number:
cursor = db.query(DB_TABLE, null, null, null, null, null, "random()");
What about Collections shuffle?
http://developer.android.com/reference/java/util/Collections.html#shuffle(java.util.List)
public ArrayList<Rows> getRows() {
ArrayList<Rows> myRaw = new ArrayList<Rows>();
Cursor rawCursor = this.db.query(DB_TABLE, null, null, null, null, null, null);
if (rawCursor.getCount() > 0) {
// get all the rows
rawCursor.moveToFirst();
do {
Rows raw = new Raws(rawCursor.getInt(rawCursor.getColumnIndex("_id")), rawCursor.getString(rawCursor.getColumnIndex("raw")), rawCursor.getInt(rawCursor.getColumnIndex("fav")));
myRaw.add(raw);
} while (rawCursor.moveToNext());
rawCursor.close();
}
// shuffle the rows in some kind of random order
Collections.shuffle(myRaw);
return myRaw;
}
The answer provided by #CL. could be a better option, but the main difference is that the shuffle method has an option to provide your own Random object, this means that you can seed the random.
//Random with seed;
Random r = new Random(68498493);
Collections.shuffle(myRaw, r);
Related
I want to get date difference between today and expiring day. This is the code I implemented. But this is not returning the right output.
public String[] getDaysList(){
Cursor cursor = db.query("COUPON", null, null, null, null, null, null );
if(cursor.getCount()<1){
cursor.close();
return null;
}
String[] array = new String[cursor.getCount()];
int i=0;
while(cursor.moveToNext()){
String days = "(julianday('now') - julianday(EXPIRED_DATE))";
array[i] = days;
i++;
}
return array;
}
This returns (julianday('now') - julianday(EXPIRED_DATE)). Please help me to get date difference as string to a array here.
The now modifier returns not only the date but also the time.
To change the timestamp to the start of the date, use the date() function:
SELECT julianday(date('now')) - julianday(EXPIRED_DATE) FROM ...
(If the expired column also contains time values, you have to use date() for it, too.)
And to actually execute this, you have to give it to the database:
public String[] getDaysList() {
String days = "julianday(date('now')) - julianday("+EXPIRED_DATE+")";
Cursor cursor = db.query("COUPON",
new String[]{ days }, // query returns one column
null, null, null, null, null);
try {
String[] array = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
array[i++] = cursor.getString(0); // read this column
}
return array.length > 0 ? array : null;
} finally {
cursor.close();
}
}
(And the number of days is not a string; consider using int[] instead.)
Hi please try these one
Cursor cursor = db.rawQuery("SELECT julianday('now') - julianday(DateCreated) FROM COUPON", null);
if (cursor.moveToFirst()) {
do {
array[i]=cursor.getString(0)
} while (cursor.moveToNext());
}
My android app has 2 tables Projects and Tasks.
Each Project can have multiple Tasks.
Like below
Now I want to sum up all proportion values of the single task table
I did it.. but the issue is its adding proportion values from all task tables !
The cursor I coded is as follows
public int sumproportion(long projectId){
int value = 0;
int p = 0;
Cursor cu = mDatabase.rawQuery("SELECT * FROM " + DBHelper.TABLE_TASKS, null);
ArrayList temp = new ArrayList();
if (cur != null) {
if (cur.moveToFirst()) {
do {
temp.add(cur.getString(cur.getColumnIndex("proportion"))); // "Title" is the field name(column) of the Table
} while (cur.moveToNext());
}
}
Object ia[] = temp.toArray();
for(int i=0; i<ia.length; i++)
{
p = Integer.parseInt((String) ia[i]);
value = value + p;
}
System.out.println("Value is: " + value);
return value;
}
When I added cursor as below
Cursor cur = mDatabase.query(DBHelper.TABLE_TASKS, mAllColumns,
DBHelper.COLUMN_TASK_PROJECT_ID + " ="+String.valueOf(projectId),
null, null, null, null);
It doesn't add anything. Can any one help fix it please?
First of all, you can just use query like this SELECT SUM(proportion) from TABLE_TASK. proportion should have numeric type.
Secondly, verify that your Cursor return any rows. Probably you pass wrong projectId if there no rows.
I am populating AChartEngine from sqlite database and I need all of the data to be displayed. The problem I'm having is when I delete a record the graph series stops populating at the deleted record. I need to find a way to skip over deleted/empty records and continue populating my graph. I need it to do it the same way listview skips over deleted records and keeps on displaying all rows. I am very new to a lot of this and am having a very difficult time with this. I have tried to write if statements in order to skip deleted/empty rows but nothing seems to work. Thank you for helping!
in my graphing activity:
for (int i = 1; !c.isAfterLast(); i++) {
String value1 = db.getValue1(i);
String value2 = db.getValue2(i);
c.moveToNext();
double x7 = Double.parseDouble(value1);
double y7 = Double.parseDouble(value2);
myseries.add(x7, y7);
}
I am getting error: CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
If I surround with try and catch it will populate rows up until the deleted record.
"EDIT"
in my sqlite database:
public String getValue1(long l) {
String[] columns = new String[]{ EMP_DEPT };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(0);
return value2;
}
return null;
}
Your issue is that your safety net for commands on rows that don't exist is to use if (c != null){ and then perform your commands inside that block, but a Cursor request from a query will never come up null, it will instead result in a cursor object with no rows.
A more appropriate solution to use this as your safety net instead if (c.moveToFirst()){ Because the method itself returns a boolean for if the method actually carried itself out in the first place - true if it moved and false if not (which occurs when there's no rows to move into). another check, if you wish, would be to see how many rows the cursor has with c.getCount().
Additionally, you should combine your methods so that you don't make redundant queries to the database:
public String[] getValues(long l) {
String[] results = new String[2];
String[] columns = new String[]{ EMP_DEPT, EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c.moveToFirst()) {
results[0] = c.getString(0);
results[1] = c.getString(1);
} else {
Log.d("GET_VALUES", "No results formed from this query!");
}
return results;
}
You should use a single query to get all values at once:
SELECT Date1 FROM MyTable WHERE id BETWEEN 1 AND 12345
or:
db.query(EMP_TABLE, columns, EMP_ID + " BETWEEN 1 AND " + ..., ...);
Then missing values will just not show up when you iterate over the cursor.
I'm creating a simple multiple choice trivia game in Android where the user has three choices. The correct answer choice is pulled directly from the DB, and the two other wrong choices are randomly selected using a method. I put the correct and 2 wrong answers in an array and shuffle the array. The game works fine when in the random selection method I'm only grabbing one column from the row. Now I'd like to grab 3 columns from each random row. So then my problem is how to write the code that is "get two random rows with three columns and put the resulting array into an array that can be shuffled". Here's my working code:
DBAdapter:
// ---Grabs 2 RANDOM ---
public String[] getRandomHA() {
Cursor cursor = this.db.query(
"hdtable Order BY RANDOM() LIMIT 2",
new String[] { KEY_HA }, null, null, null, null, null);
if (cursor != null) {
int i = 0;
String colStrings[] = new String[cursor.getCount()];
while (cursor.moveToNext())
{
colStrings[i] = cursor.getString(0);
i++;
//cursor.close();
}
return colStrings;
}
return null;
}
// --- END Grabs 2 RANDOM ---
Main Activity:
// --- Random 2 answers ----
public void getRandom() {
dba.open();
String[] wrong2 = dba.getRandomHA();
dba.close();
}
shuffle an Array:
// --- shuffle array ----
String[] numbArray = { rightAnswer[2], wrong2[0], wrong2[1] };
List<String> aList = new ArrayList<String>();
for (String s : numbArray)
aList.add(s);
Collections.shuffle(aList);
TextView[] tVs = { optionA_TV, optionB_TV, optionC_TV };
for (int i = 0; i < tVs.length; i++) {
tVs[i].setText(aList.get(i));
}
// --- END shuffle array ----
So is this how I'd write the DB Adapter method?
// ---Grabs 2 RANDOM ---
public String[] getRandomHA() {
Cursor cursor = this.db.query(
"hdtable Order BY RANDOM() LIMIT 2",
new String[] { KEY_Y, KEY_MD, KEY_HA }, null, null, null, null, null);
if (cursor != null) {
int i = 0;
String colStrings[] = new String[cursor.getCount()];
while (cursor.moveToNext())
{
colStrings[i] = cursor.getString(0);
colStrings[i] = cursor.getString(1);
colStrings[i] = cursor.getString(2);
i++;
//cursor.close();
}
return colStrings;
}
return null;
}
// --- END Grabs 2 RANDOM ---
and if the above method is correct, then how would I write the main activity methods to reflect the nested arrays?
The first thing that comes to my mind is to use an instance of the java.util.Random class to call one of the nextXXX() methods to generate a random number. Use that number to select a row from the database to use as your random wrong answer.
I want to display the database in a list in Android. I am using cursors for that. I am getting the columncount and using for loop I am moving the cursor. But the database is not displayed. Please help. Here is my code:
List<String> s;
Cursor c = db.query(Geo_Create_Table, new String[] { lat + "", lon + "", result1 }, null, null, null, null, null);
c.moveToFirst();
int count = c.getColumnCount();
for (int i = 0; i < count; i++)
{
c.moveToNext();
}
Please let me know if there is any other simpler approach.
You seem to have lost some of your code there. You should edit your post, I don't have the privilages. The column count will give you the number of columns (fields) in each row and shouldn't be used to loop through the cursor's records if that is what you're trying to do, you should probably use the getCount() method instead.
List<String> s;
Cursor c=db.query(Geo_Create_Table, new String[]{lat+"",lon+"",result1}, null,null, null, null, null);
c.moveToFirst();
int count=c.getCount();
for(int i=0; i < count; i++)
{
....
c.moveToNext();
}
Alternatively, in my code below you query moveToFirst(), if this returns true it means there are records to be traversed. The I use a do/while loop to move through each record (note: c.moveToNext()).
List s;
Cursor c=db.query(Geo_Create_Table, new String[]{lat+"",lon+"",result1}, null,null, null, null, null);
if (c.moveToFirst()) {
do
{
...
c.moveToNext();
}
while (!c.isAfterLast());
}