Learning how to produce random numbers from arrays. The code will pick a random string during the onCreate method, but when the button is clicked there is no change to the string. Am I messing up the scope of my variables somehow? I really do not know what it wrong.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
}
public void onClick(View view){
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
TextView question = (TextView) findViewById(R.id.question);
question.setText(q);
}
});
}
}
First of all you haven't set click listener on button properly you made onClick method which is never called . Also you are getting the references of view multiple times you should do it like this.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
question.setText(q);
}
});
}
}
You either need to set the onClickListener in xml (in which case you don't need to set the listener in code), or you need to set the listener in onCreate. Right now its being set in a function named onClick, which is never called.
First, you never set the onClickListeren. You have a method which adds one, but you never call it. Move the code in the onClick method to your onCreate method. This will probably fix your problem.
If not, don't make your Random final and add this to your #Override onClick():
rgen = new Random(System.currentTimeMillis());
This will use a different seed every time
Related
I am trying to save data to a Deque on buttonclick and display the data in a tablelayout. My issue is that every time I trigger the onclick, the Deque loses all previous data. I tried to instantiate the Deque outside the onCreate method and it did not work. I am using a Deque as a stack because I need to display the data LIFO. Any help on this would be very much appreciated. Here is what I've tried so far:
public class MainActivity extends AppCompatActivity {
private Button buttonAdd;
private EditText editText1;
private Deque<String> input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText)findViewById(R.id.edit_text_1);
final Deque<String> input = new ArrayDeque<String>();
buttonAdd = (Button) findViewById(R.id.button_add);
buttonAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
String data = editText1.getText().toString();
input.addFirst(data);
Deque<String> inputData = input;
while (!inputData.isEmpty()) {
String s = inputData.removeFirst();
TableRow row = new TableRow(MainActivity.this);
TextView textViewData = new TextView(MainActivity.this);
textViewData.setText(s);
textViewData.setGravity(Gravity.CENTER);
row.addView(textViewData);
table.addView(row);
}
}
});
}
}
The problem is this line:
String s = inputData.removeFirst();
With this operation, you remove (delete) the next entry and since you do it in a loop:
while (!inputData.isEmpty()) {
it simply empties the queue.
What you want is to iterate over the queue without removing anything:
for (String element : inputData) {
textViewData.setText(s);
}
I have a problem. I do not know how to call a different class. the code is for a button (when you click the button a message appears in random) so i thought it would be better if i placed it in a different class as i have also used arrays.Now i do not know how to call the class.
This is my code.I want to call "Firstin" inside SecondActivity.
public class SecondActivity extends Activity {
private Firstin mFirst = new Firstin ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//finds textview
final Text Ftext = (Text) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final Text Stext = (Text) findViewById(R.id.textView3);
//finds button view
Button btnView = (Button) findViewById(R.id.button1);
#SuppressWarnings("unused")
Button btnView2 = (Button) findViewById(R.id.button2);
btnView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Answer = mFirst.firstAnswer();
Ftext.setTextContent(Answer);
}
});
this is the class I'm trying to call:
package com.example.insultgenerator;
import java.util.Random;
public class Firstin {
public String firstAnswer(){
String [] mResults={
"its cool",
"we cool",
"im cool",
"he cool",
"she cool"
};
// the button was clicked so replace the answer label with answer
String Answer = "" ;
// the two double is a 'empty string
Random RandomGen = new Random();// telling the program to construct a random generator
int RandomNum= RandomGen.nextInt(mResults.length);
Answer = mResults[RandomNum];
return(Answer);
}
}
You should cast to TextView
final TextViewFtext = (TextView) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final TextViewStext = (TextView) findViewById(R.id.textView3);
then use TextView.setText(...) method:
String Answer = mFirst.firstAnswer();
Ftext.setText(new Firstin().firstAnswer());
}
});
then last call the method from the other class with new Firstin().firstAnswer() which creates a instance of the class and executes the method.
I am trying to make a simple application where every so many seconds the text being displayed is changed to another, the input is given by the user before the onClick and set to different strings. I can't find a way to have the different strings displayed at different times - and is it even possible to use one single textView to display different text at different times, never at the same time....
Any help is appreciated. Thanks.
Andrew
This is my code so far...
public class ThunderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//when the game button is pressed
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Enter names
//player one
final EditText player1 = (EditText) findViewById(R.id.editText1);
final String player = player1.getText().toString().trim();
//player 2
final EditText player2 = (EditText) findViewById(R.id.editText2);
final String player11 = player2.getText().toString().trim();
//player 3
final EditText player3 = (EditText) findViewById(R.id.editText3);
final String player111 = player3.getText().toString().trim();
//switches to second screen - the play xml file
setContentView(R.layout.main2);
//starts the song
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.drawable.thunderstruck);
mp.start();
//shuffle names and display them
//displays name - testing purposes
v = (TextView) findViewById(R.id.textView1);
String text = player;
((TextView) v).setText(text);
//v = (TextView) findViewById(R.id.textView2);
//String text2 = player11;
//((TextView) v).setText(text2);
}
});
}
}
An easier way to do the same thing is using the Handler.postDelayed method.
public class Act extends Activity{
private Handler handler = new Handler();
private TextView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Initialize view
handler.postDelayed(new ViewUpdater("str1", view), 10000);
handler.postDelayed(new ViewUpdater("str2", view), 20000);
handler.postDelayed(new ViewUpdater("str2", view), 30000);
}
private class ViewUpdater implements Runnable{
private String mString;
private TextView mView;
public ViewUpdater(String string, TextView view){
mString = string;
mView = view;
}
#Override
public void run() {
mView.setText(mString);
}
}
}
Something like that: You get the basic idea!
ok here is your hint:
Say your TextView is called yourTextView
String[] texts = new String[]{"String1","String2","String3"}; //etc
Runnable myRun = new Runnable(){
public void run(){
for(int i=0;i<texts.length;i++){
synchronized(this){
wait(30000); //wait 30 seconds before changing text
}
//to change the textView you must run code on UI Thread so:
runOnUiThread(new Runnable(){
public void run(){
yourTextView.setText(texts[i]);
}
});
}
}
};
Thread T = new Thread(myRun);
T.start();
A more correct answer would be to use a ViewFlipper. You can add all your TextViews to it and call startFlipping(). You can set the flip interval by calling setFlipInterval(int milliseconds).
It's hard to explain in the title. Basically as far as I can tell the submit button is taking the name and placing it in the array like I want. What I need now is for the Play(done) Button to transfer the user and the data to the next class (which I believe is coded correctly) and I need it to start a game. The game which you will see in the second class (get the data from the previous) I need it to display the names from the names array 1 at a time and randomly assign them a task to do from the tasks array.
Currently the app is force closing after I click the play button. I'm linking both classes cause I'm pretty sure the problem is in the second class. Thanks for your help ahead of time.
Class1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < 6; i++)
{
names.add(input.getText().toString());
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
}
});
counter++;
}
}
Thought I should also mention that these buttons on the 2nd page I would like to assign a score to whichever name array person is up and keep track until the final round where it will display the winner. If anyone has any idea how to make that work.
Have you made sure to include the Game activity as an Application Node in your AndroidManifest?
If not, open your manifest to the application tab, on the bottom hit Add, and add an Activity of the name .Game
Without this, that intent never gets received by the other class.
You've already been told that you use non-initialized arrays here: EditText and using buttons to submit them. But also you're trying to get array extra, however you don't put it inside intent. And you're using uninitialized tasks array in Game class.
I'm a beginner in application development. My problem is, that when I run my app and I click on the Calculate button, the program stops. The code:
public class screen1 extends Activity {
private EditText name;
private CheckBox box1;
private Spinner spinner;
private TextView text1, text2, text3, text4, text5, text6;
private Button calcbutton, closebutton;
String strength;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner hubSpinner = (Spinner) findViewById(R.id.myspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.military_ranks , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hubSpinner.setAdapter(adapter);
name = (EditText)findViewById(R.id.editText1);
strength = name.getText().toString();
box1 = (CheckBox)findViewById(R.id.checkBox1);
text1 = (TextView)findViewById(R.id.textView4);
text2 = (TextView)findViewById(R.id.textView6);
text3 = (TextView)findViewById(R.id.textView8);
text4 = (TextView)findViewById(R.id.textView10);
text5 = (TextView)findViewById(R.id.textView12);
text6 = (TextView)findViewById(R.id.textView14);
final Button calcbutton = (Button) findViewById(R.id.button1);
calcbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
double sebzes;
if(box1.isChecked()){
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1*(1+1/100);
text1.setText(Double.toString(sebzes));
}
else{
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1;
text1.setText(Double.toString(sebzes));
}
}
});
final Button closebutton = (Button) findViewById(R.id.button2);
closebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
In the edittext component you should be able to write numbers only. I don't know why it's not working.
The problem are these two lines:
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
The first won't fail if you use only numbers in your EditText but it would be better to ensure that or at least catch the exception that is thrown when you try to convert a character to a numberical value. Additionally you could also use Integer.valueOf(strength).intValue(); even so it is normally not really necessary.
The real problem is the second line. You declared the variable spinner but you never instantiate it. That's why you will get a NullPointerException there.
On an unrelated note: You also should start your class name with a capital letter to follow the Java naming conventions.
You're not instantiating spinner anywhere, but you're referencing it in the second line of your button click method. Probably a null reference problem.