I have written a class inside one activity to display a hh:mm:ss timer in my activity:
This is code of the class designed to show the timer:
//class to display on screen timer
class ShowTimer
{
long mMilliseconds = 120000;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
CountDownTimer mCountDownTimer = new CountDownTimer(mMilliseconds, 1000) {
#Override
public void onFinish() {
mTextView.setText(mSimpleDateFormat.format(0));
}
public void onTick(long millisUntilFinished) {
mTextView.setText(mSimpleDateFormat.format(millisUntilFinished));
}
};
}
This is how I am trying to access the class:
mSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
mTextView = (TextView) findViewById(R.id.timer_textView);
mCountDownTimer.start();
I am getting an error like this:
mCountDownTimer cannot be resolved
The full activity is here:
public class SpeedTestExamActivity extends Activity {
String xmlContent=null;
String duration=null;
//strings for use
String answer_str, option1_str,option2_str,option3_str,option4_str;
//text views for quiz layout
TextView question_view;
TextView question_sr_no;
RadioButton option1;
RadioButton option2;
RadioButton option3;
RadioButton option4;
int counter=0;
int loop_checker=0;
int i;
//buttons on UI
Button prevQuestion;
Button nextQuestion;
Button resetQuestion;
Button endTest;
// XML node keys
static final String KEY_LIST = "List"; // parent node
static final String KEY_SR_NO = "SRNo";
static final String KEY_EXAM_SET_ID="ExamSetId";
static final String KEY_Q_ID="QId";
static final String KEY_QT_ID="QTId";
static final String KEY_QUESTION = "Question";
static final String KEY_MARKS = "Marks";
static final String KEY_NEGATIVE_MARKS = "NegativeMark";
static final String KEY_ATTEMPTED_TIME = "AttemtedTime";
static final String KEY_IDLE_TIME = "IdleTime";
static final String KEY_ELAPSED_TIME = "ElapsedTime";
static final String KEY_LAST_Q_INDEX = "LastQIndex";
static final String KEY_SUBJECT_NAME = "SubjectName";
static final String KEY_OPTION1 = "Option1";
static final String KEY_OPTION2 = "Option2";
static final String KEY_OPTION3 = "Option3";
static final String KEY_OPTION4 = "Option4";
static final String KEY_CORRECT = "Correct";
//variables to run the timer
int test_duration;
//object of the handler class
Handler handler;
//textview for timer
TextView mTextView;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_test_exam);
//getting previously received content as xml
xmlContent=getFromPreference("SpeedTestContent");
//getting previously saved exam duration from preference
duration=getFromPreference("exam_duration");
//setting time for timer to finish activity after test duration is over
test_duration=Integer.parseInt(duration.toString())*60000;
//makeAToast("Test duration is ms: "+test_duration);
mSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
mTextView = (TextView) findViewById(R.id.timer_textView);
mCountDownTimer.start();
//starting timer
runTimer();
//assigning objects to layouts
question_view=(TextView)findViewById(R.id.question_textView);
question_sr_no=(TextView)findViewById(R.id.question_id_textView);
option1=(RadioButton)findViewById(R.id.option1_radioButton);
option2=(RadioButton)findViewById(R.id.option2_radioButton);
option3=(RadioButton)findViewById(R.id.option3_radioButton);
option4=(RadioButton)findViewById(R.id.option4_radioButton);
//calling function to populate ui
populating_textview(counter);
//onclick opt 1
option1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option1_str=option1.getText().toString();
if (answer_str.equalsIgnoreCase(option1_str))
{
//makeAToast("Correct!");
//calling function to populate ui with next question
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 2
option2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option2_str=option2.getText().toString();
String answer=answer_str;
if (answer.equalsIgnoreCase(option2_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 3
option3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option3_str=option3.getText().toString();
String answer1=answer_str;
if (answer1.equalsIgnoreCase(option3_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 4
option4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option4_str=option4.getText().toString();
String answer2=answer_str;
if (answer2.equalsIgnoreCase(option4_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick next button
nextQuestion = (Button) findViewById(R.id.next_question_button);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
counter++;
if (counter<=loop_checker)
{
populating_textview(counter);
}
else
{
makeAToast("Game Over!");
}
}
});
//onclick previous button
prevQuestion = (Button) findViewById(R.id.previous_question_button);
prevQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(counter!=0)
{
counter--;
}
if (counter<loop_checker)
{
populating_textview(counter);
}
if(counter==loop_checker)
{
counter--;
populating_textview(counter);
}
if(counter==0)
{
makeAToast("No more questions!");
}
}
});
//onclick reset button
resetQuestion = (Button) findViewById(R.id.reset_question_button);
resetQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
}
});
//onclick end test button
endTest = (Button) findViewById(R.id.end_test_button);
endTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//deactivating timer before finishing activity
handler.removeCallbacksAndMessages(null);
finish();
Intent intent = new Intent(SpeedTestExamActivity.this, RateUsActivity.class);
SpeedTestExamActivity.this.startActivity(intent);
}
});
}
//deactivating back button
#Override
public void onBackPressed() {
}
//getting content from preferences
public String getFromPreference(String variable_name)
{
String get_content;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
get_content = preferences.getString(variable_name,"");
return get_content;
// makeAToast(xmlContent);
}
// function to populate ui with question counter
void populating_textview(int count_questions)
{
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
//String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xmlContent); // getting DOM element
//count_questions=2;
NodeList nl = doc.getElementsByTagName(KEY_LIST);
// looping through all item nodes <item>
for ( i = 0; i < nl.getLength();i++) {
loop_checker=i;
// while(counter< nl.getLength())
// {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(count_questions);
// adding each child node to HashMap key => value
map.put(KEY_LIST, parser.getValue(e, KEY_LIST));
map.put(KEY_SR_NO, parser.getValue(e, KEY_SR_NO));
question_sr_no.setText(parser.getValue(e, KEY_SR_NO)+".");
map.put(KEY_QUESTION, parser.getValue(e, KEY_QUESTION));
question_view.setText(parser.getValue(e, KEY_QUESTION));
map.put(KEY_OPTION1, parser.getValue(e, KEY_OPTION1));
//option1_str =parser.getValue(e, KEY_OPTION1);
option1.setText(parser.getValue(e, KEY_OPTION1));
map.put(KEY_OPTION2, parser.getValue(e, KEY_OPTION2));
option2.setText(parser.getValue(e, KEY_OPTION2));
//option2_str =parser.getValue(e, KEY_OPTION2);
map.put(KEY_OPTION3, parser.getValue(e, KEY_OPTION3));
option3.setText(parser.getValue(e, KEY_OPTION3));
//option3_str =parser.getValue(e, KEY_OPTION3);
map.put(KEY_OPTION4, parser.getValue(e, KEY_OPTION4));
option4.setText(parser.getValue(e, KEY_OPTION4));
//option4_str =parser.getValue(e, KEY_OPTION4);
map.put(KEY_CORRECT, parser.getValue(e, KEY_CORRECT));
// makeAToast(parser.getValue(e, KEY_ANSWER));
answer_str =parser.getValue(e, KEY_CORRECT);
// adding HashList to ArrayList
menuItems.add(map);
}
}
//method to run timer
public void runTimer()
{
handler = new Handler();
// run a thread after a particular time seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
makeAToast("Your time is up!");
Intent intent = new Intent(SpeedTestExamActivity.this, RateUsActivity.class);
finish();
SpeedTestExamActivity.this.startActivity(intent);
}
}, test_duration); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
}
//method to show toast
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
//class to display on screen timer
class ShowTimer
{
long mMilliseconds = 120000;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
CountDownTimer mCountDownTimer = new CountDownTimer(mMilliseconds, 1000) {
#Override
public void onFinish() {
mTextView.setText(mSimpleDateFormat.format(0));
}
public void onTick(long millisUntilFinished) {
mTextView.setText(mSimpleDateFormat.format(millisUntilFinished));
}
};
}
}
The problem is that, I already have the time in ms, I cannot use any hard coded values.
I had followed the tutorial in here.
Where am I going wrong? What should I do to implement the timer?
Thanks in advance
Try this:
ShowTimer showTimer = new ShowTimer();
showTimer.mCountDownTimer.start();
Or better use an accessor in ShowTimer:
showTimer.getCountDownTimer().start();
The getCountDownTimer returns mCountDownTimer:
public CountDownTimer getCountDownTimer() {
return mCountDownTimer;
}
You have mCountDownTimer declared in the inner class rather than the main class. If you move it up into your SpeedTestExamActivity class you'll be able to access it.
mCountDownTime is an instance field so therefore you need an instance of ShowTimer on which to access the field.
Related
I am making an app which consists of an activity and a service. By pressing a button the service is started, it collects data in the background from a sensor and classifies it and outputs a string. I want to display the string in a textView. Right now I can see in the log that the variable is updated 2 times every second, but when I try and update the textView from the service class nothing is happening unless I press the button, whenever I press the button, the string is displayed in the textView.
What is the easiest solution here? I tried to make the textView static and it still can't update it. Can you make it so that the view is updated automatically every second? Can I add a listener somehow? Since I am not very experienced I would like an easy solution that does not have to be a "good" one.
Here is my code
Activity:
public class CollectorActivity extends Activity {
private enum State {
IDLE, COLLECTING, TRAINING, CLASSIFYING
};
private final String[] mLabels = { Globals.CLASS_LABEL_STANDING,
Globals.CLASS_LABEL_WALKING, Globals.CLASS_LABEL_RUNNING,
Globals.CLASS_LABEL_OTHER };
private RadioGroup radioGroup;
private final RadioButton[] radioBtns = new RadioButton[4];
private Intent mServiceIntent;
private File mFeatureFile;
public static TextView mCurrentLabel;
private State mState;
private Button btnDelete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radioGroup = (RadioGroup) findViewById(R.id.radioGroupLabels);
radioBtns[0] = (RadioButton) findViewById(R.id.radioStanding);
radioBtns[1] = (RadioButton) findViewById(R.id.radioWalking);
radioBtns[2] = (RadioButton) findViewById(R.id.radioRunning);
radioBtns[3] = (RadioButton) findViewById(R.id.radioOther);
btnDelete = (Button) findViewById(R.id.btnDeleteData);
mCurrentLabel = (TextView) findViewById(R.id.textView);
mState = State.IDLE;
mFeatureFile = new File(getExternalFilesDir(null),
Globals.FEATURE_FILE_NAME);
mServiceIntent = new Intent(this, SensorsService.class);
}
public void onCollectClicked(View view) {
if (mState == State.IDLE) {
mState = State.COLLECTING;
((Button) view).setText(R.string.ui_collector_button_stop_title);
btnDelete.setEnabled(false);
radioBtns[0].setEnabled(false);
radioBtns[1].setEnabled(false);
radioBtns[2].setEnabled(false);
radioBtns[3].setEnabled(false);
int acvitivtyId = radioGroup.indexOfChild(findViewById(radioGroup
.getCheckedRadioButtonId()));
String label = mLabels[acvitivtyId];
Bundle extras = new Bundle();
extras.putString(Globals.CLASS_LABEL_KEY, label);
mServiceIntent.putExtras(extras);
startService(mServiceIntent);
} else if (mState == State.COLLECTING) {
mState = State.IDLE;
((Button) view).setText(R.string.ui_collector_button_start_title);
btnDelete.setEnabled(true);
radioBtns[0].setEnabled(true);
radioBtns[1].setEnabled(true);
radioBtns[2].setEnabled(true);
radioBtns[3].setEnabled(true);
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();
}
}
public void onDeleteDataClicked(View view) {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
if (mFeatureFile.exists()) {
mFeatureFile.delete();
}
Toast.makeText(getApplicationContext(),
R.string.ui_collector_toast_file_deleted,
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (mState == State.TRAINING) {
return;
} else if (mState == State.COLLECTING || mState == State.CLASSIFYING) {
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel(Globals.NOTIFICATION_ID);
}
super.onBackPressed();
}
#Override
public void onDestroy() {
// Stop the service and the notification.
// Need to check whether the mSensorService is null or not.
if (mState == State.TRAINING) {
return;
} else if (mState == State.COLLECTING || mState == State.CLASSIFYING) {
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancelAll();
}
finish();
super.onDestroy();
}
And this is the "doInBackground" method in my service class. The line "CollectorActivity.mCurrentLabel.setText(classification);" is the problem. I want this to update the textView continously.
public class OnSensorChangedTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Instance inst = new DenseInstance(mFeatLen);
inst.setDataset(mDataset);
Instance inst2 = new DenseInstance(65);
int blockSize = 0;
FFT fft = new FFT(Globals.ACCELEROMETER_BLOCK_CAPACITY);
double[] accBlock = new double[Globals.ACCELEROMETER_BLOCK_CAPACITY];
double[] re = accBlock;
double[] im = new double[Globals.ACCELEROMETER_BLOCK_CAPACITY];
double max = Double.MIN_VALUE;
while (true) {
try {
// need to check if the AsyncTask is cancelled or not in the while loop
if (isCancelled () == true)
{
return null;
}
// Dumping buffer
accBlock[blockSize++] = mAccBuffer.take().doubleValue();
if (blockSize == Globals.ACCELEROMETER_BLOCK_CAPACITY) {
blockSize = 0;
testList = new ArrayList<Double>();
// time = System.currentTimeMillis();
max = .0;
for (double val : accBlock) {
if (max < val) {
max = val;
}
}
fft.fft(re, im);
for (int i = 0; i < re.length; i++) {
double mag = Math.sqrt(re[i] * re[i] + im[i]
* im[i]);
inst.setValue(i, mag);
testList.add(i,mag);
im[i] = .0; // Clear the field
}
// Append max after frequency component
inst.setValue(Globals.ACCELEROMETER_BLOCK_CAPACITY, max);
inst2.setValue(Globals.ACCELEROMETER_BLOCK_CAPACITY, max);
testList.add(max);
classificationIndex = WekaClassifier.classify(testList.toArray());
classification = testLabel.get((int) classificationIndex);
CollectorActivity.mCurrentLabel.setText(classification);
inst.setValue(mClassAttribute, mLabel);
mDataset.add(inst);
Log.i("new instance", mDataset.size() + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
In doInBackground(Void... arg0) change CollectorActivity.mCurrentLabel.setText(classification); to publishProgress(classification); then change second argument from Void to String: public class OnSensorChangedTask extends AsyncTask<Void, Srting, Void> and add onProgressUpdate().
Finally your code should looks like:
public class OnSensorChangedTask extends AsyncTask<Void, Srting, Void> {
#Override
protected Void doInBackground(Void... arg0) {
//...
publishProgress(classification);
//...
}
#Override
protected Void onProgressUpdate(String... classification) {
CollectorActivity.mCurrentLabel.setText(classification[0]);
}
So, I am creating a little trivia game for learning purposes, but I ran into a problem.
First, I had a specific Android Fragment obtaining the data from JSON, and I will simply use that data on the callback method and display it on TextViews and Buttons. Everything was working fine, however, every time I returned to that fragment, the same questions would be there. So I decided to handle that in a better way outside of the callback method.
The problem here is that apparently my Arrays are either null or their lengths is zero. Which is weird, because according to my LOG, data is being passed to those arrays on the callback method.
Here's my full fragment code. Thanks!
public class GameFragment extends Fragment {
private TextView txtQuestion;
private Button btnAnswer1;
private Button btnAnswer2;
private Button btnAnswer3;
private Button btnAnswer4;
private Questions[] gameQuestions;
private Questions[] animeQuestions;
private Questions[] techQuestions;
private Questions[] movieQuestions;
private Questions[][] gameCategories = new Questions[4][];
int correctAnswer = -1;
private TransparentProgressDialog progressBar;
private Handler handler;
private Runnable runnable;
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
gameCategories[0] = new Questions[myApiData.getCategory()[0].getQuestions(0).length];
gameCategories[1] = new Questions[myApiData.getCategory()[1].getQuestions(1).length];
gameCategories[2] = new Questions[myApiData.getCategory()[2].getQuestions(2).length];
gameCategories[3] = new Questions[myApiData.getCategory()[3].getQuestions(3).length];
//gameCategories = new Questions[][] {gameQuestions, animeQuestions, techQuestions, movieQuestions};
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
gameCategories[i][j] = myApiData.getCategory()[i].getQuestions(i)[j];
//Log.d("GameFragment", "gameCategories[i][j] - gameCategories["+i+"]["+j+"]: " + gameCategories[i][j].getQuestion());
}
}
//displayQuestion();
progressBar.dismiss();
displayQuestion();
}
#Override
public void failure(RetrofitError error) {
Log.d("GameScreen", "Callback failed!");
}
};
public GameFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game, container, false);
txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
btnAnswer1 = (Button) view.findViewById(R.id.btnAnswer1);
btnAnswer2 = (Button) view.findViewById(R.id.btnAnswer2);
btnAnswer3 = (Button) view.findViewById(R.id.btnAnswer3);
btnAnswer4 = (Button) view.findViewById(R.id.btnAnswer4);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer2.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer3.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(view);
}
});
handler = new Handler();
progressBar = new TransparentProgressDialog(getActivity(), R.drawable.loading_spinner);
runnable = new Runnable() {
#Override
public void run() {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
};
//launchRingDialog();
//RestClient.get().getQuestions(cb);
// Inflate the layout for this fragment
return view;
}
public void launchRingDialog() {
new Thread(new Runnable() {
public void run(){
try {
Log.d("Thred", "Try");
progressBar.show();
RestClient.get().getQuestions(cb);
//Thread.sleep(10000);
} catch (Exception e) {
}
//progressBar.dismiss();
}
}).start();
}
public void checkAnswer(View v){
switch(v.getId()){
case R.id.btnAnswer1:
if(correctAnswer == 1){
feedback(true, btnAnswer1);
}else {
feedback(false, btnAnswer1);
}
break;
case R.id.btnAnswer2:
if(correctAnswer == 2){
feedback(true, btnAnswer2);
}else {
feedback(false, btnAnswer2);
}
break;
case R.id.btnAnswer3:
if(correctAnswer == 3){
feedback(true, btnAnswer3);
}else {
feedback(false, btnAnswer3);
}
break;
case R.id.btnAnswer4:
if(correctAnswer == 4){
feedback(true, btnAnswer4);
}else {
feedback(false, btnAnswer4);
}
break;
default: txtQuestion.setText("Error");
break;
}
}
public void feedback(Boolean correct, Button btn){
if(correct){
btn.setBackgroundColor(Color.GREEN);
btn.setText("CORRECT!");
}else{
btn.setBackgroundColor(Color.RED);
btn.setText("WRONG!");
}
}
#Override
public void onResume() {
super.onResume();
//displayQuestion();
}
public void displayQuestion(){
Random randomizer = new Random();
int randomQuestion;
int category = GTMain.choosenCategory;
if(category == 5){
category = randomizer.nextInt(4);
}
randomQuestion = randomizer.nextInt(25);
Log.d("displayQuestion", "Before if statements");
if(gameCategories != null && gameCategories.length != 0) {
Log.d("displayQuestion", "First if");
if(gameCategories[category] != null && gameCategories[category].length != 0){
Log.d("displayQuestion", "Second if");
txtQuestion.setText(gameCategories[category][randomQuestion].getQuestion());
correctAnswer = gameCategories[category][randomQuestion].getCorrectAnswer();
Log.d("displayQuestion()", "correctAnswer: " + correctAnswer);
btnAnswer1.setText(gameCategories[category][randomQuestion].getAnswers().getA1());
btnAnswer2.setText(gameCategories[category][randomQuestion].getAnswers().getA2());
btnAnswer3.setText(gameCategories[category][randomQuestion].getAnswers().getA3());
btnAnswer4.setText(gameCategories[category][randomQuestion].getAnswers().getA4());
}
}
}
}
PS: On my main activity, I check to see which fragment should be loaded. If it's the fragment that contains the components to display the questions and answer (the one from the code above), I call the following method: gameFragment.launchRingDialog(); (and yes, I have created an instance of my GameFragment fragment before calling that method!)
When onResume() is called, your RestClient.get().getQuestions(cb) is still running in background, and your call displayQuestion(), so of course nothing is shown.
Can you put displayQuestion() inside success() of your callback?
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
....
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
...
}
}
displayQuestion();
}
....
};
I would also suggest you to remove displayQuestion() in onResume() method.
I want to validation on RatingBar in Android. I have 5 rating Bar and 1 Button. I don't want to submit the data without pressed the rating bar. I want to take validation on Rating bar.
Can someone help me. How to take validation on Rating bar?
Here is my Activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rating_baar);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
addListenerOnRatingBar_one();
addListenerOnRatingBar_two();
addListenerOnRatingBar_three();
addListenerOnRatingBar_four();
addListenerOnRatingBar_five();
addListenerOnButton();
}
#SuppressLint("SimpleDateFormat")
public void addListenerOnButton() {
buttonSubmitRate = (Button) findViewById(R.id.button_SubmitRate);
buttonSubmitRate.setOnClickListener(new OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
if((etTaskName.getText().toString().isEmpty()))
etTaskName.setError("Field Can Not Be Empty !");
else if (!etTaskName.getText().toString().trim().matches("[a-zA-Z{ }]+"))
etTaskName.setError("Accept Alphabets Only.");
else {
strEmpName = textViewNAme.getText().toString().trim();
strTaskName = etTaskName.getText().toString().trim();
String strCurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println("strCurrentDate = " + strCurrentDate);
String strCurrentMonth = new SimpleDateFormat("MMM").format(new Date());
System.out.println("strCurrentDate = " + strCurrentMonth);
String strCurrenYear = new SimpleDateFormat("yyyy").format(new Date());
System.out.println("strCurrenYear = " + strCurrenYear);
System.out.println("__________________________________________________________________________________");
databaseHelper.insertPerformance_Details(intentStr1, strEmpName,
strTaskName, rateVal_one,
rateVal_two, rateVal_three,
rateVal_four,rateVal_five,
strCurrentDate,strCurrentMonth,
strCurrenYear);
System.out.println("Data Add SuccesFully !!!!");
etTaskName.setText("");
Intent i = new Intent(RatingBaar_Class.this, Rating_Msg.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.anim_in,R.anim.anim_out);
}
}
});
}
public void addListenerOnRatingBar_one() {
ratingBar_one = (RatingBar) findViewById(R.id.ratingBar1);
ratingBar_one.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rateVal_one = String.valueOf(rating);
System.out.println(" rateVal_one = " + rateVal_one);
}
});
}
/* Exactly the same methods for four other rating bars, except for variable names */
public void addListenerOnRatingBar_two() { ... }
public void addListenerOnRatingBar_three() { ... }
public void addListenerOnRatingBar_four() { ... }
public void addListenerOnRatingBar_five() { ... }
At first set all rating bar to 0 value. Then on click to button, check if the value has altered in all of them. If so, only valid else invalid.
Also you can use listener to each rating bar and change value of some boolean variable to true
Example:
boolean flag1 = false;
boolean flag2 = false;
.... //similarly upto 5
Then in rating bar listener1
{
flag1 = true;
}
Similarly for all set flag to be true
And in button onClickListener do the following:
if(flag1 && flag2 && flag3 && flag4 && flag5){
//do your work
}else{
//display message that one of the rating bar hasn't been touched
}
I checked other similar tags with almost same title. Those answers were not relevant
When setting element at one position of array, both the elements have the same value.
public class LogActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
startStopButton = (Button) findViewById(R.id.btnStart);
loggingStatusText = (TextView) findViewById(R.id.logStatusText);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
sensorValues=new ArrayList<float[]>(sensorList.size());
sensorValsArray=new float[sensorList.size()][];
sensorNameList = new ArrayList<String>();
selectedSensorNames = new ArrayList<String>();
for (Sensor itemSensor : sensorList)
{
if (itemSensor != null)
{
sensorNameList.add(itemSensor.getName());
}
}
showSensorList();
}
private void showSensorList()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setMultiChoiceItems((CharSequence[]) sensorNameList
.toArray(new CharSequence[sensorNameList.size()]),
new boolean[sensorNameList.size()],
new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked)
{
if (isChecked)
{
if (!selectedSensorNames.contains(sensorNameList
.get(whichButton)))
selectedSensorNames.add(sensorNameList
.get(whichButton));
} else
{
if (selectedSensorNames.contains(sensorNameList
.get(whichButton)))
{
selectedSensorNames.remove(sensorNameList
.get(whichButton));
}
}
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
listeners=new SensorEventListener[selectedSensorNames.size()];
float[] tempVals = new float[] { 0, 0, 0 };
for (int i = 0; i < selectedSensorNames.size(); i++)
{
sensorValsArray[i]=tempVals;
}
showRateList();
}
});
builder.setCancelable(false);
builder.create().show();
}
void registerSensors()
{
for (Sensor sensor : sensorList)
{
if (selectedSensorNames.contains(sensor.getName()))
{
mSensorManager.registerListener(listeners[selectedSensorNames.indexOf(sensor.getName())], sensor, selectedDelay);
}
}
}
class SchedulerTask extends TimerTask
{
/*
* The task to run should be specified in the implementation of the
* run() method
*/
public void run()
{
logSensorData();
}
}
private void createLog(String fileName)
{
File root = getExternalFilesDir(null);// Get the Android external
// storage directory
Date cDate = new Date();
String bstLogFileName = fileName;
bstLogFile = new File(root, bstLogFileName);// Construct a new file for
// using the specified
// directory and name
FileWriter bstLogWriter;
logScheduler = new Timer();// Create a new timer for updating values
// from content provider
logScheduler.schedule(new SchedulerTask(),
LOG_TASK_DELAY_IN_MILLISECONDS,
getLogPeriodInMilliSeconds(selectedDelay));
}
public void logSensorData()
{
Date stampDate = new Date();
String LogPack ="\r\n";
for (int count=0;count<selectedSensorNames.size();count++)
{
LogPack += sensorValsArray[count][0] + "," + sensorValsArray[count][1] + "," + sensorValsArray[count][2] + ",";
}
LogPack += "\r\n";
try
{
F_StreamWriter.write(LogPack);
F_StreamWriter.flush();
}
catch (IOException e)
{
}
catch (NullPointerException e)
{
}
}
public void startStopLog(View v)
{
if (startStopButton.getText().equals("Start"))
{
createSensorListeners();
registerSensors();
showFilenameDialog();
} else if (startStopButton.getText().equals("Stop"))
{
stopLog();
}
}
public void startLog(String fileName)
{
createLog(fileName);
}
public void stopLog()
{
logScheduler.cancel();
logScheduler.purge();
for(int i=0;i<listeners.length;i++)
mSensorManager.unregisterListener(listeners[i]);
}
private void showFilenameDialog()
{
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_text_input_dialog);
dialog.setCancelable(true);
final EditText fileNameInput = (EditText) dialog
.findViewById(R.id.fileNameText);
Button button = (Button) dialog.findViewById(R.id.okButton);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startLog(nameInput);
dialog.dismiss();
}
});
dialog.show();
}
private void createSensorListeners()
{
listeners=new SensorEventListener[selectedSensorNames.size()];
for (int i = 0; i < selectedSensorNames.size(); i++)
{
listeners[i]=new SensorEventListener()
{
#Override
public void onSensorChanged(SensorEvent event)
{
sensorValsArray[selectedSensorNames.indexOf(event.sensor.getName())]=event.values;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
};
}
}
}
When index is 0, when set command is executed, it also changes the the value at index position '1'.
Can anyone help me with this?
Thanks in Advance,
Dheepak
When index is 0, when set command is executed, it also changes the the value at index position '1'. Can anyone help me with this?
You are definitely mistaken as to what it is causing this. Setting the value at one position of an ArrayList WILL NOT mysteriously cause the value at another position to change. It simply does not work like that.
The effect you are observing will be due to something else:
maybe the value of index is not what you expect
maybe the value of event.values is not what you expect. (Maybe you've made a mistake in the way that you create the Event objects, and they are all sharing one float[] object.)
maybe the value at position 1 was already that value
maybe you've got multiple threads updating the sensorValues list.
I'm newbie in java. So the program should take the user entered text and if there is "a" it gonna play a-sound, if there is "b" it gonna play b-sound.And it must play this sounds one by one even if there are multiple "a" or "b". Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bStart = (Button) findViewById(R.id.bStart);
final EditText etStart = (EditText) findViewById(R.id.etStart);
final EditText etFinish = (EditText) findViewById(R.id.etFinish);
final char[] arr = etStart.getText().toString().toCharArray();
final MediaPlayer as = MediaPlayer.create(R2d2Activity.this, R.raw.as);
final MediaPlayer bs = MediaPlayer.create(R2d2Activity.this, R.raw.bs);
final SoundPool sp;
final int a;
final int b;
final int t;
sp = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
a = sp.load(this, R.raw.as, 1);
b = sp.load(this, R.raw.bs, 1);
final String value = etStart.getText().toString();
final Thread timer = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1300);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
}
});
bStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int n = 0;
String value;
String first;
value = etStart.getText().toString();
// TODO Auto-generated method stub
//actual code
for (int i=0; i<value.length(); i++){
first = etStart.getText().toString().substring(i, i+1);
if(first.contentEquals("a")){
as.start();
as.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer arg0) {
//when finished
}
});
}else{
}
if(first.contentEquals("b")){
bs.start();
}else{
}
}
}
});
The problem is that it starts playing audio files all at one time. I tried to add some OnCompletionListener, but I don't know what to do with it. Help me please.
What you can do is
//define a variable to be used as index.
int audioindex = 0;
//Extract the files id into an array
int[] audioFileIds=new int[]{R.raw.as,R.raw.bs};
Then in your MediaPlayer onCompletionListener put something like following.
then in your OnCompletionListener.
mp.setOnCompletionListener(new OnCompletionListener(){
// #Override
public void onCompletion(MediaPlayer player) {
// File has ended, play the next one.
FunctionPlayFile(audioFileIds[audioindex]);
audioindex+=1; //increment the index to get the next audiofile
}
});