Passing variable score from one activity to another - java

I'm making a simple quiz app that consist of 10 questions with 10sec countdown timer each questions, which means i have 10 activity for questions. The scoring works while each questions answer correctly multiply by remaining time on CountDownTimer method, so it will be: score = answer * timeLeft; And the total score will be printed on ResultActivity at the end of activity after activity 10. The problem is i cannot pass my score variable through each activity and when i click next button that intent from activity 10 to ResultActivity, the ResultActivity cannot be open or force close. Here is my code:
TestActivity1
package com.finalproject.logicaltest;
import android.content.Intent;
import android.os.CountDownTimer;
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.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Timer;
import butterknife.ButterKnife;
import butterknife.Bind;
import static android.R.id.message;
import static android.R.string.cancel;
import static com.finalproject.logicaltest.R.id.rb1;
import static com.finalproject.logicaltest.R.id.rb2;
import static com.finalproject.logicaltest.R.id.rb3;
import static com.finalproject.logicaltest.R.id.rb4;
public class TestActivity1 extends AppCompatActivity {
#Bind(R.id.rb1) RadioButton rB1;
#Bind(R.id.rb2) RadioButton rB2;
#Bind(R.id.rb3) RadioButton rB3;
#Bind(R.id.rb4) RadioButton rB4;
#Bind(R.id.next) Button bNext;
#Bind(R.id.timer) TextView cDown;
public int answer = 0;
public int score = 0;
public long timeLeft = 0;
//The number of milliseconds in the future from
//the call to start() until the countdown is done
public long millisInFuture = 11000; //11 seconds
//The interval along the way to receive onTick(long) callbacks
long countDownInterval = 1000; //1 second
public long millisUntilFinished;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test1);
ButterKnife.bind(this);
setTimer();
}
public void setTimer() {
//Initialize a new CountDownTimer instance
final CountDownTimer timer = new CountDownTimer(millisInFuture,countDownInterval){
public void onTick(long millisUntilFinished){
//do something in every tick
//Display the remaining seconds to app interface
//1 second = 1000 milliseconds
cDown.setText("" + millisUntilFinished / 1000);
timeLeft = millisUntilFinished / 1000;
}
public void onFinish(){
//Do something when count down finished
cDown.setText("NEXT!");
Intent intent = new Intent(TestActivity1.this,TestActivity2.class);
intent.putExtra("score", score);
startActivity(intent);
finish();
timeLeft = 0;
}
}.start();
bNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
timeLeft = millisUntilFinished;
Intent intent = new Intent(TestActivity1.this,TestActivity2.class);
intent.putExtra("score", score);
startActivity(intent);
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
public void onRadioButtonClicked (View v) {
boolean checked = ((RadioButton) v).isChecked();
switch (v.getId()) {
case rb1:
if (checked){
answer++;
break;
}
case rb2:
if (checked){
answer = 0;
break;
}
case rb3:
if (checked){
answer = 0;
break;
}
case rb4:
if (checked){
answer = 0;
break;
}
}
score = ((int)(timeLeft) * Integer.valueOf(answer));
}
}
It pass score with putExtra through TestActivity2 until TestActivity10 like this:
package com.finalproject.logicaltest;
/**
* Created by VICKY on 19-May-17.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.Bind;
import static com.finalproject.logicaltest.R.id.rb1;
import static com.finalproject.logicaltest.R.id.rb2;
import static com.finalproject.logicaltest.R.id.rb3;
import static com.finalproject.logicaltest.R.id.rb4;
import static com.finalproject.logicaltest.R.id.rb5;
public class TestActivity10 extends AppCompatActivity {
#Bind(rb1) RadioButton rB1;
#Bind(rb2) RadioButton rB2;
#Bind(rb3) RadioButton rB3;
#Bind(rb4) RadioButton rB4;
#Bind(rb5) RadioButton rB5;
#Bind(R.id.end) Button bEnd;
#Bind(R.id.timer) TextView cDown;
public int answer = 0;
public int score = 0;
public long timeLeft = 0;
//The number of milliseconds in the future from
//the call to start() until the countdown is done
public long millisInFuture = 11000; //11 seconds
//The interval along the way to receive onTick(long) callbacks
long countDownInterval = 1000; //1 second
public long millisUntilFinished;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test10);
ButterKnife.bind(this);
score = getIntent().getExtras().getInt("score");
setTimer();
}
public void setTimer() {
//Initialize a new CountDownTimer instance
final CountDownTimer timer = new CountDownTimer(millisInFuture,countDownInterval){
public void onTick(long millisUntilFinished){
//do something in every tick
//Display the remaining seconds to app interface
//1 second = 1000 milliseconds
cDown.setText("" + millisUntilFinished / 1000);
timeLeft = millisUntilFinished / 1000;
}
public void onFinish(){
//Do something when count down finished
cDown.setText("NEXT!");
Intent intent = new Intent(TestActivity10.this,ResultActivity.class);
intent.putExtra("score", score);
startActivity(intent);
finish();
timeLeft = 0;
}
}.start();
bEnd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
timeLeft = millisUntilFinished;
Intent intent = new Intent(TestActivity10.this,ResultActivity.class);
intent.putExtra("score", score);
startActivity(intent);
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
public void onRadioButtonClicked (View v) {
boolean checked = ((RadioButton) v).isChecked();
switch (v.getId()) {
case rb1:
if (checked){
answer = 0;
break;
}
case rb2:
if (checked){
answer++;
break;
}
case rb3:
if (checked){
answer = 0;
break;
}
case rb4:
if (checked){
answer = 0;
break;
}
case rb5:
if (checked){
answer = 0;
break;
}
}
score += ((int)(timeLeft) * Integer.valueOf(answer));
}
}
And printed total score on ResultActivity:
package com.finalproject.logicaltest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import static android.R.id.message;
public class ResultActivity extends AppCompatActivity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
score = getIntent().getExtras().getInt("score");
TextView result = (TextView) findViewById(R.id.total_score);
result.setText(score);
}
}
What's wrong with my code?

Hello Try this code it may help,use according to your logic
Declarations and Initialization
SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences("results", Context.MODE_PRIVATE);
storing your score for using in the other activities
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("score", score);
editor.commit();
Retrieving the stored data
SharedPreferences prefs = this.getSharedPreferences("results", Context.MODE_PRIVATE);
String lanSettings = prefs.getString("score", null);

You can use Application class for that , save score value in Application class which can be accessible from any class you want.(as you only need to save score value.) for more info you can check here
Hope it helps..

IMO you are setting score to your TextView which is incorrect.
Either set it like this:
result.setText(String.valueOf(score));
or like this:
result.setText(" "+score);
See if this works.

Related

How do I end a repeating handler when it hits a certain condition?

I'm making an application that plays audio files off the device's storage, and I have a seek bar that checks the progress of the audio file (how long it has played) every second, and updates the seekbar accordingly.
The audio is played through a service that runs in the foreground, and also displays a notification that the audio is playing.
When the audio ends, I noticed the handler still goes in it's cycle, and I want to end the handler once the audio is done.
What I'm currently trying to do is to end the handler from inside the runnable that the handler runs, as I'm not sure how else I can end it.
Main Activity, where I handle OnClick from the ListView where you can select an audio file and also handles the seekbar update.
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
SeekBar musicProgBar;
Handler progBarHandler = null;
Runnable r = null;
private MP3Service.MyBinder myService = null;
TextView progressText = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
musicProgBar = findViewById(R.id.musicProgressBar);
progressText = findViewById(R.id.progressText);
final ListView lv = (ListView) findViewById(R.id.musicList);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Media.IS_MUSIC + "!= 0",
null,
null);
progBarHandler = new Handler();
final int progBarDelay = 1000; // delay for the handler, making it repeat itself only every 1000 miliseconds (1 second)
lv.setAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[] { MediaStore.Audio.Media.DATA},
new int[] { android.R.id.text1 }));
Intent tempIntent = new Intent(this, MP3Service.class);
startService(tempIntent);
bindService(tempIntent, serviceConnection, 0);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter,
View myView,
int myItemInt,
long myLong) {
Cursor c = (Cursor) lv.getItemAtPosition(myItemInt);
String uri = c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA));
Log.d("g53mdp", uri);
if (myService.fetchPlayerState() != MP3Player.MP3PlayerState.STOPPED)
myService.stopMusic();
myService.loadMusic(uri);
myService.playMusic();
musicProgBar.setMax(myService.fetchDuration()); // set the max value of the seekbar to be the duration of the song
r = new Runnable()
{
#Override
public void run()
{
int tempInt = myService.fetchProgress();
Log.d("progress ticking", tempInt + " " + musicProgBar.getProgress());
musicProgBar.setProgress(tempInt); // sets the current progress of the seekbar to be the progress of the song
long minutes = TimeUnit.MILLISECONDS.toMinutes(tempInt);
long seconds = TimeUnit.MILLISECONDS.toSeconds(tempInt);
if (seconds >= 60)
seconds = seconds - 60;
String tempString = minutes + ":" + seconds;
progressText.setText(tempString);
progBarHandler.postDelayed(this, progBarDelay);
if (musicProgBar.getProgress() == myService.fetchDuration())
progBarHandler.removeCallbacks(this);
}
};
progBarHandler.post(r);
}});
}
private ServiceConnection serviceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName name, IBinder service)
{
myService = (MP3Service.MyBinder) service;
}
#Override
public void onServiceDisconnected(ComponentName name)
{
myService = null;
}
};
public void playButClicked(View view)
{
myService.playMusic();
}
public void pauseButClicked(View view)
{
myService.pauseMusic();
}
public void stopButClicked(View view)
{
myService.stopMusic();
}
#Override
protected void onDestroy()
{
unbindService(serviceConnection);
progBarHandler.removeCallbacks(r);
super.onDestroy();
}
}
What is strange is that in onDestroy(), I do use removeCallbacks to end the handler, and that works nicely. I know that it comes to the point where it calls for removeCallbacks in the Runnable r, confirmed through debugging and logging. Also tried implementing a method that is specifically for removing the handler and calling that, no luck. Also tried using return.
The part I'm struggling with is
r = new Runnable()
{
#Override
public void run()
{
int tempInt = myService.fetchProgress();
Log.d("progress ticking", tempInt + " " + musicProgBar.getProgress());
musicProgBar.setProgress(tempInt); // sets the current progress of the seekbar to be the progress of the song
long minutes = TimeUnit.MILLISECONDS.toMinutes(tempInt);
long seconds = TimeUnit.MILLISECONDS.toSeconds(tempInt);
if (seconds >= 60)
seconds = seconds % 60;
String tempString = minutes + ":" + seconds;
progressText.setText(tempString);
progBarHandler.postDelayed(this, progBarDelay);
if (musicProgBar.getProgress() == myService.fetchDuration())
progBarHandler.removeCallbacks(this);
}
};
progBarHandler.post(r);
}});
The service which handles the music player and handles playing the music
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
public class MP3Service extends Service
{
public static MP3Service instance = null; // implementing singleton by instantiating a reference to the instance
private final String SERVICE_ID = "100"; // id for the service
public static boolean isRunning = false; //
NotificationManager notificationManager = null;
int notificationID = 001;
private final IBinder binder = new MyBinder();
MP3Player mainPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return binder;
}
#Override
public void onRebind(Intent intent)
{
// TODO: implement Rebind for screen orientation change
}
#Override
public void onCreate()
{
instance = this;
isRunning = true;
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mainPlayer = new MP3Player();
super.onCreate();
Handler handler = new Handler();
}
#Override
public void onDestroy()
{
isRunning = false;
instance = null;
notificationManager.cancel(notificationID);
}
public void createNotification()
{
CharSequence name = "MP3 Notification";
String description = "Displays a notification when a song is playing";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(SERVICE_ID, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// when the user clicks the notification, this will bring them to the activity
PendingIntent navToMainActivity = PendingIntent.getActivity(this, 0, intent, 0);
// sets up the info and details for the notification
final NotificationCompat.Builder mNotification = new NotificationCompat.Builder(this, SERVICE_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("MP3 Player")
.setContentText("Playing music")
.setContentIntent(navToMainActivity)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
startForeground(notificationID, mNotification.build());
}
public void removeNotification()
{
stopForeground(false);
notificationManager.cancelAll();
}
public class MyBinder extends Binder
{
public void loadMusic(String filePath)
{
mainPlayer.load(filePath);
}
public void playMusic()
{
mainPlayer.play();
createNotification();
}
public void pauseMusic()
{
mainPlayer.pause();
removeNotification();
}
public void stopMusic()
{
mainPlayer.stop();
removeNotification();
}
public MP3Player.MP3PlayerState fetchPlayerState()
{
return mainPlayer.getState();
}
public int fetchDuration()
{
return mainPlayer.getDuration();
}
public int fetchProgress()
{
return mainPlayer.getProgress();
}
}
}
Thanks in advance for any help, and I am happy to provide with more information if required
EDIT: changed the progBarHandler.postDelay() that is outside the runnable to a simple progBarHandler.post()
I think the only reason you failed to stop the handler is constantly invoking progBarHandler.postDelayed(this, progBarDelay);,you need to check why it's still running.
Managed to get it working by introducing a different kind of if statement to the runnable, like so
Runnable r = new Runnable()
{
#Override
public void run()
{
if (musicProgBar.getProgress() == myService.fetchProgress() && myService.fetchProgress() != 0)
Log.d("audio", "over");
else {
int tempInt = myService.fetchProgress();
long minutes = TimeUnit.MILLISECONDS.toMinutes(tempInt);
long seconds = TimeUnit.MILLISECONDS.toSeconds(tempInt);
if (seconds >= 60)
seconds = seconds % 60;
String tempString = minutes + ":" + seconds;
progressText.setText(tempString);
musicProgBar.setProgress(tempInt); // sets the current progress of the seekbar to be the progress of the song
progBarHandler.postDelayed(this, progBarDelay);
}
}
};
It seemed for some reason, using .fetchDuration() and .fetchProgress() will never equalize each other, so changing the if statement worked.

App Crash on Arrayupdate within Ticklistener

im working through my first app right now and i have a problem concerning an update of an Arraylist object.
This is the code:
package com.example.stopwatchmulti;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class Main2Activity extends AppCompatActivity {
//Define Variables and Arrays
String ergebnis;
String stopTime;
int anzahl;
int hours;
int minutes;
int seconds;
Chronometer chronometer;
long pauseOffset;
boolean running;
int arrayelements = anzahl - 1;
long timeElapsed;
ListView customListview;
ArrayList<UserIDs> userList;
ArrayList<String> stoppedTime;
CustomListview adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ergebnis = getIntent().getExtras().getString("Ergebnis");
anzahl = Integer.parseInt(ergebnis);
chronometer = findViewById(R.id.chronometer);
customListview = (ListView) findViewById(R.id.customListview);
userList = new ArrayList<>();
// Add Lines in favour of UserChoice in First activity
for (int i = 1; i <= anzahl; i++) {
UserIDs user = new UserIDs(String.valueOf(i), "Chronometer" + String.valueOf(i), stopTime);
userList.add(user);
}
stopTime = String.valueOf(hours)+":"+String.valueOf(minutes)+":"+String.valueOf(seconds);
// Run Custom ArrayAdapter
adapter = new CustomListview(this, R.layout.usertableobjects, userList);
customListview.setAdapter(adapter);
}
public void startChronometer(View v) {
if (!running) {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
running = true;
new Thread(new updateStoptime()).start();
}
}
public void pauseChronometer(View v) {
if (running) {
chronometer.stop();
running = false;
}
}
public void resetChronometer(View v) {
chronometer.setBase(SystemClock.elapsedRealtime());
}
class updateStoptime implements Runnable {
#Override
public void run() {
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
timeElapsed = SystemClock.elapsedRealtime() - chronometer.getBase();
hours = (int) (timeElapsed / 3600000);
minutes = (int) (timeElapsed - hours * 3600000 / 6000);
seconds = (int) (timeElapsed - hours * 3600000 - minutes * 60000) / 1000;
stopTime = String.valueOf(hours)+":"+String.valueOf(minutes)+":"+String.valueOf(seconds);
Log.i("Zeit:", String.valueOf(stopTime));
}
});
while(running == true){
for (int i = 1; i <= anzahl; i++) {
userList.get(arrayelements).setUserTime(stopTime);
Log.i("LoopNr:", String.valueOf(i));
}
}
}
}
}
The update of the arraylist in the while loop is the reason why the app is crashing when the user clicks the button. If I just loop through and print the number of the loop in the logs, everything is ok.
Is it too much dada? How can I fix it?
PS. Basically I just need the actual countdowntime, when the user clicks the button and then update the listview with the updated array. So if there's a better and smarter way to achieve this instead of using a while loop, i would appreciate a hint.
Thx in advance
Quick correction:
// Here anzahl is not initialized and is being referred to in the next line.
// Please initialize anzahl first;
int anzahl;
int arrayelements = anzahl - 1;
Then, change your while loop to something like this.
while(running == true){
for (int i = 1; i <= anzahl; i++) {
/* here, just call "i -1". this is basically equal to "arrayelements"
which is not properly referenced up in your code.*/
userList.get(i - 1).setUserTime(stopTime);
Log.i("LoopNr:", String.valueOf(i));
}
}

