how to restart horizontal progressbar - android

I've a horizontal progressbar which shows progress from 0 to 100. What I want is to restart the progressbar again from 0 when it reaches 100. I'll be showing this in a Fragmentdialog. For now I'm checking it in activity itself. How to do that?
public class MainActivity extends AppCompatActivity{
private Button startbtn, stopbtn;
ProgressBar pb;
private TextView progressTxt;
int progressBarValue = 0;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = new CShowProgress(MainActivity.this);
btn = (Button)findViewById(R.id.btn);
startbtn = (Button)findViewById(R.id.startbtn);
stopbtn = (Button)findViewById(R.id.stopbtn);
pb = (ProgressBar)findViewById(R.id.progressBar);
progressTxt = (TextView)findViewById(R.id.progressTxt);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myprogress(true);
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myprogress(false);
}
});
}
private void myprogress(final Boolean isStart){
handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
if(isStart && progressBarValue<100)
{
progressBarValue+=1;
pb.setProgress(progressBarValue);
progressTxt.setText(String.valueOf(progressBarValue));
handler.sendEmptyMessageDelayed(0, 100);
}
}
};
handler.sendEmptyMessage(0);
}
}

I assume this chunk of code will work for your use case:
private void myprogress(final Boolean isStart) {
handler = new Handler() {
public void handleMessage(Message msg) {
if (isStart && progressBarValue < 100) {
...
} else if (isStart) {
// progressBarValue is equal to 100
// make it zero and do the same thing again
progressBarValue = 0;
progressBarValue += 1;
pb.setProgress(progressBarValue);
progressTxt.setText(String.valueOf(progressBarValue));
handler.sendEmptyMessageDelayed(0, 100);
}
}
};
handler.sendEmptyMessage(0);
}

First, you should use a counter mechanizm (run a delayed handler, timer, thread or something else)to check current progress periodically.
(progressTxt.getProgress == 100)
will do the trick.
Another way is using this answer.

Related

Seekbar is still not updating

I made these two method to update seekbar every 100ms:
public void updateSeekBar() {
handler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
#Override
public void run() {
mySeekBar.setMax(mySong.getDuration());
x = mySong.getCurrentPosition();
mySeekBar.setProgress(x);
handler.postDelayed(this, 100);
}
};
and put it inside my playMusic method:
public void playMusic() {
//just a test from intent.getExtra
if(test.equalsIgnoreCase("Jason Mraz")) {
mySong = MediaPlayer.create(MusicClass.this, jm[musicCounter]);
displaySong(jm);
songNumbers = jm.length;
}else if(test.equalsIgnoreCase("fob")) {
mySong = MediaPlayer.create(MusicClass.this, fob[musicCounter]);
displaySong(fob);
songNumbers = fob.length;
}else if(test.equalsIgnoreCase("ed")) {
mySong = MediaPlayer.create(MusicClass.this, ed[musicCounter]);
displaySong(ed);
songNumbers = ed.length;
}
//when the song is completed
mySong.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
nextSong();
}
});
//seekbar update
mySeekBar.setMax(mySong.getDuration());
mySeekBar.setProgress(0);
mySong.start();
updateSeekBar();
}
this is my onCreate method:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
artistName = (TextView)findViewById(R.id.artistName);
song = (TextView)findViewById(R.id.song);
musicCounter = 0;
ifPlaying = true;
isRandom = false;
random = (ImageButton) findViewById(R.id.random);
stop = (ImageButton)findViewById(R.id.stop);
myImageView = (ImageView)findViewById(R.id.myImageView);
dice = new Random();
mySeekBar = (SeekBar)findViewById(R.id.mySeekBar);
test = getIntent().getStringExtra("test");
if(test.equalsIgnoreCase("Jason Mraz")) {
artistName.setText("Jason Mraz");
displayPP();
songNumbers = jm.length;
myImageView.setImageResource(R.drawable.jason_mraz);
} else if (test.equalsIgnoreCase("fob")) {
artistName.setText("Fall Out Boys");
displayPP();
songNumbers = fob.length;
myImageView.setImageResource(R.drawable.fall_out_boys);
} else if (test.equalsIgnoreCase("ed")) {
artistName.setText("Ed Sheeran");
displayPP();
songNumbers = ed.length;
myImageView.setImageResource(R.drawable.ed_sheeran);
}
playMusic();
mySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
mySong.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mySong.pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (ifPlaying == true) {
mySong.start();
} else {
return;
}
}
});
}
My application says Unfortunately stopped. But when I remove the updateSeekbar in playMusic method it works fine, but without the updating seekBar every second. The setOnSeekBarChangeListener works perfectly fine, the only problem is I can't make updateSeekBar method work because it is alwats stopping my application and force exit.
The symptoms you are describing is called an ANR. It means that you is doing to much work in the main thread.
What you need todo is review what you are triggering in your mUpdateTimeTask.
Next make sure your handler is running on the UI since your are updating views:
Handler handler = new Handler(Looper.getMainLooper());

