How do I utilize a timer in Android? - java

I need to collect data on an interval, here the data collection is simulated with a counting integer. I can't seem to collect that integer though. I need the collection to start after a button is clicked and end when another is clicked. Any ideas?
package com.example.test.gothedistance;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
Button start, stop;
TextView sumText;
int count;
Timer t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById((R.id.stopButton));
sumText = (TextView) findViewById(R.id.sumTV);
t = new Timer();
count = 0;
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
count++;
}
},0,2000);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
sumText.setText(count);
}
});
}
}

The problem is likely with the line sumText.setText(count), which uses TextView.setText(int resid). That means it's looking for an id equal to count, rather than displaying the value of count. You need to convert this value to an integer first:
sumText.setText(Integer.toString(count))

Related

Wrong result of addition of two numbers in Android studio

I am developing a brain trainer application for Android users. Problem is that sometimes I got the wrong result when I try to add two numbers together (as an example: question is 2 + 2 and when I press the button and displaying the result is wrong.) but it occurs randomly. Appreciate if someone could assist me to correct way. Thanks.
This is MainActivity.java
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity{
Button button, button1, button2, button3, button4, button5;
RelativeLayout relativeLayout;
TextView sumTextView, resultTextView, pointTextView, timerTextView;
ArrayList<Integer> answers=new ArrayList<Integer>();
int locOfCorrectAns, score=0, noOfQues=0;
public void playAgain(View view) {
score=0;
noOfQues=0;
pointTextView.setText("0/0");
resultTextView.setText("");
timerTextView.setText("30s");
button5.setVisibility(View.INVISIBLE);
generateQues();
new CountDownTimer(30100, 1000){
#Override
public void onTick(long l){
timerTextView.setText(String.valueOf(l/1000)+"s");
}
#Override
public void onFinish(){
button5.setVisibility(View.VISIBLE);
timerTextView.setText("0s");
resultTextView.setText(Integer.toString(score)+"/"+Integer.toString(noOfQues));
}
}.start();
}
public void generateQues(){
Random random=new Random();
int a=random.nextInt(21);
int b=random.nextInt(21);
sumTextView.setText(Integer.toString(a)+"+"+Integer.toString(b));
locOfCorrectAns=random.nextInt(4);
answers.clear();
int incorrectAns;
for (int i=0;i<4;i++){
if ((i == locOfCorrectAns)){
answers.add(a + b);
}
else{
incorrectAns=random.nextInt(41);
while (incorrectAns == a + b){
incorrectAns=random.nextInt(41);
}
answers.add(incorrectAns);
}
}
button1.setText(Integer.toString(answers.get(0)));
button2.setText(Integer.toString(answers.get(1)));
button3.setText(Integer.toString(answers.get(2)));
button4.setText(Integer.toString(answers.get(3)));
}
public void chooseAns(View view){
if (view.getTag().toString().equals(Integer.toString(locOfCorrectAns))){
score++;
resultTextView.setText("Correct!");
}
else{
resultTextView.setText("Wrong!");
}
noOfQues++;
pointTextView.setText(Integer.toString(score)+"/"+Integer.toString(noOfQues));
generateQues();
}
public void go(View view){
button.setVisibility(View.INVISIBLE);
relativeLayout.setVisibility(View.VISIBLE);
playAgain(findViewById(R.id.playAgain));
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sumTextView=(TextView)findViewById(R.id.sumTextView) ;
button=(Button)findViewById(R.id.button);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button4=(Button)findViewById(R.id.button4);
button5=(Button)findViewById(R.id.playAgain);
resultTextView=(TextView)findViewById(R.id.textView4);
pointTextView=(TextView)findViewById(R.id.scoreTextView);
timerTextView=(TextView)findViewById(R.id.timerTextView);
relativeLayout=(RelativeLayout)findViewById(R.id.relativeLay);
}
}
   
You have set the wrong tags for the buttons. The tags should be 0 to 3 for button1 to button4.

How do I transform a string from EditText to a character array, to allow audio implementation?

This is my code:
package com.example.pembroke.finalalgorhythmic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button asdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asdf = (Button) findViewById(R.id.keybutton);
asdf.setOnClickListener(MainActivity.this);
}
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
}
What I want to do, is create a character array, so that I can use media player class to play certain sounds based on the user input after my button is clicked. Any ideas?
Have you tried
notes.toCharArray() yet?
EDIT: Long version
EDIT 2: Sample implementation
MediaPlayer mp;
char[] currentNotes;
int noteIndex;
// Create the mp in onCreate and register your onCompletion callback
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
currentNotes = notes.toCharArray();
noteIndex = 0;
mp.setDataSource(getNoteResource(currentNotes[0]));
mp.start();
}
// Convert tone values into
public int getNoteResource(char tone) {…}
#Override
public void onCompletion(MediaPlayer mp) {
if(++noteIndex < currentNotes.length) {
mp.setDataSource(getNoteResource(currentNotes[noteIndex]));
mp.start();
}
}

I need to generate and display a random number in SystemClock.sleep() with no range

