How to setText on the ArrayList of Button in Android - java

I am making a random number generator app in this app we will take the random number range like 0-100 then when we click on the generate button it will set the number on the button.
Manually we can set that value of random number and set it on button. If i set the random number 4 will always correct it means the fourth button will always be correct.
Now I want to make the shuffle of random number on button so I create the Random number Array and ArrayList of button so I add it on the ArrayList but I don't know how to set the value of random number array on arraylist of button.
If there is an other way to solve this problem then guide me.
public class MainActivity extends AppCompatActivity {
Button genbtn,optbtn1,optbtn2,optbtn3,optbtn4;
EditText mintext,maxtext;
Random rand[]=new Random[4];
int minrange,maxrange;
ArrayList <Button>shufflearray=new ArrayList<Button>();
int random[]=new int[4];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
genbtn=(Button)findViewById(R.id.gen);
shufflearray.add((Button)findViewById(R.id.opt1));
shufflearray.add((Button)findViewById(R.id.opt2));
shufflearray.add((Button)findViewById(R.id.opt3));
shufflearray.add((Button)findViewById(R.id.opt4));
mintext=(EditText)findViewById(R.id.min);
maxtext=(EditText)findViewById(R.id.max);
genbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
minrange=Integer.parseInt(mintext.getText().toString());
maxrange=Integer.parseInt(maxtext.getText().toString());
for(int i=0;i<rand.length;i++){
random[i]=rand[i].nextInt(maxrange-minrange)+maxrange;
}
for(int i=0;i<shufflearray.size();i++) {
}
}
});
}

You can use Random function like this .
int rand = (int)(Math.random());
it will give you a random number which you can pass to the array list .

Related

Print several inputs into different plain texts - Android Studio

I'm working on a project in Android Studio where I have one EditText where the user will insert one word at a time, 10 times. Everytime the user writes a new input and clicks on the button it goes to a different TextView than the previous ones and different from the next ones.
How can I put the different inputs into the specific (different) TextViews?
Every TextView has a different sequencial ID like, word1, word2, etc.
I haven't done java in a long time, so I'm having problems with logic. I tried to do the following but the app crashes.
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
printwords(gameword.getText().toString());
}
});
public void printwords(String word) {
String[] array = new String[10];
TextView[] positions = new TextView[10];
for (int i=0; i < 10; i++){
array[i] = word;
positions[i].setText(array[i]);
}
}
}
You're creating a new array of TextView's and String every time the button is clicked. Change your code to the code below and it should work.
Make your int[] textViews , String[] array & int i = 0 class variables and then initialize them in onCreate() after setContentView()
In above code, int[] textViews is the array of ID's of TextView's from your activity.
After doing that, change your code to following:
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
array[i] = gameword.getText().toString();
YourActivity.this.findViewById(textViews[i]).setText(array[i]);
i++;
}
});

Conditional Statement in Android App Not working as Expected

I'm currently trying to add a condition based on what the user has selected on the drop down. If the first item is selected, then the data entered on the textView will be multiplied by 34, else the second item will be multiplied by 18. So far I can test the first selection works as it should, but it's not picking up the second selection. Could anybody explain to me the proper way to tackle this conditional? this is what my code looks like.
public class CatalinaFerryTickets extends AppCompatActivity{
String[] ferryRoutes = new String[]{"To Catalina Island", "To Long Beach"};
private Button renderBtn;
EditText handleData;
TextView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// RENDER SPINNER TO DEVICE
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalina_ferry_tickets);
final Spinner spin=findViewById(R.id.mySpinner);
final ArrayAdapter<String> myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, ferryRoutes);
spin.setAdapter(myAdapter);
renderBtn=findViewById(R.id.button);
displayData=findViewById(R.id.textView);
displayData.setMovementMethod(new ScrollingMovementMethod());
renderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleData=findViewById(R.id.editInput);
int ticketAmount = Integer.parseInt(handleData.getText().toString());
int total;
// FAULTY CONDITIONAL STATEMENT
if (ferryRoutes[0] == "To Catalina Island"){
total = ticketAmount * 34;
displayData.setText(Integer.toString(total));
}
else{
total = ticketAmount * 18;
displayData.setText(Integer.toString(total));
}
}
});
}
}
You aren't checking what's selected, you're checking what the value is in a static array. So it will always take one branch. If you want to do something based on the spinner selection, you need to actually query the spinner for what's selected.
The problem here is that the ferryRoutes array is never linked to a drop-down component.
Because of that, the condition
if (ferryRoutes[0] == "To Catalina Island")
will always be true, and the else block will never be executed.
Also, never compare String(s) using the reference equality operator (==). Use equals
if ("To Catalina Island".equals(ferryRoutes[0]))
You might be lucky to have the String(s) interned, and that would make the equality operator work. But don't do that as a general rule.