How to loop a sound a different number of times at set intervals - android

I've done a little with android in the past, but this is the first time I've touched it in over a year and I've been stuck on this problem since yesterday.
I'm working on a project with someone and I need to play a sound a certain number of times at set intervals. (For example, play once after one minute, twice after two minutes, three times after three minutes, and on and on). I can get the sound to play at whatever interval, that's not an issue, but I can't figure out how to get it to play the correct number of times at each interval. It either ends up looping infinitely, playing once each time the interval is up or playing once and stopping.
Tried TimerTask, switched to Handler/Runnable, tried using a for loop and using an if statement with counter. After two evenings of multiple attempts, hours of research and my limited experience, this is the one problem I've run into that I haven't been able to figure out.
Here's the code I've currently got in for this particular feature. I'm having issues with the Runnable tenMinChime and OnCompletionListener chimeCompletion. Any guidance at all is very appreciated.
public class MainActivity extends AppCompatActivity {
TextView chimeOn, chimeOff;
Handler chimeHandler = new Handler();
MediaPlayer.OnCompletionListener chimeCompletion;
MediaPlayer cp;
int chimeCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (screen == 1) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
setContentView(R.layout.activity_main);
chimeOn = (TextView) findViewById(R.id.chimeOn);
chimeOff = (TextView) findViewById(R.id.chimeOff);
chimeOn.setTextColor(0xFFbebebe);
chimeOff.setTextColor(0xFF000000);
cp = MediaPlayer.create(this, R.raw.placeholder_chime);
chimeOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (chime == 0) {
chimeOn.setTextColor(0xFF000000);
chimeOff.setTextColor(0xFFbebebe);
handler2.postDelayed(tenMinChime, 5000);
chime = 1;
}
}
});
chimeOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (chime == 1) {
chimeOff.setTextColor(0xFF000000);
chimeOn.setTextColor(0xFFbebebe);
handler2.removeCallbacks(tenMinChime);
chime = 0;
}
}
});
chimeCompletion = new MediaPlayer.OnCompletionListener() {
int count = 0;
int maxCount = chimeCount;
#Override
public void onCompletion(MediaPlayer mp) {
if(count < maxCount) {
count++;
cp.seekTo(0);
cp.start();
cp.setOnCompletionListener(chimeCompletion);
}
}
};
public Runnable tenMinChime = new Runnable() {
public void run() {
chimeCount+=1;
cp.start();
cp.setOnCompletionListener(chimeCompletion);
}
};
Maybe this solves your issue ?
public class MainActivity extends AppCompatActivity {
TextView chimeOn, chimeOff;
Handler handler2 = new Handler();
MediaPlayer.OnCompletionListener chimeCompletion;
MediaPlayer cp;
int chimeCount = 0;
int mPlayCount=0;
int mMaxPlayCount=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (screen == 1) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
setContentView(R.layout.activity_main);
chimeOn = (TextView) findViewById(R.id.chimeOn);
chimeOff = (TextView) findViewById(R.id.chimeOff);
chimeOn.setTextColor(0xFFbebebe);
chimeOff.setTextColor(0xFF000000);
cp = MediaPlayer.create(this, R.raw.placeholder_chime);
chimeOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (chime == 0) {
chimeOn.setTextColor(0xFF000000);
chimeOff.setTextColor(0xFFbebebe);
handler2.postDelayed(tenMinChime, 5000);
chime = 1;
}
}
});
chimeOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (chime == 1) {
chimeOff.setTextColor(0xFF000000);
chimeOn.setTextColor(0xFFbebebe);
handler2.removeCallbacks(tenMinChime);
cp.setOnCompletionListener(null);
chime = 0;
mMaxPlayCount=0;
mPlayCount=0;
}
}
});
chimeCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(mPlayCount < mMaxPlayCount) {
mPlayCount++;
cp.seekTo(0);
cp.start();
}
}
};
public Runnable tenMinChime = new Runnable() {
public void run() {
mPlayCount=0;
mMaxPlayCount= 3;
cp.setOnCompletionListener(chimeCompletion);
cp.start();
}
};

