I want to get random data without repeat - android

I want to get random data from database(sqlite) without repeat.Can anyone help me ..
DBManager *databaseManager = (DBManager *)[[DBManager alloc] init];
NSArray *array=[databaseManager readQuestionFromDatabase];
que=[array objectAtIndex:0];
self.lblQuestion.text=que.question;
[self.btnOption1 setTitle:que.questionoption1 forState:UIControlStateNormal];
[self.btnOption2 setTitle:que.questionoption2 forState:UIControlStateNormal];
[self.btnOption3 setTitle:que.questionoption3 forState:UIControlStateNormal];
[self.btnOption4 setTitle:que.questionoption4 forState:UIControlStateNormal];

This is another answer which uses same random number generation without repetition but avoids multiple query execution.
String randomRowData = "";
selQuery = "SELECT MYFIELD FROM MYTABLE ";
ArrayList<String> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++) {
list.add(MYFIELD_VALUE); // All DB Data here
}
Random rand = new Random();
while(list.size() > 0) {
int index = rand.nextInt(list.size());
randomRowData = list.remove(index); // Will display the rows without repetition
/* USE THE ROW DATA APPROPRIATELY */
}

This approach using Random Number Generation via java and ROWNUM for SQLITE should help you. But you might have to execute queries multiple times.
int DBSize = getDBSize();
int randomRowNum = 0;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++) {
list.add(i);
}
Random rand = new Random();
while(list.size() > 0) {
int index = rand.nextInt(list.size());
randomRowNum = list.remove(index);
selQuery = "SELECT * FROM MYTABLE WHERE ROWNUM = " + randomRowNum + " ORDER BY SOME_UNIQUE_SORT_ORDER";
// EXECUTE SELECT QUERY AND YOU WOULD GET RANDOM ROWS here.
}
private int getDBSize ()
{
int retVal = 5;
retVal = // Select count(1) from myTable;
return retVal; //(Assuming I have 5 records in DB)
}
Note: Make sure your sort order in ORDER BY is unique. Else results would not be as expected.

Related

records inserted in a sqlite table are the same for each row

I have a JSONArray which contains many records. I want to compare a string inside those object with a similar(I know it has the same value) record in my SQLite db. but when I loop the table each row value has the first row value.
INSERT A RECORD TO DB >> it returns different value
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
JSONObject row = pagamenti.getJSONObject(i); /** LOOP OGGETTI */
String fattura = row.getString("Fattura");
String descrizione = row.getString("Descrizione");
String scadenza = row.getString("Data Scadenza");
String importo = row.getString("Importo");
String stato = row.getString("Stato Pagamento");
// FATURA SHOW ALL DIFFRERENtS VALUE CORRECTLY
fieldsNameTasse.add("fattura");
fieldsValueTasse.add(fattura);
Toast.makeText(getContext(), fattura.toString(), Toast.LENGTH_LONG).show();
fieldsNameTasse.add("descrizione");
fieldsValueTasse.add(descrizione);
fieldsNameTasse.add("scadenza");
fieldsValueTasse.add(scadenza);
fieldsNameTasse.add("importo");
fieldsValueTasse.add(importo);
fieldsNameTasse.add("stato");
fieldsValueTasse.add(stato);
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
CHECK DB ROW VALUE << it returns always the first value
/** SHOW ALWAYS THE SAME VALUE*/
int counter = 0;
Cursor cursor = DBmanager.readAll("TasseIncoming");
while(cursor.moveToNext()) {
String ffattura = cursor.getString(cursor.getColumnIndex("fattura"));
counter++;
Toast.makeText(getContext(), ffattura+" - "+counter, Toast.LENGTH_LONG).show();
}
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
Every time you loop, you're just adding values to the end of what's already in those ArrayLists. So there's lots of duplicate column names with different values for each. Some quick testing:
sqlite> create table foo(a, b);
sqlite> insert into foo(a,b,a,b) values(1,2,3,4);
sqlite> select * from foo;
a b
---------- ----------
1 2
indicates that when a column is included multiple times in an INSERT, only the first corresponding value is used. Hence only ever getting the values from the first iteration of the loop.
The easy fix is to move those variable definitions inside the loop, so each insert is done with a fresh set of columns and values:
for (int i = 0; i < pagamenti.length(); i++) {
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}