how to feed input node (which is a sentence) in android studio using TensorFlowInferenceInterface

If my question is unclear, please let me know, I am quite new in this area.
I did the following:
I freezed and optimized tensorflow model
It is a RNN lstm model , getting a sentence then saying if that positive or negative
I successfully added all the things in android studio
Now I have a editbox to enter my sentence , then touch Run button, then this run button should fill the label if this sentence was positive or negative,
Would you please give me some instructions that if there is a predefined function I should use,
or I have to write down that by myself, if this is the case, how,
Thanks in advance for helping.
Update
This is something I have tried but it seems quite incorrect:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inferenceInterface = new TensorFlowInferenceInterface();
inferenceInterface.initializeTensorFlow(getAssets(), MODEL_FILE);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText editNum1 = (EditText) findViewById(R.id.editNum1);
inferenceInterface.fillNodeInt(INPUT_NODE, INPUT_SIZE, editNum1);
inferenceInterface.runInference(new String[] {OUTPUT_NODE});
int[] resu = {0, 0};
inferenceInterface.readNodeInt(OUTPUT_NODE, resu);
final TextView textViewR = (TextView) findViewById(R.id.txtViewResult);
textViewR.setText(Float.toString(resu[0]) + ", " + Float.toString(resu[1]));
}
});
}
Edit2
there is FillNodeInt in TensorFlowInferenceInterface,
what I thought is that, it is going to tie my input in the editbox to the input node in my model,
so the first parameter is input node, the second is the size, and the third should be the input for example I fill in the text box,
but there is no function to have the third parameter as String,
they are int or float or byte(like example above which is Int), or something like buffer
can someone please explain which method I can use

How to make a Random Layout when button clicked

