Get random items from firebase min 3 max 5 - firebase

I am trying to get random items from my firebase database and it almost works,
sometimes I only get one or two items when the minimum is 3 and max is 5.
Every item has an index and it's getting the items that startAt(startindex) and endAt(startIndex+randomNumber).
Is there any other way to do this other than using an index on each item in the database?
Here is how the code looks now:
randomNumber = getRandomInt(3,5);
listView = (ListView)view.findViewById(R.id.listView);
int startIndex = (int)(Math.random() * childs+1);
adapter = new FirebaseListAdapter<TraningData>(getActivity(),TraningData.class,R.layout.layout_traning_item,ref_1
.orderByChild("index")
.startAt(startIndex)
.endAt(startIndex+randomNumber)) {
#Override
protected void populateView(View view, final TraningData td, int i) {
//Populating over here!
}
};
listView.setAdapter(adapter);

Since Firebase never want to add this feature.
Here how I solved it by adding all to an array and then make a random selection.
ArrayList<TraningData> randomSelected = new ArrayList<>();
Random rand = new Random();
int numElements = getRandomInt(3,5);
for(int i = 0;i < numElements;i++){
int randomIndex = rand.nextInt(traningData.size());
randomSlected.add(traningData.get(randomIndex));
}
cAdapter = new CustomAdapter(getActivity(),randomSlected);
listView.setAdapter(cAdapter);

Related

Can I remove a column if it's part of a primary key? [duplicate]

is there a way to remove primary key from the datatable Or is there any way to remove the constraints of "PK" first and then remove the column itself?
Thanks!
UPDATED:
dtTable.Columns.Add(new System.Data.DataColumn("PRIMARY_KEY", typeof(System.Int32)));
dtTable.PrimaryKey = new DataColumn[1] { dtTable.Columns["PRIMARY_KEY"] }; // throws an error
dtTable.Columns["PRIMARY_KEY"].AutoIncrement = true;
You can remove primay key using
DataTable.PrimaryKey = null;
you can delete data table column using
DataTable.Columns.Remove("column name here");
I found that sometimes after removing PrimaryKey from a DataTable:
MyDataTable.PrimaryKey = null;
the Unique setting remains true on the member columns of the deleted PrimaryKey.
My solution:
public static void KillPrimaryKey(DataTable LocDataTable)
{
int LocPriKeyCount = LocDataTable.PrimaryKey.Length;
string[] PrevPriColumns = new string[LocPriKeyCount];
// 1. Store ColumnNames in a string Array
for (int ii = 0; ii < LocPriKeyCount; ii++) PrevPriColumns[ii] = LocDataTable.PrimaryKey[ii].ColumnName;
// 2. Clear PrimaryKey
LocDataTable.PrimaryKey = null;
// 3. Clear Unique settings
for (int ii = 0; ii < LocPriKeyCount; ii++) LocDataTable.Columns[PrevPriColumns[ii]].Unique = false;
}

ASP.NET/SQL Function not storing all values in a loop

So I'm creating a monopoly game, and I've got two functions which read/write information about the game to/from a database so it can be retrieved between postbacks. I also have a start game function which initialises everything to 0 and then calls the writeToDatabase(). createArrays() just creates a list of players/squares, squares have been removed as they'not relevant.
The problem I'm having is I believe it is only storing some of the values within the loop. When the start game function is called it correctly sets the players positions to 0, and their money to 1500, however for some reason when reading from the database again the 4th players details immediately go back to what they were during the previous session.
private void readFromDatabase()
{
createArrays();
for (int i = 0; i < players.Count(); i++)
{
players[i].SetID(Convert.ToInt32(players_table.GetRow(i)["ID"]));
players[i].SetPosition(Convert.ToInt32(players_table.GetRow(i)["position"]));
players[i].SetMoney(Convert.ToInt32(players_table.GetRow(i)["money"]));
players[i].SetInJail(Convert.ToBoolean(players_table.GetRow(i)["isInJail"]));
players[i].SetIsBankrupt(Convert.ToBoolean(players_table.GetRow(i)["isBankrupt"]));
}
currentPlayerID = Convert.ToInt32(gameinfo_table.GetRow(0)["CurrentPlayerID"]);
currentSquareID = Convert.ToInt32(gameinfo_table.GetRow(0)["CurrentSquareID"]);
freeParkingAmount = Convert.ToInt32(gameinfo_table.GetRow(0)["FreeParkingAmount"]);
currentPlayer = players[currentPlayerID];
CurrentSquare = squares[currentSquareID];
}
private void writeToDatabase()
{
CurrentSquare = squares[currentSquareID];
for (int i = 0; i < players.Count(); i++)
{
SQLDatabase.DatabaseRow prow = players_table.GetRow(players[i].GetID());
prow["ID"] = players[i].GetID().ToString();
prow["position"] = players[i].GetPosition().ToString();
prow["money"] = players[i].GetMoney().ToString();
prow["isInJail"] = players[i].IsInJail().ToString();
prow["isBankrupt"] = players[i].IsBankrupt().ToString();
players_table.Update(prow);
}
SQLDatabase.DatabaseRow girow = gameinfo_table.GetRow(0);
girow["CurrentPlayerID"] = currentPlayerID.ToString();
girow["CurrentSquareID"] = CurrentSquare.GetID().ToString();
girow["FreeParkingAmount"] = freeParkingAmount.ToString();
gameinfo_table.Update(girow);
}
private void startGame()
{
createArrays();
currentPlayerID = 0;
currentPlayer = players[0];
CurrentSquare = squares[0];
writeToDatabase();
}
private void createArrays()
{
for (int i = 0; i < 4; i++)
{
Player player = new Player(i);
players.Add(player);
}
}
I really can't work out why this is happening, as when it creates the player array it loops through 4 times, therefore creating 4 brand new players, and immediately overwriting the details in the database. It just seems odd it works perfectly fine for the first 3 players but the 4ths details don't seem to change. Any help would be greatly appreciated, I'm sure it something simple but I have spent hours on this and haven't got anywhere.