Need help generating a unique request code for alarm

My app structure is like, there are 1000 masjids/mosques and each masjid has been given a unique id like 1,2,3,4 ..... 1000 . Now each mosque has seven alarms associated with it , I wish to generate a unique request code number for each alarm so that they don't overlap each other,
Following is the code:
//note integer NamazType has range 0 to 5
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return (MasjidID *(10)) + (namazType);
}
Will this code work?
you can simply concatenate masjidID and namaztype( or specifically namaz ID). This will always return unique.
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return Integer.ParseInt(String.valueOf(MasjidID)+""+NamazType)
}
Use Random class:
Try out like this:
//note integer NamazType has range 0 to 5
public int generateRequestCodeForAlarm(int MasjidID, int NamazType)
{
return (MasjidID * (Math.abs(new Random().nextInt()))) + (namazType);
}
It will work for sure.
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return (MasjidID*(10)) + (NamazType );
}
Output:
Have a look at this
If MasjidID and NamazType are unique, then
Integer.parseInt( MasjidID + "" + NamazType );
would be enough to do the trick!
Example:
Masjid ID = 96, Namaz type = 1, Unique no = 961
MasjidId = 960, Namaz type = 1, Unique no = 9601
MasjidID = 999, Namaz type = 6, Unique no = 9996
I don't find any way in which it would get repeated. However, it is very similar to
(MasjidID * 10) + NamazType
Irrespective of MasjidID and NamazType, if a random number needs to be generated, this can be used.
public class NoRepeatRandom {
private int[] number = null;
private int N = -1;
private int size = 0;
public NoRepeatRandom(int minVal, int maxVal)
{
N = (maxVal - minVal) + 1;
number = new int[N];
int n = minVal;
for(int i = 0; i < N; i++)
number[i] = n++;
size = N;
}
public void Reset() { size = N; }
// Returns -1 if none left
public int GetRandom()
{
if(size <= 0) return -1;
int index = (int) (size * Math.random());
int randNum = number[index];
// Swap current value with current last, so we don't actually
// have to remove anything, and our list still contains everything
// if we want to reset
number[index] = number[size-1];
number[--size] = randNum;
return randNum;
}
}

Indexing Android

My problem is I have around 1000+ records in an Android App
string field1;
string field2;
string field3;
string field4;
//...
I want to search in this set of records and get the best results on two fields (field1 and field2).
Currently I read each record and compare() (string compare) with the text i want to search so that takes a long time.
What is the best method to perform search?
Store each records in SQLite DB and do "select query where like"
Hash-Mapped
? any other suggestions?
Or may be create an Index of the records and do search.
If you want to search for not exact matches, I would try to make an ArrayList of MyAppRecord where
public class MyAppRecord {
private String record;
private int deviance;
}
and get for each record the deviance of the String you want to find with:
public static int getLevenshteinDistance (String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
}
save it to your MyAppRecord-object and finally sort your ArrayList by the deviance of its MyAppRecord-objects.
Note that this could take some time, depending on your set of records. And NOTE that there is no way of telling wether dogA or dogB is on a certain position in your list by searching for dog.
Read up on the Levensthein distance to get a feeling on how it works. You may get the idea of sorting out strings that are possibly to long/short to get a distance that is okay for a threshold you may have.
It is also possible to copy "good enough" results to a different ArrayList.

Array integer Android

ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.

Array access producing unwanted result

I am getting an unusual result when attempting to place a value in an array.
I have an array table[] of a simple class result{ int score, long time, string ID}
Intention is to have a sort of leader board.
My code happily finds the correct place to insert a new score if it is in the top 10.
int ix = 0;
int jx = 10; //
while ( ix < jx )
{
if (points > sTable[ix].points)
{
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
}
ix++;
}
Problem is that when I try to insert the score using sTable[ix].score = score;
The value gets written to sTable[ix].score and also sTable[ix +1].score.
It is repeatable, it occurs at any value of ix, I have single stepped through the code and as far as I can tell the command only executes once.
Has anyone seen this before?
That because you copied the object reference to the next element in the array. You should copy the values, or create a new object:
Option A:
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx].time = sTable[jx -1].time;
sTable[jx].score = sTable[jx -1].score;
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
Option B:
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
sTable[ix] = new Result(score, time, ""); // Or however you construct the object

Categories

Resources