Previous button and next button - java

I have <> and <> buttons in my quiz app, but if the user is in the first question since there is no previous question there should be toast which says "this is the first question" and the same with <>button.
Here is my code for buttons (which is incorrect):
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex=0;
if (mCurreentIndex>mQuestionBank.length){
Toast.makeText(QuizActivity.this,R.string.last_question,Toast.LENGTH_LONG).show();
}
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex--;
if (mCurreentIndex<mQuestionBank.length){
Toast.makeText(QuizActivity.this, R.string.first_question,Toast.LENGTH_LONG).show();
}
updateQuestion();
}
});

mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mCurreentIndex=0;// not valid
if (mCurreentIndex>=mQuestionBank.length){
Toast.makeText(QuizActivity.this,getString(R.string.last_question),Toast.LENGTH_LONG).show();
return;
}
mCurreentIndex++;
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurreentIndex<=0){
Toast.makeText(QuizActivity.this, getString(R.string.first_question),Toast.LENGTH_LONG).show();
return;
}
mCurreentIndex--;
updateQuestion();
}
});

Try this
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurreentIndex<=0){
Toast.makeText(QuizActivity.this, R.string.first_question,Toast.LENGTH_LONG).show();
}else{
mCurreentIndex--;
updateQuestion();
}
}
});
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurreentIndex>=mQuestionBank.length){
Toast.makeText(QuizActivity.this,getString(R.string.last_question),Toast.LENGTH_LONG).show();
}else{
mCurreentIndex++;
updateQuestion();
}
}
});

You have just display toast message but next statement also execute after displaying toast. For your solution you need to use "return" or if..else block.
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex=0;
if (mCurreentIndex>mQuestionBank.length){
Toast.makeText(QuizActivity.this,R.string.last_question,Toast.LENGTH_LONG).show();
return;
}
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex--;
if (mCurreentIndex<mQuestionBank.length){
Toast.makeText(QuizActivity.this, R.string.first_question,Toast.LENGTH_LONG).show();
return;
}
updateQuestion();
}
});

//Previous Button Condition;
mCurreentIndex--;
if (mCurreentIndex<mQuestionBank.length && mCurreentIndex>=0){
Toast.makeText(QuizActivity.this, R.string.first_question,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(QuizActivity.this, "This is first question",Toast.LENGTH_LONG).show();
mCurreentIndex++;
}
//Next Button Condition;
mCurreentIndex++;
if (mCurreentIndex<mQuestionBank.length){
Toast.makeText(QuizActivity.this,R.string.last_question,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(QuizActivity.this, "This is last Question",Toast.LENGTH_LONG).show();
mCurreentIndex--;
}

public class QuizActivity extends AppCompatActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mPreviousButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[]{
new Question(R.string.question_australia, true),
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true),
};
private int mCurreentIndex = 0;
private boolean[] QuestionsAnswered = new boolean[mQuestionBank.length];
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if (savedInstanceState != null) {
mCurreentIndex =savedInstanceState.getInt(KEY_INDEX, 0);
QuestionsAnswered = savedInstanceState.getBooleanArray(KEY_INDEX);
}
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex = (mCurreentIndex+mQuestionBank.length +1) % mQuestionBank.length;
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex= (mCurreentIndex+ mQuestionBank.length - 1) % mQuestionBank.length;
updateQuestion();
}
});
updateQuestion();
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX,mCurreentIndex);
savedInstanceState.putBooleanArray(KEY_INDEX,QuestionsAnswered);
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
private void updateQuestion(){
int question = mQuestionBank[mCurreentIndex].getTextResId();
mQuestionTextView.setText(question);
mTrueButton.setEnabled(!QuestionsAnswered[mCurreentIndex]);
mFalseButton.setEnabled(!QuestionsAnswered[mCurreentIndex]);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurreentIndex].isAnswerTrue();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show();
QuestionsAnswered[mCurreentIndex] = true;
mTrueButton.setEnabled(false);
mFalseButton.setEnabled(false);
}
}

Related

On going back to the previous Activity my media progress get lost (seekBar and media player progress)

