Java code to show action on x amount of presses? - java

I have an iOS app that I worked on some time ago, and the function it uses I like, and would like to somehow get it to work on some Android code I have.
At the top of my MainActivity I have
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "nShownLobby";
on my onCreate I have
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
And I am calling this method
changeTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
long nb_shown_lobby = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getLong("nShownLobby", 0);
++nb_shown_lobby;
if ((nb_shown_lobby % 20) == 0) {
this.turnAround();
}
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}
});
The intention is that after every 20 presses, the turnAround() method is called but it does not... It just gets ignored - I am guessing I have missed something?

**According to your question your code should be like this**
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor editor;
private static final String MyPREFERENCES = "nShownLobby";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
changeTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
int nb_shown_lobby = sharedpreferences.getInt("nShownLobby", 0);
if ((nb_shown_lobby % 20) == 0) {
turnAround();
}
nb_shown_lobby += 1;
editor.putInt("nShownLobby", nb_shown_lobby);
editor.commit();
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
});
}
//created this in activity, not in the button onclick
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}

Related

Music plays only one time from server in online music player

I designed an online music player which streams file from my server and shows them in a recyclerView. when I click on the specific song it plays automatically, but when I go back to my recyclerview and I choose it again it doesn't play anymore and even duration of song becomes an insane number. I even tried to handle my media player onBackPressed() method or in OnRestart() or onResume() method. I'm confused. Please let me know about any suggestion.
Here's my code for player:
public class PlayerActivity extends AppCompatActivity implements View.OnClickListener {
private CircularMusicProgressBar cover;
private ImageButton playPause, rewind, forward, repeat, fav, download;
private TextView title, term, spendingTime, totalTime, emptyRec;
private Context context;
public static MediaPlayer mediaPlayer;
int i;
private Timer timer;
private Bundle extra;
Uri uri;
RecyclerView recyclerView;
RequestQueue requestQueue;
SuggestionAdapter suggestionAdapter;
LinearLayoutManager layoutManager;
List<Listening> list = new ArrayList<>();
String url = "https://www.learnhere.ir/listening.php";
AccessDataOnServer suggestionData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
initFields();
playOnStart();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play_pause:
if (i == 1) {
i = 2;
playPause.setImageResource(R.drawable.ic_baseline_play);
mediaPlayer.pause();
} else {
i = 1;
playPause.setImageResource(R.drawable.ic_baseline_pause);
int b = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(b);
mediaPlayer.start();
}
break;
case R.id.rewind:
Toast.makeText(context, "rewind", Toast.LENGTH_SHORT).show();
break;
case R.id.forward:
Toast.makeText(context, "forward", Toast.LENGTH_SHORT).show();
break;
case R.id.repeat:
Toast.makeText(context, "repeat", Toast.LENGTH_SHORT).show();
break;
case R.id.fav:
Toast.makeText(context, "fav", Toast.LENGTH_SHORT).show();
break;
case R.id.download:
Toast.makeText(context, "download", Toast.LENGTH_SHORT).show();
break;
}
}
public void initFields() {
i = 0;
context = this;
cover = findViewById(R.id.cover_progress);
playPause = findViewById(R.id.play_pause);
rewind = findViewById(R.id.rewind);
forward = findViewById(R.id.forward);
repeat = findViewById(R.id.repeat);
fav = findViewById(R.id.fav);
download = findViewById(R.id.download);
title = findViewById(R.id.title_tv);
term = findViewById(R.id.term_tv);
emptyRec = findViewById(R.id.empty_rec);
spendingTime = findViewById(R.id.spending_time);
totalTime = findViewById(R.id.total_time);
playPause.setOnClickListener(this);
rewind.setOnClickListener(this);
forward.setOnClickListener(this);
repeat.setOnClickListener(this);
fav.setOnClickListener(this);
download.setOnClickListener(this);
extra = getIntent().getExtras();
Picasso.get().load(extra.getString("cover")).into(cover);
title.setText(extra.getString("title"));
term.setText(extra.getString("term"));
timer = new Timer();
uri = Uri.parse(extra.getString("link"));
recyclerView = findViewById(R.id.suggestion_recycler);
requestQueue = Volley.newRequestQueue(context);
layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
suggestionAdapter = new SuggestionAdapter(list, context);
suggestionData = new AccessDataOnServer();
recyclerView.setAdapter(suggestionAdapter);
recyclerView.setLayoutManager(layoutManager);
suggestionData.getSuggestion(context, list, recyclerView, url, requestQueue);
if (list.size() <= 1) {
emptyRec.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
emptyRec.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
public void play() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes
.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build());
mediaPlayer.setDataSource(context, uri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getTime();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
thread.start();
}
public void playOnStart() {
Toast.makeText(context, "Please wait until the audio plays...", Toast.LENGTH_SHORT).show();
play();
i = 1;
playPause.setImageResource(R.drawable.ic_baseline_pause);
}
public String millisecondToSecond(long millisecond) {
String finalTimerString = "";
String secondString = "";
String minuteString = "";
//convert total duration into time
int hour = (int) (millisecond / (1000 * 60 * 60));
int minute = (int) (millisecond % (1000 * 60 * 60) / (1000 * 60));
int second = (int) (millisecond % (1000 * 60 * 60) % (1000 * 60) / 1000);
//Add hours if there
if (hour > 0) {
finalTimerString = hour + ":";
}
//Prepending 0 to second if it's one digit
if (second < 10) {
secondString = "0" + second;
} else {
secondString = "" + second;
}
//Prepending 0 to minute if it's one digit
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = "" + minute;
}
finalTimerString = finalTimerString + minuteString + ":" + secondString;
//Return timer string
return finalTimerString;
}
public void getTime() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Without runOnUiThread we don't have access to modifiers like text view
runOnUiThread(new Runnable() {
#Override
public void run() {
long current = mediaPlayer.getCurrentPosition();
int i = (mediaPlayer.getCurrentPosition() * 100) / mediaPlayer.getDuration();
spendingTime.setText("" + millisecondToSecond(current));
cover.setValue(i);
int duration = mediaPlayer.getDuration();
String time = String.format(Locale.US, "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(duration),
TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
totalTime.setText(time);
}
});
}
}, 0, 1000);
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
finish();
}
#Override
protected void onRestart() {
super.onRestart();
playOnStart();
}
Well I reviewed your codes and it seems you aren't using Media player class properly.
I made a few changes to each block of your codes. I hope it solves your problem.
First of all change the following scope:
public static MediaPlayer mediaPlayer;
To
MediaPlayer mediaPlayer = new MediaPlayer();
I made a method for your mediaPlayer and you should use it in your onCreate() :
private void prepareMediaPlayer() {
try {
mediaPlayer.setDataSource(context, uri);
mediaPlayer.prepare();
updateSeekBarTimer();
} catch (Exception e) {
e.printStackTrace();
}
}
A method to update your seekbar :
private void updateSeekBarTimer() {
try {
if (mediaPlayer.isPlaying()) {
total_time = mediaPlayer.getDuration();
current_time = mediaPlayer.getCurrentPosition();
totalTime.setText("" + utils.milliSecondsToTimer(total_time));
spendingTime.setText("" + utils.milliSecondsToTimer(current_time));
int progress = (int) (utils.getProgressPercentage(current_time, total_time));
seekBar.setProgress(progress);
Runnable runnable = new Runnable() {
#Override
public void run() {
updateSeekBarTimer();
}
};
handler.postDelayed(runnable, 1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
And finally you need an Interface to decide what happens when your track ends:
public class PlayerActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener
#Override
public void onCompletion(MediaPlayer mp) {
handler.removeCallbacks(null);
playPause.setImageResource(R.drawable.ic_baseline_play);
if (rep) {
mediaPlayer.start();
playPause.setImageResource(R.drawable.ic_baseline_pause);
updateSeekBarTimer();
} else {
seekBar.setProgress(0);
totalTime.setText(R.string.zero_time);
spendingTime.setText(R.string.zero_time);
playPause.setImageResource(R.drawable.ic_baseline_play);
mediaPlayer.reset();
prepareMediaPlayer();
}
}

Monitoring Voice in my android app

Iam making an android app which monitor voice in which when the voice loudness exceed a user defined threshold the app dial a specific number .
i done making voice monitoring and compared the highest value with the threshold then dialling the number .everything goes right except when the app returned after the call i find the monitoring isnt right , as the mic sensitivity is very week (measurement is very low ) i have to restart the app to obtain the right measurement , the second question here i make the comparison of the threshold and the last value of sound in the handler at the bottom , is this the right way ? thanks in advanceThis is the App image
Below is The Main activity
public class MainActivity extends AppCompatActivity {
private static final int sampleRate = 11025;
private static final int bufferSizeFactor = 10;
private Button Stop;
private ProgressBar On;
private Button Start;
private AudioRecord audio;
private int bufferSize;
private ProgressBar level;
private TextView textView;
volatile int threshold;
TextView testtextview;
private boolean clicked ;
private Handler handler = new Handler();
private int lastLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threshold = 20000;
//progressbar detect voice
level = (ProgressBar) findViewById(R.id.progressbar_level);
level.setMax(32676);
//text displaying progress par value
textView = (TextView) findViewById(R.id.textView1);
testtextview = (TextView) findViewById(R.id.textViewtest);
if (audio != null) {
audio.stop();
audio.release();
audio = null;
handler.removeCallbacks(update);
} else {
bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT) * bufferSizeFactor;
audio = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
audio.startRecording();
Thread thread = new Thread(new Runnable() {
public void run() {
readAudioBuffer();
}
});
thread.setPriority(Thread.currentThread().getThreadGroup().getMaxPriority());
thread.start();
handler.removeCallbacks(update);
handler.postDelayed(update, 25);
}
//seekbar let user choose threshhold
SeekBar mSeekBar = (SeekBar) findViewById(R.id.seekBar);
//text displayin user choice
final TextView textViewuser = (TextView) findViewById(R.id.textView3);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textViewuser.setText("" + i + "/32676");
threshold = i ;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Stop = (Button) findViewById(R.id.dummy_buttonstop);
On = (ProgressBar) findViewById(R.id.progressBar11);
Start = (Button) findViewById(R.id.dummy_button);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Start.setVisibility(View.GONE);
On.setVisibility(View.VISIBLE);
clicked = true;
}
});
Stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
clicked = false;
}
});
}
private void readAudioBuffer() {
try {
short[] buffer = new short[bufferSize];
int bufferReadResult;
do {
bufferReadResult = audio.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferReadResult; i++) {
if (buffer[i] > lastLevel) {
lastLevel = buffer[i];
}
}
}
while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);
if (audio != null) {
audio.release();
audio = null;
handler.removeCallbacks(update);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Runnable update = new Runnable() {
public void run() {
MainActivity.this.level.setProgress(lastLevel);
textView.setText(lastLevel + "/" + level.getMax());
if (clicked) {
if (lastLevel > threshold) {
clicked=false;
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
String url = "tel:01224271138";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//recreate();
}
}
lastLevel *= .5;
handler.postAtTime(this, SystemClock.uptimeMillis() + 500);
}
};

App crashing when using SharedPreferences to carry over final score

My android app is crashing when using SharedPreferences to try and carry the final score over from when the game ends. The app crashes inside the onTouchEvent at the line.
SharedPreferences.Editor editor = mySharedPreferences.edit();
The idea is when the game ends it final score that is within the SVGameView to carry over into the SVGameOver class and display there. If anyone could give some advice that would be great!
SVGameView:
public class SVGameView extends SurfaceView implements Runnable {
private SurfaceHolder holder;
Thread thread = null;
volatile boolean running = false;
static final long FPS = 30;
private Sprite sprite;
private long lastClick;
private Bitmap ball, gameOver;
//private int x = 200, y = 200;
private int scorePosX = 100;
private int scorePosY = 100;
private int countScore = 0;
private int life = 1;
SharedPreferences mySharedPreferences;
public SVGameView(Context context) {
super(context);
thread = new Thread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
running = false;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
running = true;
thread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball2);
gameOver = BitmapFactory.decodeResource(getResources(),R.drawable.endscreen);
sprite = new Sprite(this, ball);
context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
}
#Override
public void run() {
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = getHolder().lockCanvas();
synchronized (getHolder()) {
update();
onDraw(c);
}
} finally {
if (c != null) {
getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
thread.sleep(sleepTime);
else
thread.sleep(10);
} catch (Exception e) {}
}
}
private void update(){
sprite.update();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
Paint paint = new Paint();
canvas.drawPaint(paint);
paint.setColor(Color.WHITE);
paint.setTextSize(48);
canvas.drawText("Score: " + countScore, scorePosX, scorePosY, paint);
canvas.drawText("Lives: " + life, 500, 100, paint);
sprite.onDraw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(System.currentTimeMillis()-lastClick > 300){
lastClick = System.currentTimeMillis();
}
synchronized (getHolder()){
if(sprite.isHit(event.getX(), event.getY())){
countScore += 1;
sprite.increase();
}else{
life --;
}
}
if(life == 0) {
getContext().startActivity(new Intent(getContext(), SVGameOver.class));
//Intent intent;
//intent = new Intent(getContext(), SVGameView.class);
//intent.putExtra("scoreOutput", countScore);
//Crashes Here
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("cScore", String.valueOf(countScore));
}
return super.onTouchEvent(event);
}
}
SVGameOver Class:
public class SVGameOver extends Activity implements View.OnClickListener{
Button btnBack;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(this);
SharedPreferences mySharedPreferences = getSharedPreferences("myPrefsFile", 0);
String theScore = mySharedPreferences.getString("cScore","");
TextView textView = (TextView)findViewById(R.id.scoreOutput);
textView.setText(theScore);
//intent = getIntent();
//String uir = intent.getStringExtra("scoreOutput");
}
#Override
public void onClick(View v) {
}
}
XML Layout:
https://gyazo.com/8e49d02c66dde7ff0e7f09a4fa9eacd2
You're missing:
mySharedPreferences = context.getSharedPreferences("myPrefsFile", Context.MODE_PRIVATE);
in your SVGameView, so mySharedPreferences always null.
You missed assigning SharedPreferencesobject to your reference mySharedPreferences in SVGameView(Context context) -
context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
Change it to
mySharedPreferences = context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
You are not initializing the SharedPreference object right.
Use this library, which simplifies the use of SharedPreferences and will make life simpler for you.
Android-SharedPreferences-Helper simplifies usage of the default Android SharedPreferences Class. The developer can do in a few lines
of code which otherwise would have required several. Simple to
understand as compared to the default class and easy to use.