Checkboxes and if-else statements

This is the source for a small app I'm making in Android Studio. When I call this function its suppose to compare dog,cat, and parrot to each other and then increment int dogCounter by 5. When I run the function however, It does not update the score.
dogCounter= 0;
catCounter = 0;
//check boxes
cutestCheckBoxDog = (CheckBox)findViewById(R.id.CheckboxCutestDog);
cutestCheckBoxCat = (CheckBox)findViewById(R.id.CheckboxCutestCat);
cutestCheckBoxParrot =(CheckBox)findViewById(R.id.CheckboxCutestParrot);
//call methods
processCutest(cutestCheckBoxDog, cutestCheckBoxCat, cutestCheckBoxParrot);
showResultButton= (Button)findViewById(R.id.showResults);
showResultButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),catCounter + " " + dogCounter, Toast.LENGTH_LONG).show();
public void processCutest(CheckBox dog, CheckBox cat, CheckBox parrot){
if (dog.isChecked() && !cat.isChecked() && !parrot.isChecked()){
dogCounter += 5;
}else if (cat.isChecked() && !dog.isChecked() && !parrot.isChecked()){
catCounter += 5;
} else{
//nobody gets points
}
}
edit: Sorry for poor organization. Still pretty new, pointers on that would be nice as well.
package dogorcatperson.ivellapplication.com.dogorcatperson;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private RadioGroup canineRadioGroup;
private RadioButton canineRadioButton;
private SeekBar seekBar;
private TextView seekBarTextView;
private CheckBox cutestCheckBoxDog;
private CheckBox cutestCheckBoxCat;
private CheckBox cutestCheckBoxParrot;
private RadioGroup droolRadioGroup;
private RadioButton droolRadioButton;
private Button showResultButton;
private int dogCounter;
private int catCounter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//call setup()
setUp();
//seekbar
seekBar = (SeekBar) findViewById(R.id.seekBarFeline);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekBarTextView.setText("comfortableness: " + progress + "/" + seekBar.getMax());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void setUp(){
dogCounter= 0;
catCounter = 0;
canineRadioGroup =(RadioGroup)findViewById(R.id.radioGroupCanine);
droolRadioGroup = (RadioGroup)findViewById(R.id.RadioGroupDrool);
seekBarTextView = (TextView)findViewById(R.id.seekBarProgressTextView);
//check boxes
cutestCheckBoxDog = (CheckBox)findViewById(R.id.CheckboxCutestDog);
cutestCheckBoxCat = (CheckBox)findViewById(R.id.CheckboxCutestCat);
cutestCheckBoxParrot = (CheckBox)findViewById(R.id.CheckboxCutestParrot);
//call methods
processCutest(cutestCheckBoxDog, cutestCheckBoxCat, cutestCheckBoxParrot);
processDrool(droolRadioGroup);
processCanine(canineRadioGroup);
showResultButton= (Button)findViewById(R.id.showResults);
showResultButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),catCounter + " " + dogCounter, Toast.LENGTH_LONG).show();
// Intent i = new Intent(MainActivity.this, ResultActivity.class);
// i.putExtra("catCounter", catCounter);
// i.putExtra("dogCounter", dogCounter);
// startActivity(i);
}
});
}
public void processCutest(CheckBox dog, CheckBox cat, CheckBox parrot){
if (dog.isChecked() && !cat.isChecked() && !parrot.isChecked()){
dogCounter += 5;
}else if (cat.isChecked() && !dog.isChecked() && !parrot.isChecked()){
catCounter += 5;
} else{
//nobody gets points
}
}
public void processDrool(final RadioGroup radioGroup){
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int radioId= radioGroup.getCheckedRadioButtonId();
droolRadioButton = (RadioButton)findViewById(radioId);
if (droolRadioButton.getText().equals("yes")){
dogCounter+= 5;
}else if (droolRadioButton.getText().equals("no")){
catCounter+= 5;
}
}
});
}
public void processCanine(final RadioGroup radioGroup){
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int radioId= canineRadioGroup.getCheckedRadioButtonId();
canineRadioButton = (RadioButton)findViewById(radioId);
if (canineRadioButton.getText().equals("yes")){
catCounter+= 5;
}else if (canineRadioButton.getText().equals("no")){
dogCounter+= 5;
}
}
});
}
}
I think you just need to change your processCutest call so that it goes inside the onClick method, but before the toast.makeText call. Like this:
showResultButton= (Button)findViewById(R.id.showResults);
showResultButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processCutest(cutestCheckBoxDog, cutestCheckBoxCat, cutestCheckBoxParrot);
Toast.makeText(getApplicationContext(),catCounter + " " + dogCounter, Toast.LENGTH_LONG).show();
I'm assuming that the actual checkboxes are defined elsewhere. Are your checkboxes showing up? If so you might want to put the processDrool and processCanine calls right there as well.