Actually i have 2 activities , in the main activity i am displaying all the songs using recycler view and setup an onClickListner on it, and when someone taps on it , it launches a new activity(MediaPlayer Activity) and start playing the song along with media controls like (paly, pause and seekBar).
But when i get back to the main activity and click on a button (which basically takes to the MediaPlayer activity again) all the mediaPlayer and seekBar progress are gone also the (play, pause, next and previous buttons) are not responding to the clicks.
This is from where i am starting the MediaPlayer activity :
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.Song.setText(mData.get(position).title);
holder.Artist.setText(mData.get(position).artist);
Glide.with(mcontext).load(mData.get(position).imagePath).
placeholder(R.drawable.unknown_art).into(holder.PhotoId);
holder.Options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mcontext, "You clicked on options", Toast.LENGTH_SHORT).show();
}
});
holder.RL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mcontext, MediaPlayerActivity.class);
intent.putExtra("songPosition",position);
mcontext.startActivity(intent);
}
});
These are the codes in the MediaPlayerActivity :
public class MediaPlayerActivity extends AppCompatActivity {
static MediaPlayer mediaPlayer=null;
static int pos=0;
SeekBar seekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent intent = getIntent();
pos = intent.getIntExtra("songPosition",pos);
seekBar = (SeekBar)findViewById(R.id.seekBar);
Button next = (Button)findViewById(R.id.button_1);
Button previous = (Button)findViewById(R.id.button_2);
final Button play_pause = (Button)findViewById(R.id.button_3);
final TextView info = (TextView)findViewById(R.id.songInfo);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
playMedia(pos);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playMedia(++pos);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this,"Already the last song!!!",Toast.LENGTH_SHORT).show();
}
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playMedia(--pos);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this,"Already the first song!!!",Toast.LENGTH_SHORT).show();
}
}
});
play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
play_pause.setText(R.string.mp_play);
mediaPlayer.pause();
}
else{
play_pause.setText(R.string.mp_Pause);
mediaPlayer.start();
}
}
});
}
public void playMedia(int pos){
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(VerticalRecyclerViewAdapter.mData.get(pos).songPath);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
mediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
setSeekbarProgress();
onSeekbarChange();
playNext();
}
public void playNext(){
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
mediaPlayer.release();
playMedia(++MediaPlayerActivity.pos);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this, "Already the last song", Toast.LENGTH_SHORT).show();
}
}
});
}
public void setSeekbarProgress(){
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
if (mediaPlayer != null) {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
}
catch (RuntimeException e){
Log.i("CRASH",""+e.getMessage());
}
}
},0,1000);
}
public void onSeekbarChange(){
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(b) {
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
And this is where from i wanted to go back to the MediaPlayer Activity (on button click ) :
mFloatingToolbar.setClickListener(new FloatingToolbar.ItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.music:
Intent intent = new Intent(getActivity(),MediaPlayerActivity.class);
startActivity(intent);
break;
case R.id.pause :
break;
case R.id.next :
Toast.makeText(getContext(), "Next", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getContext(), "Back", Toast.LENGTH_SHORT).show();
verticalRecyclerViewAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onItemLongClick(MenuItem item) {
}
});

cannot apply String values in a Text View array

in if(saveInstanceState != null) I am trying to save the changes of the text in Text Views that happened by whoWon() method to save it in while user rotate the phone and get it back as it was before rotation but it shows me an error that says getText() in TextView cannot be applied to (java.lang.string) , I tried to add .toString() but it didn't work.
public class Multiplayer extends AppCompatActivity {
private TextView mTicTacTextViews [] = new TextView[9];
private Button mButtonX;
private Button mButtonO;
private Button mResult;
private int mcheckAllButtonsClicked =0;
private String TEXT_VIEW_VALUES_KEY = "VALUES OF TEXT VIEW'S";
private String mTextviewValues [] = new String[9];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null)
{
String values[]=savedInstanceState.getStringArray(TEXT_VIEW_VALUES_KEY);
for (int i=0;i<values.length;i++ ) {
mTextviewValues[i]=values[i];
mTicTacTextViews[i].getText(mTextviewValues[i]);
}
}
setContentView(R.layout.activity_tic_tac);
mTicTacTextViews[0] = (TextView) findViewById(R.id.tic_tac_one);
mTicTacTextViews[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[0]);
ifPressed_OButton(mTicTacTextViews[0]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[1] = (TextView) findViewById(R.id.tic_tac_two);
mTicTacTextViews[1].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[1]);
ifPressed_OButton(mTicTacTextViews[1]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[2] = (TextView) findViewById(R.id.tic_tac_three);
mTicTacTextViews[2].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[2]);
ifPressed_OButton(mTicTacTextViews[2]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[3] = (TextView) findViewById(R.id.tic_tac_four);
mTicTacTextViews[3].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[3]);
ifPressed_OButton(mTicTacTextViews[3]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[4] = (TextView) findViewById(R.id.tic_tac_five);
mTicTacTextViews[4].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[4]);
ifPressed_OButton(mTicTacTextViews[4]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[5] = (TextView) findViewById(R.id.tic_tac_six);
mTicTacTextViews[5].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[5]);
ifPressed_OButton(mTicTacTextViews[5]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[6] = (TextView) findViewById(R.id.tic_tac_seven);
mTicTacTextViews[6].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[6]);
ifPressed_OButton(mTicTacTextViews[6]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[7] = (TextView) findViewById(R.id.tic_tac_eight);
mTicTacTextViews[7].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[7]);
ifPressed_OButton(mTicTacTextViews[7]);
mcheckAllButtonsClicked+=1;
}
});
mTicTacTextViews[8] = (TextView) findViewById(R.id.tic_tac_nine);
mTicTacTextViews[8].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ifPressed_XButton(mTicTacTextViews[8]);
ifPressed_OButton(mTicTacTextViews[8]);
mcheckAllButtonsClicked+=1;
}
});
mButtonX = (Button) findViewById(R.id.x_button);
mButtonX.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mUserPressed_XButton =true;
}
});
mButtonO = (Button) findViewById(R.id.o_button);
mButtonO.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mUserPressed_OButton =true;
}
});
mTextviewValues [0]=mTicTacTextViews[0].getText().toString();
mTextviewValues [1]=mTicTacTextViews[1].getText().toString();
mTextviewValues [2]=mTicTacTextViews[2].getText().toString();
mTextviewValues [3]=mTicTacTextViews[3].getText().toString();
mTextviewValues [4]=mTicTacTextViews[4].getText().toString();
mTextviewValues [5]=mTicTacTextViews[5].getText().toString();
mTextviewValues [6]=mTicTacTextViews[6].getText().toString();
mTextviewValues [7]=mTicTacTextViews[7].getText().toString();
mTextviewValues [8]=mTicTacTextViews[8].getText().toString();
mResult = (Button) findViewById(R.id.result_button);
mResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
whoWon();
}
});
}
private void whoWon ()
{
mTextviewValues [0]=mTicTacTextViews[0].getText().toString();
mTextviewValues [1]=mTicTacTextViews[1].getText().toString();
mTextviewValues [2]=mTicTacTextViews[2].getText().toString();
mTextviewValues [3]=mTicTacTextViews[3].getText().toString();
mTextviewValues [4]=mTicTacTextViews[4].getText().toString();
mTextviewValues [5]=mTicTacTextViews[5].getText().toString();
mTextviewValues [6]=mTicTacTextViews[6].getText().toString();
mTextviewValues [7]=mTicTacTextViews[7].getText().toString();
mTextviewValues [8]=mTicTacTextViews[8].getText().toString();
if(mTextviewValues[0].equals(mTextviewValues[1]) & mTextviewValues[1].equals(mTextviewValues[2]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[1].equals(mTextviewValues[4]) & mTextviewValues[4].equals(mTextviewValues[8]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[0].equals(mTextviewValues[3]) & mTextviewValues[3].equals(mTextviewValues[6]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[1].equals(mTextviewValues[4]) & mTextviewValues[4].equals(mTextviewValues[7]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[2].equals(mTextviewValues[5]) & mTextviewValues[5].equals(mTextviewValues[8]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[2].equals(mTextviewValues[4]) & mTextviewValues[4].equals(mTextviewValues[6]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[2].equals(mTextviewValues[4]) & mTextviewValues[4].equals(mTextviewValues[6]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else if (mTextviewValues[6].equals(mTextviewValues[7]) & mTextviewValues[7].equals(mTextviewValues[8]))
{
Toast.makeText(this,"Someone won",Toast.LENGTH_SHORT).show();
}
else Log.i("error" , "whowon didn't work");
}
#Override
protected void onSaveInstanceState(Bundle bundle)
{
super.onSaveInstanceState(bundle);
bundle.putStringArray(TEXT_VIEW_VALUES_KEY,mTextviewValues);
}
}
getText() doesn't take a parameter. mTicTacTextViews[i].getText() returns the text in the view. Are you trying to set the text in the view? If so, you want setText(CharSequence), not CharSequence getText().

Sound is stopping after a period of time

The code of the mediaplayer (which starts under the comment: //Code of the mediaplayer begins) is every time called when I click a button. After some time when I click the button, the sound is not played anymore.
It is like : I click for 10 times and it is returning the sound when I click again it stops and does not work anymore. Thanks for looking, If there is any solution comment below! :D
Logcat:
E/AudioFlinger: no more track names available
E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
E/AudioTrack: AudioFlinger could not create track, status: -12
E/AudioSink: Unable to create audio track
E/ExtendedNuPlayerDecoder: error in opening audio sink. Could be fatal!!!
**Code of the main activity'*:
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
CheckBox checkBoxmp;
private MediaPlayer mp, mp2;
SharedPreferences mypref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Dialog 1
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//end Dialog 1
//Dialog 2
createDialog2();
Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
dialogButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.show();
}
});
closeButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
}
});
//end Dialog 2
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
final SharedPreferences.Editor editor = mypref.edit();
checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
editor.putBoolean("playSounds", !isChecked);
editor.commit();
if (!isChecked){
mp.setVolume(1,1);
mp2.setVolume(1,1);
}else{
mp.setVolume(0,0);
mp2.setVolume(0,0);
}
}
})
;
final boolean playSounds = mypref.getBoolean("playSounds", false);
checkBoxmp.setChecked(!playSounds);
if(playSounds){
mp.setVolume(1,1);
mp2.setVolume(1,1);
}
else{
mp.setVolume(0,0);
mp2.setVolume(0,0);
}
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
final List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
//Code of the mediaplayer begins:
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp.release();
mp = null;
}
});
mp.start();
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
try {
mp2 = new MediaPlayer();
if (playSounds) {
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
mp2.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("wrong.mp3");
mp2.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp2.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp2.release();
mp2 = null;
}
});
mp2.start();
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
//End mediaplayer main code
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
private void createDialog2() {
dialog2 = new Dialog(this);
dialog2.setTitle("Settings");
dialog2.setContentView(R.layout.popup_menu1_2);
closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);
}
}
You are not releasing MediaPlayers. That could be the reason behind this issue. Without touching most of your logic, one way to do this is:
Make mp and mp2, private members of QuizActivity.
public class QuizActivity extends AppCompatActivity {
...
private MediaPlayer mp, mp2;
...
}
Create MediaPlayer whenever required, and release it when playback is done.
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
AssetFileDescriptor afd;
...
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp.release();
mp = null;
}
});
mp.start();
At other places, you will have to perform null checks as shown below, before accessing mp and mp2 to avoid NPE.
if (null != mp && null != mp2) {
if (!isChecked) {
mp.setVolume(1, 1);
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
mp2.setVolume(0, 0);
}
}
Other approach would be to add click-listeners only after creating media players.
This link sheds more light on MediaPlayer release.
And the complete source would look as shown below.
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
CheckBox checkBoxmp;
private MediaPlayer mp, mp2;
SharedPreferences mypref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Dialog 1
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//end Dialog 1
//Dialog 2
createDialog2();
Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
dialogButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.show();
}
});
closeButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
}
});
//end Dialog 2
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
final SharedPreferences.Editor editor = mypref.edit();
checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean("playSounds", !isChecked);
editor.commit();
if (null != mp && null != mp2) {
if (!isChecked) {
mp.setVolume(1, 1);
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
mp2.setVolume(0, 0);
}
}
}
});
final boolean playSounds = mypref.getBoolean("playSounds", false);
checkBoxmp.setChecked(!playSounds);
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
final List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
//Code of the mediaplayer begins:
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
try {
mp2 = new MediaPlayer();
if (playSounds) {
mp2.setVolume(1, 1);
} else {
mp2.setVolume(0, 0);
}
AssetFileDescriptor afd;
afd = getAssets().openFd("wrong.mp3");
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp2.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp2.start();
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
//End mediaplayer main code
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
private void createDialog2() {
dialog2 = new Dialog(this);
dialog2.setTitle("Settings");
dialog2.setContentView(R.layout.popup_menu1_2);
closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);
}
}