Actually i want to make it Random class but then i think to much activity can make the app slow so i just want to make Relative layout Random
so i have 5 layout in one activity class
layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);
layout5 = (RelativeLayout)findViewById(R.id.layout5);
and in each layout there is the button in there to make layout random again
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//The code to how make layout random
}
});
}
and then how to make layout that already opened not open again if the button random was pressed? then if all layout was already opened it will open new activity class
can anyone help me explain with give some example code of that?
Initially set visibility gone to all relative layouts and put all of them into View's ArrayList.
Get random number from 0 to List size.
Get View at random position and set its visibility to Visible and remove from ArrayList.
Do same thing until ArrayList is empty.
Create new activity when ArrayList is empty.
Code:
ArrayList<View> viewList=new ArrayList<>();
initLayouts(){
layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);
layout5 = (RelativeLayout)findViewById(R.id.layout5);
viewList.add(layout1);
viewList.add(layout2);
viewList.add(layout3);
viewList.add(layout4);
viewList.add(layout5);
for(int i=0;i<viewList.size();i++){
viewList.get(i).setVisibility(View.GONE);
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
loadRandomLayout();
}
});
}
public loadRandomLayout(){
if(viewList.size()>0) {
Random r = new Random();
int number = r.nextInt(viewList.size());
viewList.get(number).setVisibility(View.VISIBLE);
viewList.remove(number);
}else{
startActivity(new Intent(this,NewActivity.class));
}
}
You could create random int as follows:
//To get a Random number 1-5 (I saw your RelativeLayouts and you've 5
Random rand = new Random();
int randomNum = rand.nextInt((5 - 1) + 1) + 1;
And then you could create a method to choose what to show :
public void ShowRelativeLayout(int rand){
switch(rand){
case 1:
if (layout1.getVisibility() == View.VISIBLE) {
//Do nothing cause it's visible
break;
} else {
layout1.setVisibility(View.VISIBLE);
break;
}
case 2:
..........
}
Make an array to store the layout indexes.
RelativeLayout[] layout = new RelativeLayout[5];
layout[0] = (RelativeLayout)findViewById(R.id.layout[0]); // 0
layout[1] = (RelativeLayout)findViewById(R.id.layout[1]); // 1
layout[2] = (RelativeLayout)findViewById(R.id.layout[2]); // 2
layout[3] = (RelativeLayout)findViewById(R.id.layout[3]); // 3
layout[4] = (RelativeLayout)findViewById(R.id.layout[4]); // 4
Make a simple random number generator.
public void FindNewLayout ()
{
Random r_generator = new Random();
int randomNum;
//now the only way to know which layouts have been shown before, you
//need to store the indexes that have been used before, somewhere.
//I recommend using an array.
// count, and the array below should be initialized somewhere else
//rather than inside the method so that only one instance of each is
//created, but for simplicity I'll just put their initialization here
int static count = 0;
//I'll explain below what count does.
// the log array that remembers each layout change
boolean[] log = new boolean[5];
do
{
//select new random number
randomNum = r_generator.nextInt((max - min) + 1) + min;
//in this case max = 4, min = 0, so replace these values in the
//equation above
// check the log to see if the number has appeared again
if ( log[randomNum] == false )
{
//Great! it hasn't appeared before, so change layout
log[randomNum] = true;
layout[randomNum].setVisibility = true;
count++; // increases step
break; //stops while because an unused layout has been found
}
}while (count<5)
//if the value of count is equal to 5 then every layout has been used
//before so the do-while code should not be run again
}// end method
And the above method should be called whenever you want to try to change layout.
Finally, you can use something like the Debugger.log("message"); statement
to be printed on the console for debugging purposes if you want, in order to find out when the layout has changed.

Please help me to random it without repeat element.

This below code it was run by repeat the same elements,
what i want is to random it without repeat.
public class khmerAlphabetExercise extends Activity {
AlphabetData data;
MediaPlayer mp;
int dataType;
int dataKey;
Random random;
private ImageView iv1, iv2, iv3,iv4;
private ImageView[] imgs = { iv1, iv3, iv3,iv4 };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_khmer_exercise);
int[] imageViews={R.id.ex_con1,R.id.ex_con2,R.id.ex_con3,R.id.ex_con4};
//int images[]={R.drawable.con_ex_01,R.drawable.con_ex_02,R.drawable.con_ex_03,R.drawable.con_ex_04,R.drawable.con_ex_05,R.drawable.con_ex_06,R.drawable.con_ex_07,R.drawable.con_ex_08,R.drawable.con_ex_09,R.drawable.con_ex_10};
int[] images={data.getImageId()};
random = new Random(System.currentTimeMillis());
for(int v : imageViews)
{
ImageView iv = (ImageView)findViewById(v);
iv.setImageResource(images[random.nextInt(images.length)]);
}
}
}
You could keep a counter of the images left to select. And everytime you choose one you swap it in the original array with the last unselected.
So, for example, you have an array {0,1,2,3,4}. The Length of unselected will be 5, lets call it l
Choose a random number n between 0 an l-1
Your new element is the element at n.
Swap the element at n with the element at l-1, substract one to l and go back to point 1 if l bigger than 0. Go to point 4 if l == 0.
You finish
You can use Collections.shuffle
Collections.shuffle(Arrays.asList(images));
then you can just add this images one by one using a simple for loop without randomizing positions. BTW in your example images contains only one element..

Categories

Resources