I'm a student at a community college. The following is the Main Activity in which I was tasked to generate a random number instead of the 5 milliseconds to run the sleep()method. I then have to display that random number. I figured out how to accomplish it for the first button, but I keep running into snags for the next two(converting to int, converting to a string for resultsTextView.setText();. I have tried several times to code a method, but then I'm running into other errors because onCreate is void.
package com.example.dan.hour5application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button uiThreadButton;
Button postButton;
Button asyncTaskButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);
resultsTextView = (TextView) findViewById(R.id.textView);
uiThreadButton = (Button) findViewById(R.id.uiThreadButton);
uiThreadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////Achieved a random number here////
Random random = new Random();
int x = random.nextInt(10);
SystemClock.sleep(x);
String aString = Integer.toString(x);
resultsTextView.setText(aString);
}
});
postButton = (Button) findViewById(R.id.post);
postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
resultsTextView.post(new Runnable() {
#Override
public void run() {
resultsTextView.setText("Updated");
}
});
}
}).start();
}
});
asyncTaskButton = (Button) findViewById(R.id.asynctask);
class DelayTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
resultsTextView.setText("Starting AsyncTask");
}
#Override
protected void onPostExecute(Integer result) {
if (result == 0) {
resultsTextView.setText("Updated via AsyncTask");
}
}
#Override
protected Integer doInBackground(Integer... params) {
SystemClock.sleep(5000);
return 0;
}
}
}
}
I have looked at several other examples on Stack, but they aren't quite what I'm doing. I'm only starting my 4th month in Android Development, and I'm still trying to learn Java. The assignment is long gone, and my instructor didn't provide me with help when I asked. Thanks for your help!

How to set image resource in Android?

I am writing code for a poker game on eclipse and I am stuck on how to make the card clicked in the cardHand area show up in the playedCards area and have it removed from the deck I am drawing it from. Here's the code:
package com.viktorengineering.poker254;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import java.util.Random;
public class Poker extends Activity {
private ImageView mViewDeck;
private ImageView mViewHand;
private ImageView mViewPlayedCards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getWindow().setBackgroundDrawableResource(R.drawable.green_back);
mViewDeck = (ImageView) findViewById(R.id.deckImage);
mViewDeck.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int[] imagesArray = {R.drawable.clubs_ace, R.drawable.hearts_seven, R.drawable.diamonds_five,
R.drawable.clubs_three, R.drawable.hearts_eight, R.drawable.spades_six};
Random random = new Random();
mViewHand.setImageResource(imagesArray[new Random().nextInt(6)]);
}
});
mViewHand = (ImageView) findViewById(R.id.cardHand);
mViewHand.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mViewPlayedCards.setImageResource(0);
mViewHand.setImageResource(0);
}
});
mViewPlayedCards = (ImageView) findViewById(R.id.playedCards);
}
}
Your Image in Drawable Folder means use bellow code
mViewPlayedCards.setImageResource(R.drawable.icon);
mViewHand.setImageResource(R.drawable.icon_home);

Using simple text view and button widgets in android

Im trying to make a basic program where you press a button and it adds to an integer. Im having trouble updating the text view.
package com.example.curtis.simpleapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int num;
TextView numview;
private void updateNumber(){
TextView numview = (TextView)findViewById(R.id.Number);
numview.setText(num);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupButton();
}
private void setupButton() {
Button button = (Button) findViewById(R.id.Button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num = num + 1;
numview.setText(num);
}
});
}
Help would be great im trying to get into android and books havent been very helpful
There are a few mistakes here. First, you are never calling updateNumber() so numviewis never set. Moreover, you have two TextView numView once global in your MainActivity and again in updateNumber(). There is a better way to do this. But first go to activity_main.xml file and within the button tag add the the line android:onClick="onClick" something like this :
<Button
android:id="#+id/button1"
...
android:onClick="onClick"/>
Next in your MainActivity.java, add the following lines of code :
package com.example.curtis.simpleapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int num = 0;
TextView numview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numview = (TextView)findViewById(R.id.Number);
}
public void onClick(View view){
num += 1;
numview.setText(String.valueOf(num));
}
}
onClick() will be automatically called when your button is clicked because of the android:onClick property.
you have two different objects with same name and it would cause error.
one of them is defined in your class (TextView numview;) and the other one is defined in your function update number.
in your onClick method you want to change numView defined in your class and it's not initialized. you have to add change your code :
package com.example.curtis.simpleapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int num;
TextView numview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numview = (TextView)findViewById(R.id.Number);
setupButton();
}
private void setupButton() {
Button button = (Button) findViewById(R.id.Button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num = num + 1;
numview.setText(num);
}
});
}
Put this code in your onClick function
num = num + 1;
updateNumber();
You are never calling updateNumber()
package com.example.curtis.simpleapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int num=0;
TextView numview;
private void updateNumber(int number){
numview = (TextView)findViewById(R.id.Number);
numview.setText(number);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupButton();
}
private void setupButton() {
Button button = (Button) findViewById(R.id.Button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num = num + 1;
updateNumber(num);
}
});
}

Categories