How to update TextView dynamically (periodically)?

I am developing a simple android activity with a scrollable TextView. I am displaying numbers from 1-100 in my TextView with a time delay. However my desired output is not what I'm getting.
Current Output: 1 replaced by 2 replaced by 3....till 100.
Desired Output:
1
2
3
4
.
.
100
Here is my Activity code:
public class MainActivity extends ActionBarActivity {
private static int i = 0;
TextView textView;
Handler handler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
textView = (TextView) findViewById(R.id.text_area);
new PrimeCalculation().execute();
handler = new Handler();
handler.post(updateView);
}
private Runnable updateView = new Runnable() {
#Override
public void run() {
if(i <= 100) {
textView.setText(Integer.toString(i));
i++;
handler.postDelayed(this, 1000);
}
}
};
}
How about this:
textView.setText(textView.getText() + "\n" + i);
Create a new String Array. Set the text view to the array.toString(); Every time that your timer runs out insert the most recent number into the array and repeat. The most recent number should be an int that increases when the timer runs out. Hope this helps!
Try this
private Handler mHandler = new Handler();
private int nCounter = 0;
View.OnClickListener mButtonStartListener = new OnClickListener() {
public void onClick(View v) {
try {
mHandler.removeCallbacks(hMyTimeTask);
// Parameters
// r The Runnable that will be executed.
// delayMillis The delay (in milliseconds) until the Runnable will be executed.
mHandler.postDelayed(hMyTimeTask, 1000); // delay 1 second
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Runnable hMyTimeTask = new Runnable() {
nCounter++;
hTextView.append("\n"+nCounter);
}
public void run() {
};
Hope this will help you
You can use following code......
public class MainActivity extends ActionBarActivity {
private static int i = 0;
TextView textView;
Handler handler;
String textViewText="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_area);
handler = new Handler();
handler.post(updateView);
}
private Runnable updateView = new Runnable() {
#Override
public void run() {
if(i <= 100) {
//
textViewText=textViewText+Integer.toString(i)+" ";
textView.setText(textViewText);
// textViewText=textViewText+textView.getText().toString();
i++;
handler.postDelayed(this, 1000);
}
}
};}
I hope it will help you....

Android dev't using thread with textview: why this is crashing?

My goal is when the user tap start button, letters "o" "n" "o" "m" and so forth will appear at the center of the screen. "o" will appear first then after a few seconds will be replaced by "n" then "o" and so forth.
note: for brevity, i just make the guessword = onomatopoeia, first. In reality, guessword will changes every time i tap the start bottom.
this is the code:
private String guessword = "onomatopoeia";
private TextView showchar;
private int n = guessword.length();
private char letArray[]= guessword.toCharArray();;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
addStartListener();
}
public void addStartListener(){
Button start = (Button) findViewById(R.id.start);
showchar = (TextView) findViewById (R.id.charView);
start.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread thread = new Thread()
{
#Override
public void run() {
try {
for(int i = 0 ; i < n ; i++) {
sleep(1000);
showchar.setText(letArray[i]);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
}
thanks for the help
I decided to implement runonuithread but still it crashes:
this is the updated version:
private String guessword = "onomatopoeia";
private TextView showchar;
private int n = guessword.length();
private char letArray[]= guessword.toCharArray();
private Handler handler;
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
handler = new Handler();
showchar = (TextView) findViewById (R.id.charView);
}
public void startGame(View view){
new Thread() {
public void run() {
while(i++ < n) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
showchar.setText(letArray[i]);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
use this code for setting the text in your textview
runOnUiThread(new Runnable() {
#Override
public void run() {
showchar.setText(letArray[i]);
}
});
You are updating ui from a thread which is not possible.
showchar.setText(letArray[i]);
UI must be updated ui thread.
All you are doing is repeatedly setting value to TextView you can use Handler with a delay for this purpose.
You could use runOnUiThread also but i don't see the need for a thread for what you are doing.
Use a Handler. You can find an example #
Android Thread for a timer

how to get auto changing background image after few seconds?

i'm working on an Android application in which i want the background image to be changed after every 5 seconds. i have all the images in my drawable folder.
i am giving the code which i am using but i am not getting the output. As an output i am getting a still image which is not changing.
Please help
Thanks
[CODE]
public class Home extends Activity {
public static int count=0;
int[] drawablearray=new int[]{R.drawable.slider_1,R.drawable.slider_2,R.drawable.slider_3,R.drawable.slider_4,R.drawable.slider_5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
new Handler().postDelayed(new Runnable() {
public void run() {
if(count<drawablearray.length){
Home.this.getWindow().
setBackgroundDrawableResource(drawablearray[count]);
count++; //<<< increment counter here
}
else{
// reset counter here
count=0;
}
}
}, 5000);
}
}
You can achieve this using Timer
public class Home extends Activity {
public static int count=0;
int[] drawablearray=new int[]{R.drawable.slider_1,R.drawable.slider_2,R.drawable.slider_3,R.drawable.slider_4,R.drawable.slider_5};
Timer _t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
lnMain = (LinearLayout) findViewById(R.id.lnMain);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() // run on ui thread
{
public void run() {
if (count < drawablearray.length) {
lnMain.setBackgroundDrawable(drawablearray[count]);
count = (count + 1) % drawablearray.length;
}
}
});
}
}, 5000, 5000);
}
}
Why don't you have a look at the ViewFlipper class
http://developer.android.com/reference/android/widget/ViewFlipper.html
final Handler h = new Handler();
Runnable r = new Runnable() {
public void run() {
Home.this.getWindow().setBackgroundDrawableResource(drawablearray[count]);
count += (count+1)%drawablearray.length; //<<< increment counter here
h.postDelayed(this, 5000);
}
};
now call like
h.postDelayed(r, 5000);
I think that would be easier to work with the xmls. You can change the background of the main layout of the activity.
Try something like this:
public class Home extends Activity {
public static int count=0;
int[] drawablearray=new int[]{R.drawable.slider_1,R.drawable.slider_2,R.drawable.slider_3,R.drawable.slider_4,R.drawable.slider_5};
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ll = (LinearLayout) findViewByID(R.id.mainlayout) //It depends of the name that you gave to it
new Handler().postDelayed(new Runnable() {
public void run() {
ll.setBackgroundDrawable(drawablearray[count]);
// or ll.setBackgroundResource(resid) if you want.
count += (count+1)%drawablearray.length;
}
}, 5000);
}
}

Categories

Resources