Trying to process different scenarios in Service

I am having a problem and I ran out of ideas how to fix it.
The goal is, when the user clicks the button an URL is loaded depending on what's selected in settings.
Problem is, I am having trouble setting it up in a right way.
Logically(to me), I tried to set it up in a service. Button is clicked > Service starts > URL is loaded from "IF ELSE".
Problem is, I get an error in "IF ELSE" - "Method length must be called from the UI Thread, currently inferred thread is is worker.
public static class Service extends IntentService {
public Service() {
super("wallpaperchanger-download");
}
#Override
protected void onHandleIntent(Intent intent) {
MainActivity mainActivity;
mainActivity = new MainActivity();
if (mainActivity.mEditTextHashtag.length() > 2) {
WallpaperManager wm = WallpaperManager.getInstance(this);
int height = wm.getDesiredMinimumHeight();
int width = wm.getDesiredMinimumWidth();
String url = "https://source.unsplash.com/all/?" + mainActivity.mEditTextHashtag.getText() + "/" + width + "x" + height + "/";
try {
InputStream input = new URL(url).openStream();
Log.v(TAG, url);
wm.setStream(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
loading = false;
}
}
}
Ok, fair enough.
I created new Method getPhoto(); in UI Thread and put the code in there. Then, I called mainActivity.getPhoto(); in Service.
Problem is, I get an error - "Attempt to invoke virtual method 'int android.widget.EditText.length()' on a null object reference"
Any ideas on what I should do?
Full code in all its glory:
package com.edip.splashwallpaper;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.io.InputStream;
import java.net.URL;
public class MainActivity extends android.app.Activity {
final static String TAG = "AllInOne";
final static int CHANGE_INTERVAL = 30 * 1000; //30 sec for testing
static boolean loading = false;
WallpaperManager wm;
//Layout Views
Switch mSwitchFixedPhoto, mSwitchControls, mSwitchSave, mSwitchPause;
Spinner mSpinnerCategories, mSpinnerInterval;
EditText mEditTextHashtag;
Button mWallpaperButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Layout Views Initialized
mSwitchFixedPhoto = (Switch) findViewById(R.id.sw_fixedphoto);
mSwitchControls = (Switch) findViewById(R.id.switch_controls);
mSwitchSave = (Switch) findViewById(R.id.switch_save);
mSwitchPause = (Switch) findViewById(R.id.switch_pause);
mSpinnerCategories = (Spinner) findViewById(R.id.spinner_categories);
mSpinnerInterval = (Spinner) findViewById(R.id.spinner_interval);
mEditTextHashtag = (EditText) findViewById(R.id.et_hashtag);
mWallpaperButton = (Button) findViewById(R.id.btn_set_wallpaper);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterCategory = ArrayAdapter.createFromResource(this,
R.array.categories_array, R.layout.dialog_spinner_layout);
// Specify the layout to use when the list of choices appears
adapterCategory.setDropDownViewResource(R.layout.dialog_spinner_layout);
// Apply the adapter to the spinner
mSpinnerCategories.setAdapter(adapterCategory);
ArrayAdapter<CharSequence> adapterInterval = ArrayAdapter.createFromResource(this,
R.array.interval_array, R.layout.dialog_spinner_layout);
adapterInterval.setDropDownViewResource(R.layout.dialog_spinner_layout);
mSpinnerInterval.setAdapter(adapterInterval);
mWallpaperButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PendingIntent pending = PendingIntent.getBroadcast(MainActivity.this,
666, new Intent("com.edip.splashwallpaper.CHANGE_WALLPAPTER_TIMER"),
PendingIntent.FLAG_CANCEL_CURRENT);
((AlarmManager) getSystemService(Context.ALARM_SERVICE))
.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
CHANGE_INTERVAL, pending);
}
});
}
public void getPhoto() {
if (mEditTextHashtag.length() > 2) {
wm = WallpaperManager.getInstance(this);
int height = wm.getDesiredMinimumHeight();
int width = wm.getDesiredMinimumWidth();
String url = "https://source.unsplash.com/all/?" + mEditTextHashtag.getText() + "/" + width + "x" + height + "/";
try {
InputStream input = new URL(url).openStream();
Log.v(TAG, url);
wm.setStream(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
loading = false;
} else {
Toast.makeText(this, "Something else", Toast.LENGTH_SHORT).show();
}
}
public static class Service extends IntentService {
public Service() {
super("wallpaperchanger-download");
}
#Override
protected void onHandleIntent(Intent intent) {
MainActivity mainActivity;
mainActivity = new MainActivity();
mainActivity.getPhoto();
}
}
public static class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if (!loading) {
loading = true;
context.startService(new Intent(context, Service.class));
}
}
}
}
Thanks :)
First of all, you should never instantiate an activity by yourself.
Second, as a best practice, your service shouldn't know about your activity, or that it has an edit text. Instead you should send the URL to load inside your intent, when the PendingIntent is created, like this :
Intent intent = new Intent("com.edip.splashwallpaper.CHANGE_WALLPAPTER_TIMER");
intent.putExtra("USER_URL", "https://source.unsplash.com/all/?" + mEditTextHashtag.getText() + "/" + width + "x" + height + "/");
PendingIntent pending = PendingIntent.getBroadcast(MainActivity.this,
666, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Then within your service, read the url like so :
#Override
protected void onHandleIntent(Intent intent) {
String url = intent.getStringExtra("USER_URL");
// ...
}

Output every minute for ten minutes

I am trying to print something out for an android app every minute for ten minutes. I would preferably like to access the phone's clock to have the code start automatically at a specific time. However, I am not exactly sure how to do that part. Here is what I have so far.
So here is my main code I want to add the code below in along with the answer provided below:
package com.example.james.texttospeech;
import android.os.Bundle;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
//TTS object
private TextToSpeech myTTS;
//status check code
private int MY_DATA_CHECK_CODE = 0;
//create the Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get a reference to the button element listed in the XML layout
Button speakButton = (Button)findViewById(R.id.speak);
Button speakButton1 = (Button)findViewById(R.id.button);
Button speakButton2 = (Button)findViewById(R.id.button2);
//listen for clicks
speakButton.setOnClickListener(this);
speakButton1.setOnClickListener(this);
speakButton2.setOnClickListener(this);
//check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
//respond to button clicks
public void onClick(View v) {
//get the text entered
EditText enteredText = (EditText)findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
}
//speak the user text
private void speakWords(String speech) {
//speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
//act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
}
else {
//no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
//setup TTS
public void onInit(int initStatus) {
//check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
}
else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
}
}
}
import java.util.*;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class ClassExecutingTask {
long delay = 10 * 60000; // delay in milliseconds
LoopTask task = new LoopTask();
Timer timer = new Timer("TaskName");
public void start() {
timer.cancel();
timer = new Timer("TaskName");
Date executionDate = new Date(); // no params = now
timer.scheduleAtFixedRate(task, executionDate, delay);
}
private class LoopTask extends TimerTask {
public void run() {
while (delay > 0) {
System.out.println("Formation will form up in " + delay + " minutes");
delay--;
}
}
}
public static void main(String[] args) {
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
}
<!---->
public void run() {
while (delay > 0) {
System.out.println("Formation will form up in " + delay + " minutes");
delay--;
}
}
<!---->
public static void main(String[] args) {
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
If you want to do above thing in android then following code will help you add those lines in your onCreate()method
new CountDownTimer(600000, 60000) {//CountDownTimer(edittext1.getText()+edittext2.getText()) also parse it to long
public void onTick(long millisUntilFinished) {
System.out.println("Your message on every minute");
//here you can have your logic to set text to edittext
}
public void onFinish() {
System.out.println("Your message after 10 minute");
}
}
.start();

Categories

Resources