Randomly place a text on some buttons - java

I am trying to move, say a text or number in setText(Integer.toString()) format randomly on 4 different buttons at each click. I am able to obtain the object form of it, but it is worthless since I can't get that information out of it.
This is my code:
public void clickButton(View view){
List mo = new ArrayList();
mo.add(Button);
mo.add(Button1);
mo.add(Button2);
mo.add(Button3); // these are defined in OnCreate method
Random rko = new Random();
int koo = rko.nextInt(mo.size());
Object a = mo.get(koo);
Log.i("here", String.valueOf(mo.get(koo)));
I get this output in the logs up on each click
android.support.v7.widget.AppCompatButton{71c6fe0 VFED..C.. ...PH... 697,708-928,933 #7f0c0052 app:id/Button2}
android.support.v7.widget.AppCompatButton{71c6fe0 VFED..C.. ...PH... 697,708-928,933 #7f0c0052 app:id/Button3}
android.support.v7.widget.AppCompatButton{71c6fe0 VFED..C.. ...PH... 697,708-928,933 #7f0c0052 app:id/Button}
I am new to this. Please help
Thanks.

hi i believe that u should use tags on your buttons p = new Random().nextInt(21);
button.setTag(Integer.toString(alpha));
//here alpha is the text that you wanted to put on the button,get the text from button by using appropriate code
cbutton.setTag(Integer.toString(" "));

You could try writing AppCompatButton instead of Object and then you should be able to get the text of a button with a.getText(); and change the text of a button with a.setText();.

#Rushikesh You did not restrict the random generated number within the range of 0-4.
The size of array list of button is 4 so the the index must be 0-4 to avoid the IndexOutOfBoundsException
List mo = new ArrayList();
mo.add(Button);
mo.add(Button1);
mo.add(Button2);
mo.add(Button3);
int koo = (int)(Math.random() * (10-(mo.size()+1))); // generated number range will be 0-4
Object a = mo.get(koo);

Related

Changing variables on button clicks - or in events in general

Introduction to the problem
It seams impossible to change a Veriable in a event (like so for example button.setOnAction(e -> { x = x+2});) and I can see why, but what if that's exactly what I need? It's actually not the first time that I needed to do that, but last time I got around it by saving the changed property directly to a file.
This time I used a really tricky trick to create a 'fake variable' by using the text in an invisibe TextField as my veriable. It works, that's not the problem, but I'd like to have a more 'elegant' salution :D
Friuts of my research
The only two salutions I could find were to either declare a Variable as a class member (which I don't want to do seeing that I already have six of them and don't want to tripple that amount) or to use seperate classes. (I found that here: How to change a variable when a button has been clicked in JavaFx )
The programm
Here is the code of my popup window (I'll spare you of the rest of my stupid programm ^^ ), I'll explain what it does after the codebox. (Note that props is a properties object and one of the mentioned class members as well as propPath (meaning I declared it at the very top of the programm so that it can be accessed from every function)):
private void createNewBuff() throws Exception {
Stage popupStage = new Stage(StageStyle.UTILITY);
popupStage.initModality(Modality.APPLICATION_MODAL);
popupStage.setTitle("Creating a new Buff");
popupStage.setMinWidth(400);
popupStage.setMinHeight(300);
GridPane layoutGP = new GridPane();
layoutGP.getColumnConstraints().addAll(
new ColumnConstraints(200), //TextField column col 0
new ColumnConstraints(10), //Gab column col 1
new ColumnConstraints(60), //tf manips column col 2
new ColumnConstraints(30), //Gab column col 3
new ColumnConstraints(80)); //Main buttons col col 4
TextField tfName = new TextField("Unknown Buff");
tfName.setPromptText("Name of the Buff, e.g. \"Unknown Buff\"");
Label lblName = new Label("Name");
layoutGP.add(tfName, 0, 0);
layoutGP.add(lblName, 2, 0);
TextField varTF = new TextField();
TextField tfEffect = new TextField();
tfEffect.setPromptText("Effect of the Buff, e.g. \"+10 LP\"");
Button btnAdd = new Button("Add");
btnAdd.setOnAction(e -> {
String input = tfEffect.getText();
String[] comps = input.split(" "); //components
if (Array.getLength(comps) == 2) {
if (input.contains("+")) {
varTF.setText(varTF.getText() + input + ";");
layoutGP.add(new Label(input), 0, 1 + Array.getLength(varTF.getText().split(";")));
} else if (input.contains("-")) {
varTF.setText(varTF.getText() + input + ";");
layoutGP.add(new Label(input), 0, 1 + Array.getLength(varTF.getText().split(";")));
}
}
});
layoutGP.add(tfEffect, 0, 1);
layoutGP.add(btnAdd, 2, 1);
Button btnDone = new Button("Done");
btnDone.setOnAction(e -> {
int buffNumber = 1;
while (props.containsKey("Buff-" + buffNumber + "-name"))
buffNumber++;
props.setProperty("Buff-" + buffNumber + "-name", tfName.getText());
props.setProperty("Buff-" + buffNumber + "-effect", varTF.getText());
try {
FileOutputStream streamOut = new FileOutputStream(propPath);
props.store(streamOut, null);
streamOut.close();
popupStage.close();
}catch (IOException someE){/*something meaningful*/}
});
btnDone.setMaxWidth(Double.MAX_VALUE);
Button btnCancel = new Button("Cancel");
btnCancel.setOnAction(e -> popupStage.close());
btnCancel.setMaxWidth(Double.MAX_VALUE);
layoutGP.add(btnDone, 4, 0);
layoutGP.add(btnCancel, 4, 1);
layoutGP.setAlignment(Pos.TOP_CENTER);
Scene popupScene = new Scene(layoutGP);
popupStage.setScene(popupScene);
popupStage.showAndWait();
}
I wanted to post a picture there of how it looks once you start it and another of how it looks after you used it, but my reputation is still to low ^^
Therefor I'll provide the links to the pictures: Befor something was done http://i.imgur.com/Wx3nIEX.png After it's used http://i.imgur.com/5QNmWP6.png
What the programm does
It's pretty strait forward actually: my main programm is a character sheet and with that popup you can add a buff to it (later I'll make it so that the effects of the buff get calculated into the values of the sheed, but one step at a time ^^ ). You can set the name of the buff you want to create ("Unknown Buff" is the standart in case you forgett to set one) and then you can simply add defferent effects by writing tem into the TextField and then pressing the 'Add' button. They will list themself top to bottom in the free space. They will also, behind the scenes, save themself as one large string into a hidden TextField to make figuring out in which line each individual Effect has to be displayed and to save it to the properties file afterwards. (and that salution with the undisplayed textfield is exactly the trick I want to remove and turn into a more 'elegant' salution)
Detailed explanaition of the code
At first the Stage is created. Then the layout is made in form of a gridpane und the column sizes are set (every second column is for spacing reasons). After that I'm creating the line for the name (the label and the textfield) and also my tricky textfield that's used as a String variable. Now I'm creating the effect textfield and add button, as well as the event for the button: at first it turns the input from the textfield into a easier to read name and splits it into it's components (at first I used tfEffect.getText() and tfEffect.getText().split(" ") inside the code below, but that was really messy) now I have if statements to verify it and make sure that the Effect is in the right format (that format beeing the amount a certain stat is raised or lowerd, consisting of either a plus or a minus symbol at the beginning and a number after that; followed by a space and then the index of the stat (I haven't been able to implement verifying if the typed thing actually is a valid stat, maybe that'll be content of a future question ;D )). After verifying the programm it adds the effect below all the others. If you're done and happy with you're buff you can click the Done button, it will first look up how many Buffs already exist, then assign the new on a number and save it all to the properties file. The cancel button with of course just cancel it and at the bottom I'm setting the scene and calling the stage.
What I'm hoping for with this question
Now I think you have a pretty clear idea of what I need to do and why I couldn't find a better salution then using a hidden TextField as a variable and I hope it's because I'm a beginner and not because there actually is no better way of doing it ^^
Also if you actually read all of this you may found one or two things I can improve besides that, but that would be the special bonus ;D

Android change background dynamically randomly from array

I am new to Android and I am trying to change the background of an ImageView in Java. This part is working. The problem is I have a 4 images and I would like to randomly choose one and display the image.
For example I have an array of drawables as such:
String[] images = new String[4];
images[0] = "R.drawable.i1";
images[1] = "R.drawable.i2";
images[2] = "R.drawable.i3";
images[3] = "R.drawable.i4";
I was trying to use this to choose a random one:
int idx = new Random().nextInt(images.length);
String random = (images[idx]);
However, I cannot seem to get the setBackground for the imageview to work with these.
For example, I tried:
images.setBackgroundDrawable( getResources().getDrawable(R.drawable.images[random]) );
I know I am not doing it correctly however that is what I would like to do.
You can try this:
int[] images = new int[4];
images[0] = R.drawable.i1;
images[1] = R.drawable.i2;
images[2] = R.drawable.i3;
images[3] = R.drawable.i4;
int idx = new Random().nextInt(images.length);
int random = (images[idx]);
images.setBackgroundDrawable( getResources().getDrawable(images[random]) );
Your problem seems to be, that you want to call a Method through a String. Thats absolutly nonesense unless you work with java SQL calls or XML...whatever. you need the actual image Object if you call your draw method.
well there is a simple solution :D
Instead of using an String[]. Use a ArrayList<Image>
after that you can call the method list.shuffle().
some pseudo Code:
ArrayList<Image> yourImages = new Arraylist<>();
yourImages[1] = image1
yourImages[2] = image2
...
yourImages.shuffle(); //shuffles your list
print(yourImages[1]);
print(yourImages[2]);
...
the first advatage is that your pictures will be displayed at random.
the second advantage is that there is no duplicate of each displayed picture.
PS: It would also work with an Image[] + the Random class. But how come, choose a String[]. a String is a representation of an Text... not an image.

Android/Java "Convert" String to Button

I have this code:
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
String object = "button";
int num;
num = r.nextInt(3 - 1) + 1;
String total = object + num;
I want do set the text for one of the buttons chosen randomly. Something like this:
button<num>.setText(some_text);
^ here instead of <num> should be 1 or 2
and has to be chosen randomly
Like Ondkloss said, you can add your buttons to an array, then randomly select one from that array.
Button[] buttonArray = new Button[2];
buttonArray[0] = button1;
buttonArray[1] = button2;
Random r = new Random();
buttonArray[r.nextInt(2)].setText(someRandomText);
Keep in mind that if you change the number of buttons you will need to change the numbers that I have used (new Button[2] & r.nextInt(2)). My solution works specifically for an array of length 2 containing only 2 buttons. But other than changing the numbers in the array creation and the random number generation to match the number of buttons you have, this solution should work just fine.
No, i want change the text of the button.
Then just do something like this
button1.setText("Just some strings here");

How to display ArrayList data in tabular format in android

I have a problem in display data in to respective fields.
I have like this data from database in arraylist.
ArrayList<String> ar= new ArrayList<String>;
ar data is:-> [2, India#1, USA#3, Australia#1, Germany#2];
How to get above data like this arraylist:
Country ArrayList: India,USA,Australai, Gernamy
valucheck arraylist: 1,3,1,2
Here first element is id and others ara values. Like India- EditText field and integer(1,2,3) is radiobutton.
India 1(checked first radio button)
India 3(checked third radio button)
Australia 1(Checked first radio button)
Germany 2(Checked second radio button)
I have been trying lots of time, but could get proper solution, so please update some tricks for display those data
I want to display like this data in to tabular form
What i did,
List<EditText> listET = new ArrayList<EditText>();
ArrayList<String> first= new ArrayList<String>();
if(edittextfield){
first.add("India");first.add("USA");first.add("Australia");first.add("Germany");
EditText et_text_input = new EditText(getContext());
for(int p=0;p<listET.size()+1;p++){
et_text_input.setText(first.get(p));
listET.add(et_text_input);
ll.addView(et_text_input);
}
}else if(radiobuttonfield){
what to do in radiobutton.
}
Here If i put data in list of first in static, then works fine, but how to put about ar list data into first list ..
Take a look at the ListView-class.
Look into ArrayAdapter (http://developer.android.com/reference/android/widget/ArrayAdapter.html) which allows you to display the data in a ListView.
Assuming you mean output to console, you could step through the list and display it's items with tab separation
//As an example of usage, not a solution using your structures
for (MyObject o : ar)
{
System.out.println(o.getCountry() + "\t" + o.getValue())
}

List of List of Buttons is empty

I'm working around with GWT.
Since I have a SQL db and my queries result set size is unknown I thought it would make sense to use Lists.
Actually I have one list of buttons and a second list of list of buttons.
The reason is because I have one table which stores groups and one which stores the actual data. Both of them in result should be buttons.
By clicking on a group button my layout is filled with the data buttons between the group buttons.
Now my db connection isn't ready to use so I wrote a function that fills my lists with fake data. Same for the groups.
public void fakeGroupData () {
// Group index 0
btnGroupList.add(new Button("Group a"));
// Group index 1
btnGroupList.add(new Button("Group b"));
...
}
public void fakeData () {
// Group index 0
btnDataList.add(new Button("Data 1.1"));
btnDataList.add(new Button("Data 1.2"));
btnDataList.add(new Button("Data 1.3"));
btnDataListList.add(btnDataList);
btnDataList.clear();
// Group index 1
btnDataList.add(...
}
Declaration looks like this
List<Button> btnGroupList = new ArrayList<Button>();
List<List<Button>> btnDataListList = new ArrayList<List<Button>>();
List<Button> btnDataList = new ArrayList<Button>();
When trying to get the ButtonList of the ListList the error appears.
int grpIndex = Panel.getWidgetIndex(grpBtn);
// grpBtn is equal to (Button)event.getSource() called by btnGroup ClickHandler
btnDataList.clear()
btnDataList = btnDataListList.get(grpIndex);
int loopEnd = btnDataList.size() - 1;
for (int i = 0; i<=loopEnd; i++) {...
"loopEnd" contains "-1" and nothing happens :(. I tried to debug here, everything seems ok.
"grpIndex" has the right index so the the right List is loaded.
But why is it empty? When debuggin the fakeData function eclipse shows the right size in the ButtonList.
Hope you can help me :)
btnDataList.clear(); will empty your referenced list objects.
for each Group index you need a new list. do like this
btnDataList = new ArrayList<Button>(); instead of btnDataList.clear();
// Group index 0
btnDataList.add(new Button("Data 1.1"));
btnDataList.add(new Button("Data 1.2"));
btnDataListList.add(btnDataList);
// Group index 1
btnDataList = new ArrayList<Button>();
btnDataList.add(new Button("Data 2.1"));
btnDataList.add(new Button("Data 2.2"));
btnDataListList.add(btnDataList);

Categories

Resources