Application always calls onCreate() when the phone is locked and unlocked

Is there any way to save the state of the application because the application calls onCreate() everytime the android phone is locked. When I unlocked it, the app calls the onCreate() method and start again.. BTW my app is like text twist. When I unlock the screen a new word is shown, instead of the current one.. The score is also reset as well as the time.. How can I work on this? Please help.. It's still unanswered..
This is the whole code of my activity..
public class friend extends Activity {
//score
ScoreHandler scHandler;
Score sc;
int totalScore;
//words
//DatabaseHelper dbHelp;
DBHelper dbHelp;
public String randomWord;
//speech
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
//shake
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
//timer
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private TextView timeText;
private final long startTime = 180 * 1000;
private final long interval = 1 * 1000;
private long timeLeft;
private int gameScore;
private TextView shuffleView;
TextView scoreView;
//Animation
Animation myFadeInAnimation;
Animation myFadeOutAnimation;
Animation leftToRight;
//sliding
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
Context context;
static final String STATE_SCORE = "currentScore";
static final String STATE_WORD = "currentWord";
static final String STATE_TIME = "currentTime";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
} else {
// Probably initialize members with default values for a new instance
}
setContentView(R.layout.friend);
leftToRight = AnimationUtils.loadAnimation(this, R.anim.left_to_right);
ImageButton next = (ImageButton) findViewById(R.id.nextround_game);
next.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, friend1.class);
startActivity(intent);
}
});
ImageButton giveUp = (ImageButton) findViewById(R.id.surrender_game);
giveUp.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, GameOverActivity.class);
startActivity(intent);
}
});
//score
//timer
timeText = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
timeText.setText(timeText.getText() + String.valueOf(startTime/1000));
countDownTimer.start();
timerHasStarted = true;
this.removeAll();
dbHelp = new DBHelper(this);
randomWord = dbHelp.random();
System.out.println(randomWord);
String wordCaps = randomWord.toUpperCase();
final String finalWord = shuffle(wordCaps);
shuffleView = (TextView) findViewById(R.id.jumble);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/American Captain.ttf");
shuffleView.setTypeface(type);
shuffleView.setText(finalWord);
//shake
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
//String str = (String) stringList.remove(selectedWord);
String wordOutput = shuffle(finalWord);
TextView tv = (TextView) findViewById(R.id.jumble);
tv.setText(wordOutput);
}
});
//speech
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timeText.setText("0:00");
playSound(R.raw.clock_whistle);
ImageView timeIsUp = (ImageView) findViewById(R.id.time_is_up);
timeIsUp.startAnimation(leftToRight);
}
#Override
public void onTick(long millisUntilFinished) {
long minutes = (millisUntilFinished / (1000*60)) % 60;
long seconds = (millisUntilFinished / 1000) % 60 ;
timeLeft = millisUntilFinished/1000;
timeText.setText("" + minutes + ":" + seconds );
if (timeLeft <= 10) {
playSound(R.raw.clock_beep);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
System.out.println(""+text.get(0));
String spoken = text.get(0);
if(dbHelp.exists(spoken)){
if(dbHelp.isLongest(spoken)){
Toast.makeText(getApplicationContext(), "You have guessed the longest word! ", Toast.LENGTH_SHORT).show();
}
gameScore = text.get(0).length()*10;
scoreView = (TextView) findViewById(R.id.scoreView);
scoreView.setText(""+gameScore);
scHandler = new ScoreHandler(this);
scHandler.addScore(new Score(1,gameScore));
int cumulativeScore = scHandler.accumulateScores();
scoreView.setText(""+cumulativeScore);
playSound(R.raw.correct);
WordGuessedHandler guessedWord = new WordGuessedHandler(this);
guessedWord.addGuessedWord(new Words(1,spoken));
ImageView img = (ImageView) findViewById(R.id.awesome);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
img.startAnimation(myFadeInAnimation);
img.startAnimation(myFadeOutAnimation);
}else{
playSound(R.raw.poweng);
ImageView image = (ImageView) findViewById(R.id.wrong);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
image.startAnimation(myFadeInAnimation);
image.startAnimation(myFadeOutAnimation);
}
}
}
}
}
public String shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
System.out.println(output.toString());
return output.toString();
}
#Override
public void onBackPressed()
{
Intent inMain=new Intent(friend.this, MainActivity.class);
inMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inMain);
countDownTimer.cancel();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE,gameScore);
savedInstanceState.putLong(STATE_TIME,timeLeft);
savedInstanceState.putString(STATE_TIME,randomWord);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
}
//sliding menu onChange
#Override
public void onContentChanged()
{
super.onContentChanged();
mOpenButton = (Button) findViewById( R.id.button_open );
mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer);
/* GridView gridView;
ArrayList ArrayofName = new ArrayList();
WordHandler db = new WordHandler(this);*/
TextView txt = (TextView) findViewById(R.id.text);
txt.setText("Hello There!");
GridView gridview = (GridView) findViewById(R.id.gridView1);
WordGuessedHandler guessed = new WordGuessedHandler(this);
List <WordGuessed> guessedList = guessed.getAllWordGuessed();
List<String> wordsList = new ArrayList<String>();
for(WordGuessed wg:guessedList){
wordsList.add(wg.getWord());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, wordsList);
gridview.setAdapter(adapter);
}
public void playSound(int sound) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.setLooping(false);
mp.setVolume(1,1);
mp.start();
}
public void removeAll()
{
ScoreHandler scHandler = new ScoreHandler(this);
// db.delete(String tableName, String whereClause, String[] whereArgs);
// If whereClause is null, it will delete all rows.
SQLiteDatabase db = scHandler.getWritableDatabase(); // helper is object extends SQLiteOpenHelper
db.delete("scores_table", null, null);
db.close();
}
}
This question answers your question.
https://developer.android.com/training/basics/activity-lifecycle/index.html
Please use the onPause() and onResume() methods in your main Activity to solve this problem. If both method aren't defined, your app will go to the next methods in the lifecycle, which will be onCreate() and other methods. Read more here.
It is also possible to save your current instance by using onSaveInstance(Bundle b) and onRestoreInstance(Bundle b)
PS: someone has asked it earlier, and wrote a small example to use the onSaveInstance and onRestoreInstance (if you want to use it) here.

