I have just started learning Android and got some misunderstanding. I'm trying to create an application which displays a textView and a button. Every button click generates a new random number which should be displayed in the textView.
But unfortunately my code causes a list of errors. Here it is:
public class FirstAndroidProjectActivity extends Activity {
public OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.display);
Random r = new Random();
int i = r.nextInt(101);
tv.setText(i);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(listener);
}
}
If I just don't use random and use some string except of i
(for example tv.setText("99");) everything is ok, but it doesn't work with a variable as a parameter of setText().
Where is a mistake?
Hope for your help.
You need to convert your random number to a string before setting the text on your TextView
Try
tv.setText(i +"");
Try:
tv.setText(String.valueOf(i));
Java doesn't auto convert types. The + operator is overloaded to transform the parameters passed to it into a String when one or more of those paramaters is a String. So, when you pass i + "" to setText() you are passing a String, however if you just pass i then the compiler sees you passing an int to a method that expects a String and lets you know that that can't be done.
i is an int, try tv.setText("" + i);
Convert your integer to a String before setting it to the textView. You should also move Random r = new Random(); outside of the method, or else your numbers may not really be random :
Random r = new Random();
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.display);
int i = r.nextInt(101);
tv.setText(Integer.toString(i));
}
From the documentation :
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers
If you create two Random objects too quickly (for example the user clicks two times on the button very quickly), they will share the same seed (the system clock is used to generate it) and as a result you will get the same number two times.
By creating only one Random instance in a global variable, you avoid this issue.
use
tv.setText(new Integer(i).toString()) ;
Related
i want to store number in array one by one ...when user press button it will generate number in Text field ..i want to store that number in array
This is quite a simple problem...I am writing this but I will hope you will first try and then ask a question from next time:
For this problem u just need to use the function Math.random() in your onClickListner() of your button. Now place this no in textview by using the function setText().
For eg if ur textview name is tv then use tv.setText(no) where no=Math.random()
Something like that?
findViewById(R.id.ButtonRandomNumber).setOnClickListener(mRandomListener);
TextView randomNumber = (TextView) findViewById(R.id.randomNumber);
private OnClickListener mRandomListener = new OnClickListener() {
public void onClick(View v) {
Random rand = new Random();
array[array.length + 1] = rand;
randomNumber.setText(String.format(rand));
}
};
Make the array a global variable and that should more or less work. Was that what you wanted to know?
I'm doing a simple addition game on android studio. Every time the "addition" activity is opened I was hoping to generate two random numbers in two text boxes. However I can't get it to work and the text box appears blank every time I run the app and open the activity. Here's my code for one of the text boxes.
public void textview2(View View) {
Random addition1 = new Random();
int additionint1 = addition1.nextInt(100)+1;
TextView additionText1 = (TextView) findViewById(R.id.textView2);
String additionString1 = String.valueOf(addition1);
additionText1.setText(additionString1);
}
Change
String additionString1 = String.valueOf(addition1);
to
String additionString1 = String.valueOf(additionint1);
You are missing something here I believe,
In onCreate method, you should do something like this..
Random addition1 = new Random();
int additionint1 = addition1.nextInt(100)+1;
TextView additionText1 = (TextView) findViewById(R.id.textView2);
String additionString1 = String.valueOf(additionint1);
additionText1.setText(additionString1);
but the point is, it should be in onCreate so that when your activity is created, the number is generated and .setText for your required textView is called...
you can also consider the same if you want to handle other activity states..
PS: Note that you can have this code folded in function and called in overrided method onCreate
also, note String.valueOf(additionint1);
this is my first question so I hope to make it clear.
I have one textView with some numerical text and next to it one button with one click listener and what I want is that when you click on the button the numerical value (>=0) of the TextView decrements in one.
Here is part of my code:
TextView Counter = new TextView(this);
if (intSeries != 0)
Counter.setText(Integer.toString(intSeries));
else
Counter.setText("0");
Counter.setId(4);
tablaContador.addView(Counter,Tr);
Button Done = new Button(this);
Done.setText("-1");
if (intSeries != 0)
Done.setVisibility(View.VISIBLE);
else
Done.setVisibility(View.GONE);
Done.setId(6);
Done.setOnClickListener(this);
And this is the onClick funcion (part of it):
#Override
public void onClick(final View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case 6:{
TextView text = (TextView)findViewById(4);
int series = Integer.parseInt(text.getText().toString());
series--;
text.setText(series);
if (series==0){
Button boton = (Button)findViewById(6);
boton.setVisibility(View.GONE);
}
}
}
}
The error is when I try to make the setText inside the onClick function, I hope it can be fixed or maybe recieve other idea to do it.
Thank you so much.
I would avoid all this hardcoding of Ids, use resources instead.
Your call to
text.setText(series)
is passing an int. The only valid setText(int resId) overload expects a resource associated with the int value, i.e. a string resource.
Convert your series value to a string.
Something like:
text.setText(Integer.toString(series));
You should setup series as an integer. And increase/descrease it as you wish. When you want to change the button's text convert the int to String.
Instead of:
text.setText(series);
use:
text.setText(String.valueOf(series));
Variablenames in java can't start with a capital letter. That is reserved for classnames.
Counter -> counter
Done -> done
I tried this and it worked:
//Create onClickListener
OnClickListener pickChoice = new OnClickListener()
{
public void onClick(View v)
{
TextView txt = (TextView) findViewById(4);
int number = Integer.valueOf(txt.getText().toString());
txt.setText(String.valueOf(number -1));
}
};
//Create layout
LinearLayout lnLayout = new LinearLayout(this);
lnLayout.setOrientation(LinearLayout.VERTICAL);
TextView txt = new TextView(this);
txt.setId(4);
txt.setText("0");
lnLayout.addView(txt);
Button Done = new Button(this);
Done.setText("-1");
Done.setId(6);
Done.setOnClickListener(pickChoice);
lnLayout.addView(Done);
setContentView(lnLayout);
Where are you creating your button inside? an activity? the part where you pass the onClickListener to the button doesn't make sense, maybe the button is getting a wrong listener and gets you an error every time you press the button ?
The code should be easy to understand, if there is anything you need me to explain please ask :)
The question really is that simple. I have an activity with a button that randomly changes the text of a textview box. How do I add another button that gathers the previous number generated so the previous textview text comes back - for a quotes app.Is there a feature I require? I have searched, but I cannot find a feature that will 'go back' on the random number generator.
Thank you in advance.
You dont need to go back on the generator itself, just remember the previous values. Store it in a variable. Here we are using prev as an array, because we need it to be final so we can access it in the anonymous inner classes (click handlers). But we also need to change it. So we use the prev[0] value.
Here I am assuming you have a button called nextNum which generates the next random number. But that could be anything, it doesnt matter. When you generate a new random number simply update the 0th element of the prev array and you should be fine.
final String[] prev = new String[] { "" }
#Override
public void onCreate(Bundle bundle) {
// ....
Button BackQuote = (Button)findViewById(R.id.back);
final TextView display = (TextView) findViewById(R.id.textView1);
// number generator button
Button nextNum = (Button) findViewById(R.id.random);
nextNum.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// generate a random number
// store it in prev
prev[0] = rndNum.toString();
}
});
BackQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
display.setText(prev[0]);
}
});
}
Unless there is a specific reason you want to avoid this, then this would work perfectly fine. And there is no way to go back on a random generator. By definition it IS random! (Yes, Pseudo-random. Nonetheless)
So if you want to keep an history, you are going to have to implement those yourself. I have yet to see a random generator which has a history feature. I'd be surprised if i do too.
I'm new to android developing but right now I'm working on an application that displays Random Facts. Since I don't want it to be in a random order, I would like to have them in a list. I would like to order through them one by one and show them using TextView.
Resources res = getResources();
myString = res.getStringArray(R.array.FactsArray);
That's what I have so far. If I'm right, that just establishes the array so I can be able to use it later. What I had before was rgenerator which chose a random string from the array and displayed it when I clicked a button.
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
fact = myString[rgenerator.nextInt(myString.length)];
TextView tv = (TextView) findViewById(R.id.text1);
tv.setText(fact);
But Like I said, I would like to just order through them one by one when a button is clicked.
Since you're displaying the strings sequentially, you'll need a counter variable to keep track of where you are in the array. It should be initialized to zero. Each time you click the button it should increment until you reach the end of the array (myString.length - 1).
As far as the actual event handling, that's not hard to do. You just need to create a setOnClickListener() for your button.
int count = 0;
Button b1 = (Button) findViewById(R.id.buttonName);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (count < myString.length) {
tv.setText(myString[count]);
count++;
}
}
});