How to reset the seekbar

I have a program with 10 songs
When I click on one of the songs the seekbar start moving
But the problem is when I click on another song seekbar doesn't go back and start moving again it just stop where the first song has stopped
So how can I reset the seekbar when I click on another song
public class on extends AppCompatActivity {
MediaPlayer x;
int tx1;
mythread my = new mythread();
private SeekBar seekbar;
class mythread extends Thread {
public void run() {
while (x != null) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
seekbar.post(new Runnable() {
#Override
public void run() {
seekbar.setProgress(x.getCurrentPosition());
}
});
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on);
Button a = (Button) findViewById(R.id.button1);
Button b = (Button) findViewById(R.id.button2);
Button c = (Button) findViewById(R.id.button3);
Button d = (Button) findViewById(R.id.button4);
Button e = (Button) findViewById(R.id.button5);
Button f = (Button) findViewById(R.id.button6);
Button g = (Button) findViewById(R.id.button7);
Button h = (Button) findViewById(R.id.button8);
Button i = (Button) findViewById(R.id.button9);
Button j = (Button) findViewById(R.id.button10);
seekbar = (SeekBar) findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tx1 = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
x.seekTo(tx1);
}
});
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.onone);
seekbar.setMax(x.getDuration());
x.start();
my.start();
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.ontwo);
seekbar.setMax(x.getDuration());
x.start();
my.start();
}
});
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.onthree);
seekbar.setMax(x.getDuration());
x.start();
my.start();
}
});
d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.onfour);
seekbar.setMax(x.getDuration());
my.start();
x.start();
}
});
e.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.onfive);
seekbar.setMax(x.getDuration());
my.start();
x.start();
}
});
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.onsix);
seekbar.setMax(x.getDuration());
my.start();
x.start();
}
});
g.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.onseven);
seekbar.setMax(x.getDuration());
my.start();
x.start();
}
});
h.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.oneight);
seekbar.setMax(x.getDuration());
my.start();
x.start();
}
});
i.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.onnine);
seekbar.setMax(x.getDuration());
my.start();
x.start();
}
});
j.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
x = MediaPlayer.create(on.this, R.raw.onten);
seekbar.setMax(x.getDuration());
my.start();
x.start();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (x != null) {
x.stop();
}
}
private void stopPlaying() {
if (x != null) {
x.stop();
x.release();
x = null;
}
}}
and I tried to do this method in every onClick
public void resetseek(){
if(seekbar.getProgress() > 0)
{
seekbar.setProgress(0);
}
}
Normally one would use
seekbar.setProgress(0);
to reset a progress bar it to it's initial position.
I see you have posted your code as an answer instead of editing your question.
One big issue with your code is that you call Thread.start() more than once, which is illegal.
Also I wouldn't update the ProgressBar in a separate thread, instead you could just do it on the UI thread.
An alternate approach can be read in this question MediaPlayer, ProgressBar