Loop through multiple ComboBoxes to get data JavaFX

I am trying loop through all the ComboBoxinstances I made in order to get the value the user picks and add that value to a new ArrayList, but I am stuck on how to proceed making the loop to get the values.
// row for comboboxes
HBox numBox = new HBox();
numBox.setSpacing(16);
numBox.setAlignment(Pos.CENTER);
vbox.getChildren().add(numBox);
// setup loop to create 8 combo boxes for user to pick
int comboNum = 8;
ComboBox<Integer> binaryBox = new ComboBox<Integer>();
for (int i = 0; i < comboNum; i++) {
binaryBox = new ComboBox<Integer>();
List<Integer> binaryList = new ArrayList<Integer>();
binaryList.add(0);
binaryList.add(1);
for (Integer num : binaryList) {
binaryBox.getItems().addAll(num);
}
binaryBox.setValue(0);
numBox.getChildren().add(binaryBox);
}
// way to get the value from each combo box
ChangeListener<Number> update =
(ObservableValue <? extends Number> ov, Number oldValue, Number newValue) -> {
for (int i = 0; i < comboNum; i++){
//todo
}
};
Each ComboBox has a SelectionModel from which you can obtain the selectedItem. First, create a list of combo boxes and populate it with your instances of ComboBox<Integer>:
List<ComboBox<Integer>> list = new ArrayList<>();
for (int i = 0; i < comboNum; i++) {
ComboBox<Integer> binaryBox = new ComboBox<Integer>();
list.add(binaryBox);
…
}
Later, you can loop through the list to retrieve the selected items using getSelectedItem():
for (ComboBox<Integer> combo : list) {
System.out.println(combo.getSelectionModel().getSelectedItem());
}

Keep getting out of bounds exception, don't know why?

I'm making a 3 dimensional tic tac toe game. The game is complete and works fine, however, the assignment demands that (for testing game situations) the program take in a file of integers that places pieces on the game board. It takes in the file from the Unix command line.
However, the game is supposed to run from start if no file is entered in command line. I'm getting an out of bounds exception and don't know why for the life of me. Any help would be greatly appreciated.
Portion of code for getting file and storing the integers:
public class Test {
static int board[][][] = new int[4][4][4];
static boolean ComputerMoved = false;
static int[] sums = new int[76];
static int n = 0;
public static void main(String[] args) throws FileNotFoundException {
//Method purpose is to look and see if there is a startup file given to
//initally setup the board. If not, plays an empty board and prompts the
//user for the first move.
Scanner scan = new Scanner(new FileInputStream(args[0]));
if (args.length > 0) {
int size = scan.nextInt();
for (int i = 0; i < size; i++) {
int level = scan.nextInt();
int row = scan.nextInt();
int column = scan.nextInt();
int value = scan.nextInt();
level = level % 4;
row = row % 4;
column = column % 4;
board[level][row][column] = value;
}
}
Hint: It appears that the out of bounds exception is coming not from your array, but rather your scanner. Could it be possible you don't have "enough" numbers to scan?

Using while to get 13 digits

I am new to programming, I need to generate 13 random number using loop (while) number + 1 when the number reaches 13, I will like to store that number in text box.
Any help will be welcomed
What you see below is a 'static' class, which needs no initialization. So, with this in your project, you can just call RandomInts.GetRandomInts() and pass it on into your model for the input box to present to your user(s).
public static class RandomInts
{
private static int _x = 0;
public static int GetRandomInts()
{
var i = 0;
var rnd = new Random();
while (i < 13)
{
_x = rnd.Next();
i++;
}
return _x;
}
}
Here is with upper and lower bounds:
var x = random.[Next](minr, maxr)

Resources