app rater not working correctly for me

can someone check this app rater code and tell me how can I have it dismiss on a customer request but not come right back after customer presses same back button at least give them 5 tries before all the conditions are met, thank you
public class AppRater {
private final static String APP_TITLE = "name";
private final static String APP_PNAME = "com.code.code";
private final static int DAYS_UNTIL_PROMPT = 1;
private final static int LAUNCHES_UNTIL_PROMPT = 1;
public static void app_launched(Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
if (prefs.getBoolean("dontshowagain", false)) { return ; }
SharedPreferences.Editor editor = prefs.edit();
// Increment launch counter
long launch_count = prefs.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
// Get date of first launch
Long date_firstLaunch = prefs.getLong("date_firstlaunch", 1);
if (date_firstLaunch == 1) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong("date_firstlaunch", date_firstLaunch);
}
// Wait at least n days before opening
if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= date_firstLaunch +
(DAYS_UNTIL_PROMPT * 0 * 24 * 60 * 1000)) {
showRateDialog(mContext, editor);
}
}
editor.commit();
}
public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle("Rate " + APP_TITLE);
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(mContext);
tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
tv.setWidth(600);
tv.setPadding(24, 0, 24, 60);
ll.addView(tv);
Button b1 = new Button(mContext);
b1.setText("Rate " + APP_TITLE);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
dialog.dismiss();
}
});
ll.addView(b1);
Button b2 = new Button(mContext);
b2.setText("Remind me later");
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
ll.addView(b2);
Button b3 = new Button(mContext);
b3.setText("No, thanks");
b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (editor != null) {
editor.putBoolean("dontshowagain", true);
editor.commit();
}
dialog.dismiss();
}
});
ll.addView(b3);
dialog.setContentView(ll);
dialog.show();
}
}
There is something strange here
DAYS_UNTIL_PROMPT * 0 * 24 * 60 * 1000
shouldn't be ?
DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000
You can also use DialogBuilder button options instead creating button manually.
Here is an example :
builder.setPositiveButton(R.string.rate_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNegativeButton(R.string.rate_dialog_never, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNeutralButton(R.string.rate_dialog_later, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});

Categories