This is for my school project and yup I'm still new at android programming. I have no idea about why these error messages keep showing up.
The error messages is:
a. cannot resolve method 'onCreate(savedInstanceState)' on the part after 'Super'
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workouttimer);
b. cannot resolve method 'findViewById(int)'
mTextViewCountDown = findViewById(R.id.text_view_countdown);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonReset = findViewById(R.id.button_reset);
c. cannot resolve method 'onSaveInstanceState(android.os.Bundle)'
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong("millisLeft", mTimeLeftInMillis);
outState.putBoolean("timerRunning", mTimerRunning);
outState.putLong("endTime", mEndTime);
}
d. cannot resolve method 'onRestoreInstanceState(android.os.Bundle)'
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTimeLeftInMillis = savedInstanceState.getLong("millisLeft");
mTimerRunning = savedInstanceState.getBoolean("timerRunning");
updateCountDownText();
updateButtons();
This is my timer.java (actually this is my second mainactivity java because my application is multi-activity)
package com.example.lenovo.pomodorotest;
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.TextView;
import java.util.Locale;
public class timer {
private static final long START_TIME_IN_MILLIS = 600000;
private TextView mTextViewCountDown;
private Button mButtonStartPause;
private Button mButtonReset;
private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
private long mEndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workouttimer);
mTextViewCountDown = findViewById(R.id.text_view_countdown);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonReset = findViewById(R.id.button_reset);
mButtonStartPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTimerRunning) {
pauseTimer();
} else {
startTimer();
}
}
});
mButtonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetTimer();
}
});
updateCountDownText();
}
private void setContentView(int workouttimer) {
}
private void startTimer() {
mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
mTimerRunning = false;
updateButtons();
}
}.start();
mTimerRunning = true;
updateButtons();
}
private void pauseTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
updateButtons();
}
private void resetTimer() {
mTimeLeftInMillis = START_TIME_IN_MILLIS;
updateCountDownText();
updateButtons();
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
private void updateButtons() {
if (mTimerRunning) {
mButtonReset.setVisibility(View.INVISIBLE);
mButtonStartPause.setText("Pause");
} else {
mButtonStartPause.setText("Start");
if (mTimeLeftInMillis < 1000) {
mButtonStartPause.setVisibility(View.INVISIBLE);
} else {
mButtonStartPause.setVisibility(View.VISIBLE);
}
if (mTimeLeftInMillis < START_TIME_IN_MILLIS) {
mButtonReset.setVisibility(View.VISIBLE);
} else {
mButtonReset.setVisibility(View.INVISIBLE);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong("millisLeft", mTimeLeftInMillis);
outState.putBoolean("timerRunning", mTimerRunning);
outState.putLong("endTime", mEndTime);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTimeLeftInMillis = savedInstanceState.getLong("millisLeft");
mTimerRunning = savedInstanceState.getBoolean("timerRunning");
updateCountDownText();
updateButtons();
if (mTimerRunning) {
mEndTime = savedInstanceState.getLong("endTime");
mTimeLeftInMillis = mEndTime - System.currentTimeMillis();
startTimer();
}
}
}
}
This is my workouttimer.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_view_countdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="00:00"
android:textColor="#android:color/black"
android:textSize="60sp" />
<Button
android:id="#+id/button_start_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_view_countdown"
android:layout_centerHorizontal="true"
android:text="Studying!" />
<Button
android:id="#+id/button_start_letsgetrest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button_start_pause"
android:layout_centerHorizontal="true"
android:text="Lets Get Rest!" />
<Button
android:id="#+id/button_reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_view_countdown"
android:layout_marginStart="11dp"
android:layout_toEndOf="#+id/button_start_pause"
android:text="reset"
android:visibility="invisible"
xmlns:tools="http://schemas.android.com/tools":visibility="visible"
android:layout_marginLeft="11dp"
android:layout_toRightOf="#+id/button_start_pause" />
</RelativeLayout>
any help would be appreciated. Thanks
Change your timer.java file to this and then rebuild
public class timer extends AppCompatActivity {
All of the methods that you are overriding is from the class AppCompatActivity or Activity.Hence, to use these methods in your class, you will have to extend the classes AppCompatActivity or Activity like -
public class timer extends AppCompatActivity{
//Your code
}
Note - Please, while creating classes, start it with a capital letter as per convention.
Related
Today i am posting my first question here in stackoverflow.
My app's subject is speech to text application all the app is working but the text doen't appear in its zone after saying the speech. So i am here asking you all for help.
Belong my xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:padding="40dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_mic_24" />
</RelativeLayout>
And my main code:
package com.example.translationapp;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
final EditText edittext = findViewById(R.id.edittext);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null) {
edittext.setText(matches.get(0));
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
edittext.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
edittext.setText("");
edittext.setHint("Listening...");
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
}
So please again and thank you all for your time.
This question already has answers here:
Create clickable link in text view in android
(2 answers)
Closed 2 years ago.
I'm trying to develop an Android application with Java. I need to separate all words in a text (bookText in code) and make them clickable. How can I do this? I will be grateful if you could help me. Thanks in advance.
public class BookActivity extends AppCompatActivity {
public static final String BOOK_TEXT = "com.example.altaybook.BOOK_TEXT";
BookViewModel bookViewModel;
private TextView bookTextView;
private String bookName;
private String bookText;
ProgressBar bookTextProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
bookTextView = findViewById(R.id.book_text_id);
bookTextProgressBar = findViewById(R.id.bookTextProgressBar);
Intent intent = getIntent();
final int bookPosition = intent.getIntExtra(BOOK_TEXT, -1);
bookViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(BookViewModel.class);
bookViewModel.getAllBooks().observe(this, new Observer<List<Book>>() {
#Override
public void onChanged(List<Book> books) {
bookName = books.get(bookPosition).getName();
setTitle(bookName);
bookText = books.get(bookPosition).getText();
SetTextAsyncTask setTextAsyncTask = new SetTextAsyncTask();
setTextAsyncTask.execute();
bookTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
});
}
public class SetTextAsyncTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bookTextProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... strings) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
bookTextView.setText(bookText);
bookTextProgressBar.setVisibility(View.GONE);
}
}
}
You can use LinearLayout. Here is an example:
activity_book.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:id="#+id/container"/>
</LinearLayout>
BookActivity.java
public class BookActivity extends Activity
{
public static final String BOOK_TEXT = "com.example.altaybook.BOOK_TEXT";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
LinearLayout ll = findViewById(R.id.container);
String[] splitText = BOOK_TEXT.split("\\.");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
for(int i=0; i < splitText.length; i++) {
TextView content = new TextView(this);
if(i == 0) { content.setText(splitText[i]);
} else { content.setText("." + splitText[i]); }
content.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(BookActivity.this, "You clicked: " + ((TextView)view).getText(), Toast.LENGTH_SHORT).show();
}
});
ll.addView(content, params);
}
}
}
I have made a CountDownTimer that works perfectly - you can get the correct time for soft/medium/hard-boiling an egg. My problem is that the timer resets after orientation change. I have googled and tried so many solution, still I don't understand how to use the onSave and onRestore properly. Here's my code:
Any tips?
package com.dohman.boilaneggbae;
import android.graphics.PorterDuff;
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.TextView;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private static final String CURRENT_TIME = "currentTime";
private static final String DURATION_TIME = "durationTime";
private long currentTime;
private int durationTime;
private TextView time;
private Button buttonLargeSize;
private Button buttonMediumSize;
private Button buttonSoft;
private Button buttonMedium;
private Button buttonHard;
private Button buttonHellaHard;
private CountDownTimer countDownTimer;
private EggSize mediumOrLarge = EggSize.UNDEFINED;
private boolean alreadyRunning = false;
enum EggSize {
UNDEFINED, MEDIUM, LARGE;
}
private View.OnClickListener btnMediumSizeClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
mediumOrLarge = EggSize.MEDIUM;
}
};
private View.OnClickListener btnLargeSizeClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
mediumOrLarge = EggSize.LARGE;
}
};
private View.OnClickListener btnSoftClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((mediumOrLarge != EggSize.UNDEFINED) && (alreadyRunning == false)) {
alreadyRunning = true;
durationTime = 240;
start(240);
} else if (mediumOrLarge == EggSize.UNDEFINED) {
time.setText("Choose size first");
} else {
alreadyRunning = false;
cancel();
}
}
};
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putLong(CURRENT_TIME, currentTime);
savedInstanceState.putInt(DURATION_TIME, durationTime);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
currentTime = savedInstanceState.getLong(CURRENT_TIME);
durationTime = savedInstanceState.getInt(DURATION_TIME);
}
time = findViewById(R.id.time);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentTime = savedInstanceState.getLong(CURRENT_TIME);
durationTime = savedInstanceState.getInt(DURATION_TIME);
currentTime -= durationTime;
}
private void start(int duration) {
time.setText("");
if (mediumOrLarge == EggSize.MEDIUM) {
duration -= 60;
}
countDownTimer = new CountDownTimer(duration * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
String text = String.format(Locale.getDefault(), "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
time.setText(text);
}
countDownTimer.start();
}
}
I finally solved this! Using this link:
https://codinginflow.com/code-examples/android/countdown-timer/part-2
Those are the codes:
package com.codinginflow.countdowntimerexample;
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.TextView;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final long START_TIME_IN_MILLIS = 600000;
private TextView mTextViewCountDown;
private Button mButtonStartPause;
private Button mButtonReset;
private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
private long mEndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewCountDown = findViewById(R.id.text_view_countdown);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonReset = findViewById(R.id.button_reset);
mButtonStartPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTimerRunning) {
pauseTimer();
} else {
startTimer();
}
}
});
mButtonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetTimer();
}
});
updateCountDownText();
}
private void startTimer() {
mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
mTimerRunning = false;
updateButtons();
}
}.start();
mTimerRunning = true;
updateButtons();
}
private void pauseTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
updateButtons();
}
private void resetTimer() {
mTimeLeftInMillis = START_TIME_IN_MILLIS;
updateCountDownText();
updateButtons();
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
private void updateButtons() {
if (mTimerRunning) {
mButtonReset.setVisibility(View.INVISIBLE);
mButtonStartPause.setText("Pause");
} else {
mButtonStartPause.setText("Start");
if (mTimeLeftInMillis < 1000) {
mButtonStartPause.setVisibility(View.INVISIBLE);
} else {
mButtonStartPause.setVisibility(View.VISIBLE);
}
if (mTimeLeftInMillis < START_TIME_IN_MILLIS) {
mButtonReset.setVisibility(View.VISIBLE);
} else {
mButtonReset.setVisibility(View.INVISIBLE);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong("millisLeft", mTimeLeftInMillis);
outState.putBoolean("timerRunning", mTimerRunning);
outState.putLong("endTime", mEndTime);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTimeLeftInMillis = savedInstanceState.getLong("millisLeft");
mTimerRunning = savedInstanceState.getBoolean("timerRunning");
updateCountDownText();
updateButtons();
if (mTimerRunning) {
mEndTime = savedInstanceState.getLong("endTime");
mTimeLeftInMillis = mEndTime - System.currentTimeMillis();
startTimer();
}
}
}
EDIT: For some reason I can't mark my own answer as a solution, but this problem is solved anyway. (Answered)
I am creating a quiz game and I have added progress bar. I want the progress bar to give 10 seconds to answer each question and if the time runs out it should display the results screen. How do I this?
package com.example.sqz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class QuestionActivity extends Activity {
List<Question> quesList;
int score = 0;
int qid = 0;
Question currentQuestion;
TextView txtQuestion, times, scored;
Button Answer1, Answer2, Answer3, Answer4;
QuizHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//level difficulty
int level;
level = getIntent().getIntExtra("level",-1); //get LEVEL from intent. If no LEVEL in intent, LEVEL=-1.
//if level not equal "-1" (so level was in intent), get questions for this level from database
if(level!=-1) {
db=new QuizHelper(this);
quesList=db.getAllQuestionsByLevel(level);
}
currentQuestion = quesList.get(qid); // current question
txtQuestion = (TextView) findViewById(R.id.txtQuestion); // textview to view the question
// the four answer buttons
Answer1 = (Button) findViewById(R.id.btnAnswer1);
Answer2 = (Button) findViewById(R.id.btnAnswer2);
Answer3 = (Button) findViewById(R.id.btnAnswer3);
Answer4 = (Button) findViewById(R.id.btnAnswer4);
// text view to show score
scored = (TextView) findViewById(R.id.score);
// textview for timer
times = (TextView) findViewById(R.id.timers);
// method to set the game
setQuestionView();
times.setText(R.string.timertext);
final ProgressBar mProgressBar;
CountDownTimer mCountDownTimer;
final int[] i = {0};
mProgressBar=(ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setProgress(i[0]);
mCountDownTimer=new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i[0] + millisUntilFinished);
i[0]++;
mProgressBar.setProgress(i[0]);
}
#Override
public void onFinish() {
//Do what you want
i[0]++;
mProgressBar.setProgress(i[0]);
}
};
mCountDownTimer.start();;
// button click listeners
Answer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // method to check if the answer is correct
getAnswer(Answer1.getText().toString());
}
});
Answer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer2.getText().toString());
}
});
Answer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer3.getText().toString());
}
});
Answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(Answer4.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
if (currentQuestion.getANSWER().equals(AnswerString)) {
score = score + 5; // increase the sore by 5 if the answer is correct
scored.setText("Score : " + score); // set text of textview to score
} else { //load the result screen if wrong answer is selected
Intent intent;
intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b;
b = new Bundle();
b.putInt("score", score);
intent.putExtras(b); // Put your score to your next
startActivity(intent); // starts the activity
finish();
}
if (qid < 20) { // 20 questions for each level
// until the questions are over do this
currentQuestion = quesList.get(qid);
setQuestionView();
} else {
// once the questions are finished show results screen
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put questions and answers together
txtQuestion.setText(currentQuestion.getQUESTION());
Answer1.setText(currentQuestion.getA1());
Answer2.setText(currentQuestion.getA2());
Answer3.setText(currentQuestion.getA3());
Answer4.setText(currentQuestion.getA4());
qid++;
}
}
You could use a running Thread or AsyncTask
1)For a running Thread,
In your activity xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:progress="100"
android:id="#+id/progress"/>
</LinearLayout>
In your activity
public class TestActivity extends AppCompatActivity{
private ProgressBar moveBar;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
moveBar = (ProgressBar)findViewById(R.id.progress);
moveBar.setProgress(100);
startProgress();
}
private void startProgress() {
Thread sleep = new Thread(new Runnable() {
#Override
public void run() {
for(count =10; count >=0; count --) {
try {
Thread.sleep(1000); //every 1sec
// here you check for the result if correct
//i use count == 5 as an example, uncomment to see
/*if(count == 5){
count = 10;
moveBar.setProgress(100);
startProgress();
break;
}*/
}catch (Exception i){
i.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
moveBar.setProgress(10 * count);
Log.e("Count", " " + count);
if(count == 0){
Toast.makeText(getApplicationContext(),
"Result screen", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});sleep.start();
}
}
2) For AsyncTask, use these links to guide you
http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.Vz7rW3yrS6k
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
The warning eclipse gives me is an unsued import warning on the View.OnClickListener, but i am using it... I am pretty confident this is where my error lies. Please take a look at my code and correct all errors. This is my first attempt to write an app from scratch. Thank you for your time!
This is my main but it is called SICalculatorActivity
package com.codeherenow.sicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SICalculatorActivity extends Activity {
private Button calcButton;
private SeekBar yearsSeek = null;
private EditText principalAmount;
private EditText interestRate;
private TextView scaleReadout;
private TextView resultText;
float totalAmount;
float iRate;
float pAmount;
float years;
String result;
// public int progressChanged=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
resultText = (TextView) findViewById(R.id.resultText);
result=resultText.getText().toString();
scaleReadout = (TextView) findViewById(R.id.scaleReadout);
years=Float.parseFloat(scaleReadout.getText().toString());
calcButton = (Button) findViewById(R.id.Calc_button);
yearsSeek = (SeekBar) findViewById(R.id.seekBar1);
principalAmount= (EditText) findViewById(R.id.editPrincipalAmount);
pAmount=Float.parseFloat(principalAmount.getText().toString());
interestRate = (EditText) findViewById(R.id.editIntrestRate);
iRate = Float.parseFloat(interestRate.getText().toString());
yearsSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
// int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
yearsSeek.setMax(50);
scaleReadout.setText(progress + " Years");
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
// Toast.makeText(SeekBarActivity.this, progressChanged +
// " Years", Toast.LENGTH_SHORT)
// .show();
}
});
// onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
calcButton.setOnClickListener(new OnClickListener() {
public void onClick1(View v) {
calculateinterest();
finish();
}
private String calculateinterest() {
// TODO Auto-generated method stub
totalAmount=(pAmount*(iRate/100)*years);
result=(totalAmount+"we did it!!");
return result;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
Here is my main.xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SICalculatorActivity" >
<TextView
android:id="#+id/PrincipalAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="23dp"
android:layout_marginTop="27dp"
android:text="Principal Amount ($)"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editPrincipalAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/PrincipalAmount"
android:layout_below="#+id/PrincipalAmount"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/InterestRate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editPrincipalAmount"
android:layout_below="#+id/editPrincipalAmount"
android:layout_marginTop="49dp"
android:text="Interest Rate"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editIntrestRate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/InterestRate"
android:layout_below="#+id/InterestRate"
android:ems="10"
android:inputType="numberDecimal" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editIntrestRate"
android:layout_marginTop="55dp" />
<TextView
android:id="#+id/scaleReadout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editIntrestRate"
android:layout_below="#+id/editIntrestRate"
android:layout_marginTop="32dp"
android:text="0 Years"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/resultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="31dp"
android:text="#+string/result"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/Calc_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="27dp"
android:text="Calculate" />
</RelativeLayout>
and im not sure this helps but here is my manifest file as well
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.codeherenow.sicalculator"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.codeherenow.sicalculator.SICalculatorActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Thank you for taking time to help poor, ignorant, ol me!! Many thanks!
calcButton.setOnClickListener(new View.OnClickListener() {
#Override//missing
public void onClick(View arg0) {
// TODO Auto-generated method stub
calculateinterest(); // It is returning a String but you are not storing it anywhere. (Just Wondering)
finish(); // I don't know why are you calling the finish() here. So I'm keeping it
}
});
Your onClick Listener should look like this
calcButton.setOnClickListener(new View.OnClickListener() {
#Override//missing
public void onClick(View arg0) {
// TODO Auto-generated method stub
result = calculateinterest();
finish();
}
});
And change your calculateinterest() like below
private String calculateinterest() {
// TODO Auto-generated method stub
String amount = principalAmount.getText().toString();
String rate = interestRate.getText().toString();
if (amount.trim().equlas("") || rate.trim().equals(""))
Toast.makeText(getApplicationContext(), "Please enter the values", Toast.Length_SHORT).show();
else
{
pAmount=Float.parseFloat(amount);
iRate = Float.parseFloat(rate);
totalAmount=(pAmount*(iRate/100)*years);
String output = "( " + totalAmount +" we did it!!) ";
return output;
}
}
Your onclick listener is wrong. Its missing the #override annotation.
calcButton.setOnClickListener(new OnClickListener() {
public void onClick1(View v) {
calculateinterest();
finish();
}
It should be like this:
calcButton.setOnClickListener(new View.OnClickListener() {
#Override//missing
public void onClick(View arg0) {
// TODO Auto-generated method stub
calculateinterest();
finish();
}
});
You are actually not using the "onClick()" method in onClick Listener of your Button
So essentially when a click is performed on your button calculateinterest() & finish() are not executed.
Cause when the onClick is performed following method is invoked, which in your case doesn't have an implementation
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
Move your code in onClick1(View) to the Overriden onClick(View) method so it looks like below
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
calculateinterest();
finish();
}
private String calculateinterest() {
// TODO Auto-generated method stub
totalAmount=(pAmount*(iRate/100)*years);
result=(totalAmount+"we did it!!");
return result;
}
});
Try this way,hope this will help you to solve your problem.
public class MyActivity extends Activity {
private Button calcButton;
private SeekBar yearsSeek = null;
private EditText principalAmount;
private EditText interestRate;
private TextView scaleReadout;
private TextView resultText;
float totalAmount;
float iRate;
float pAmount;
float years;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultText = (TextView) findViewById(R.id.resultText);
scaleReadout = (TextView) findViewById(R.id.scaleReadout);
calcButton = (Button) findViewById(R.id.Calc_button);
yearsSeek = (SeekBar) findViewById(R.id.seekBar1);
principalAmount= (EditText) findViewById(R.id.editPrincipalAmount);
interestRate = (EditText) findViewById(R.id.editIntrestRate);
yearsSeek.setProgress(1);
yearsSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
yearsSeek.setMax(50);
scaleReadout.setText(progress + " Years");
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calculateinterest();
finish();
}
});
}
private String calculateinterest() {
boolean isValidate = true;
if(principalAmount.getText().toString().length() <= 0){
isValidate = false;
principalAmount.setError("Value Required");
}
if(interestRate.getText().toString().length() <= 0){
isValidate = false;
interestRate.setError("Value Required");
}
if(isValidate){
pAmount =Float.parseFloat(principalAmount.getText().toString());
iRate = Float.parseFloat(interestRate.getText().toString());
years=Float.parseFloat(scaleReadout.getText().toString());
totalAmount=(pAmount*(iRate/100)*years);
result=(totalAmount+"we did it!!");
return result;
}else{
return "";
}
}
}
Thanks Everyone! You were all very very close, but everyone seemed to fail to notice that i did not set years to the progress of the seek bar, so when my answer was 0.0 everytime! Here is the good running code that did exactly as i intended
package com.codeherenow.sicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class SICalculatorActivity extends Activity {
private Button calcButton;
private SeekBar yearsSeek = null;
private EditText principalAmount;
private EditText interestRate;
private TextView scaleReadout;
private TextView resultText;
float totalAmount;
float iRate;
float pAmount;
float years;
String output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
resultText = (TextView) findViewById(R.id.resultText);
scaleReadout = (TextView) findViewById(R.id.scaleReadout);
calcButton = (Button) findViewById(R.id.Calc_button);
yearsSeek = (SeekBar) findViewById(R.id.seekBar1);
principalAmount = (EditText) findViewById(R.id.editPrincipalAmount);
interestRate = (EditText) findViewById(R.id.editIntrestRate);
yearsSeek.setProgress(1);
yearsSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
yearsSeek.setMax(50);
scaleReadout.setText(progress + " Years");
years=progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
calculateinterest();
resultText.setText(output);
Toast.makeText(getApplicationContext(), ""+ totalAmount, Toast.LENGTH_SHORT)
.show();
//scaleReadout.setText(progress + " Years");
// setContentView(R.layout.sicalculator);
//finish();
}
});}
private void calculateinterest() {
String amount = principalAmount.getText().toString();
String rate = interestRate.getText().toString();
if (amount.trim().equals("") || rate.trim().equals("")){
Toast.makeText(getApplicationContext(), "Please enter the values", Toast.LENGTH_SHORT)
.show();
}
else{
pAmount=Float.parseFloat(amount);
iRate =Float.parseFloat(rate);
totalAmount=(pAmount*(iRate/100)*years);
output= "( "+ totalAmount+" we did it!!) ";
}
}}