cannot be reference from a static context, run in other class

I would like to put the function run_voice() of my MainActivity on my class TypingDialogFragment but it do not work:
Non static method 'run_voice' cannot be reference from a static context
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
Home1=(ImageView)findViewById(R.id.home);
Voice1=(ImageView)findViewById(R.id.voice);
Scan1=(ImageView)findViewById(R.id.scan);
frequence_text=(TextView)findViewById(R.id.frequence_text);
command_text=(TextView)findViewById(R.id.command_text);
gain_text=(TextView) findViewById(R.id.gain_text);
body = (TextView)findViewById(R.id.body);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab_frequence = (FloatingActionButton) findViewById(R.id.freq_value);
fab_gain = (FloatingActionButton) findViewById(R.id.gain_value);
send_voice = (ImageButton) findViewById(R.id.send_voice1);
send_voice2 = (ImageView) findViewById(R.id.send_voice3);
myChrono=(Chronometer) findViewById(R.id.chronometer);
progressBar=(ProgressBar) findViewById(R.id.progressBar);
body.setMovementMethod(new ScrollingMovementMethod());
setSupportActionBar(toolbar);
OUTPUT_FILE= Environment.getExternalStorageDirectory()+ "/audiorecord.wav";
outFile=new File (OUTPUT_FILE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
type = 1;
showCmdLineDialog(type,run_voice);
}
});
fab_frequence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
type = 2;
showCmdLineDialog(type,run_voice);
}
});
fab_gain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
type = 3;
showCmdLineDialog(type,run_voice);
}
});
display_mediaplayer_false();
display_floatbutton_false();
success1=0;
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)){
Toast.makeText(this, "FEATURE_BLUETOOTH NOT support", Toast.LENGTH_LONG).show();
finish();
return;
}
//using the well-known SPP UUID
myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this hardware platform", Toast.LENGTH_LONG).show();
finish();
return;
}
Home1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(success1==1)
{
display_mediaplayer_false();
display_floatbutton_true();
}
}
});
Voice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(success1==1) {
display_floatbutton_false();
display_mediaplayer_true();
}
}
});
Scan1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(success1==1) {
display_floatbutton_false();
display_mediaplayer_false();
}
}
});
send_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
run_voice(); // FUNCTION RUN VOICE
}
});
}
My function run_voice :
public void run_voice()
{
try {
if (color==0)
{
send_voice.setColorFilter(Color.RED);
beginRecording();
progressBar.setVisibility(View.VISIBLE);
myChrono.setBase(SystemClock.elapsedRealtime());
myChrono.start();
color1=1;
run_voice=1;
}
if (color==1)
{
send_voice.setColorFilter(Color.BLACK);
progressBar.setVisibility(View.INVISIBLE);
stopRecording();
myChrono.stop();
color1=0;
run_voice=0;
}
color=color1;
}
catch (IOException e) {
e.printStackTrace();
}
}
I would like to put this function in this class :
public static class TypingDialogFragment extends DialogFragment {
EditText cmdLine;
static MainActivity parentActivity;
static ThreadConnected cmdThreadConnected;
static int type1;
static int run_voice1;
static TypingDialogFragment newInstance(MainActivity parent, ThreadConnected thread, int type, int run_voice){
type1=type;
run_voice1=run_voice;
parentActivity = parent;
cmdThreadConnected = thread;
TypingDialogFragment f = new TypingDialogFragment();
return f;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().setTitle("Cmd Line");
getDialog().setCanceledOnTouchOutside(false);
View typingDialogView = inflater.inflate(R.layout.typing_layout, container, false);
cmdLine = (EditText)typingDialogView.findViewById(R.id.cmdline);
ImageView imgCleaarCmd = (ImageView)typingDialogView.findViewById(R.id.clearcmd);
imgCleaarCmd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cmdLine.setText("");
}
});
ImageButton send_voice=(ImageButton)getActivity().findViewById(R.id.send_voice1);
send_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
byte[] NewLine = "\n".getBytes();
byte[] bytesToSend="pkill -f receiverfm.py".getBytes();
byte[] bytesToSend2="./emetteur.py".getBytes();
byte[] bytesToSend3="pkill -f emetteur.py".getBytes();
byte[] bytesToSend4="./receiverfm.py".getBytes();
if (run_voice1==0)
{
cmdThreadConnected.write(bytesToSend);
cmdThreadConnected.write(NewLine);
cmdThreadConnected.write(bytesToSend2);
}
if (run_voice1==1)
{
cmdThreadConnected.write(bytesToSend3);
cmdThreadConnected.write(NewLine);
cmdThreadConnected.write(bytesToSend4);
}
cmdThreadConnected.write(NewLine);
}
});
Button btnEnter = (Button)typingDialogView.findViewById(R.id.enter);
btnEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cmdThreadConnected!=null){
byte[] memory_freq="100.0".getBytes();
if (type1==1)
{
byte[] bytesToSend = cmdLine.getText().toString().getBytes();
cmdThreadConnected.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
cmdThreadConnected.write(NewLine);
}
if (type1==2)
{
byte[] byteToSend_freq = "./receiverfm.py --freq ".getBytes();
byte[] bytesToSend = cmdLine.getText().toString().getBytes();
memory_freq=bytesToSend;
cmdThreadConnected.write(byteToSend_freq);
cmdThreadConnected.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
cmdThreadConnected.write(NewLine);
}
if (type1==3)
{
byte[] byteToSend_gain="./receiverfm.py --freq ".getBytes();
cmdThreadConnected.write(byteToSend_gain);
cmdThreadConnected.write(memory_freq);
byte[] byteToSend_gain2=" --".getBytes();
byte[] bytesToSend = cmdLine.getText().toString().getBytes();
cmdThreadConnected.write(byteToSend_gain2);
cmdThreadConnected.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
cmdThreadConnected.write(NewLine);
}
}
}
});
Button btnDismiss = (Button)typingDialogView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
Button btnClear = (Button)typingDialogView.findViewById(R.id.clear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
body.setText("");
}
});
return typingDialogView;
}
}

Categories