Android Development: seekbar count down! - android

Is it possible, if yes how, how do i go from progress 100 to 1 without the user doing anything.
Like for every .05sec seekbar.setProgress(-=1)
So without the user doing anything the seekbar will go down until it reach 1.
Please anser how to do this
Thank-you

class Async extends AsyncTask<Void, Integer, Void>{
ProgressDialog dialog;
public Async(Context ctx) {
dialog = new ProgressDialog(ctx);
dialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
dialog.incrementProgressBy(1);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int i=0;
while (i < 1000) {
publishProgress(1);
i++;
}
return null;
}
}

You may be forced to write your own progress bar. Here's an example: http://techdroid.kbeanie.com/2010/04/custom-progressbar-for-android.html
There's more than one way to do it...

Something roughly like this (note: may not compile):
private int progressStatus = 100;
new Thread(new Runnable()
{
public void run()
{
while (progressStatus > 1)
{
progressStatus = doSomeWork();
//---Update the progress bar---
handler.post(new Runnable()
{
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
handler.post(new Runnable()
{
public void run() {
// Do your thing here when it's done
}
});
}
private int doSomeWork()
{
try
{
//---simulate doing some work---
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
int progress = progressStatus - 1;
return progress;
}
}).start();

Related

What is the difference between a UIHandler and a Handler

I want to show numbers from 1 to 100 in sequel order in the TextView and to wait 1 second after printing each number. I also want to implement it using Android services.
I don't know the difference between UIHandler and Handler. When I google about this issue, all I am getting is the difference between handler and a thread.
Please help me out of this,
Thanks in advance
private static final int SHOW_MESSAGE = 1;
private static final int m_cdelay = 1000;
private UIHandler m_cUIHandler;
public int m_cI= 0;
TextView m_cTextShow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_cTextShow = (TextView) findViewById(R.id.textview1);
for(m_cI=1; m_cI <= 100; m_cI++){
//m_cUIHandler = new UIHandler();
//m_cUIHandler.sendEmptyMessageDelayed(SHOW_MESSAGE, 1000);
showMessage(m_cI);
}
}
private void showMessage(int m_cI2) {
for(m_cI=1; m_cI <= 100; m_cI++){
m_cTextShow.setText(""+m_cI);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(m_cdelay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}).start();
}
}
#Override
protected void onResume() {
super.onResume();
startService(new Intent(this, NumberService.class));
}
public final class UIHandler extends Handler {
#Override
public void handleMessage(Message pObjMessage) {
switch(pObjMessage.what) {
case SHOW_MESSAGE:
m_cTextShow.setText(""+m_cI);
break;
}
}
}
You can actually rewrite your code like that to make it probably work.
Pls test it and respond.
public void showMessage(int number){
runOnUiThread(new Runnable(){
public void run() {
//Write your number onto the screen
}
});
}
protected void onCreate(Bundle savedInstanceState) {
//Blablabla...
for(m_cI=1; m_cI <= 100; m_cI++){
//m_cUIHandler = new UIHandler();
//m_cUIHandler.sendEmptyMessageDelayed(SHOW_MESSAGE, 1000);
showMessage(m_cI);
Thread.sleep(1000);
}
}

Android progress spinner loader stops spinning when the data starts fetching in background

I am using a progress spinner on pre execute method of Async task to show it on UI and the data starts fetching in the background from Api using volley library.The problem is when it starts fetching the data,the loader stops spinning and its like the UI is not responding.
need help,Thanks in advance..
`
ProgressDialog dialog;
public void open() {
dialog = new ProgressDialog(BuzoongaContacts.this);
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
dialog.setContentView(R.layout.progress_layout);
dialog.setCanceledOnTouchOutside(false);
}
public void stopLoading() {
Log.d("res", "stopLoading ");
try {
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
}`
Async Task:
class BuzoongaContactsAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
runOnUiThread( new Runnable() {
public void run() {
open();
}
});
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ContactsDataTableOperations conDataTab = new ContactsDataTableOperations(BuzoongaContacts.this);
conDataTab.open();
JSONParsingForContactsB.count = 0;
count = 0;
if (fromRefresh)
{
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !",getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else
{
if (getContactsExistence() == 0) {
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !", getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else if (Constants.buzoongaContactsAdded)
{
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !", getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else {
stopLoading();
}
}
arr_list = conDataTab.getAllRecords();
conDataTab.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
cb_select_all.setChecked(false);
iv_quick_launch.setBackgroundResource(R.drawable.quick_lounch_icon_disable);
Constants.selected_buzoonga_contacts = 0;
rl_delete.setAlpha(0.5f);
rl_delete.setClickable(false);
rl_show_contacts.setVisibility(View.INVISIBLE);
mAdapter.notifyDataSetChanged();
}
}
Basically, you can't touch your UI elements in background threads, which means that all your calls to startAnimation() or stopLoading should be wrapped with runOnUiThread.
But I can see your UI code is so bound up with your background code. Maybe you could consider using Thread & Handler instead of AsyncTask.

Running SoundPool on Background with AsyncTask

I am trying to play 5 SoundPool one after the other on Background using AsyncTask for it. But I wanna click an ImageView while sounds are running. The problem begins when SoundPool uses getBaseContext() that blocks my ImageView while doInBackground is running.
Does anyone know whats happening?
Thxs a lot!
Here is my code:
public class SensoriomotoraActivity extends Activity {
private boolean playing = false ;
private ImageView image ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensoriomotora);
image = (ImageView) findViewById(R.id.img_sensoriomotora_pandereta);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (playing){
Log.v("onClick","clicked while playing");
}
else {
Log.v("onClick","clicked while !playing");
}
}
});
new Thread (
new Runnable(){
#Override
public void run(){
// Waiting 2.5 secs before playing the beeps
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
new PlaySoundBackground().execute();
}
});
}
}
).start();
}
private class PlaySoundBackground extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
playing = true ;
}
#Override
protected Void doInBackground(Void... params) {
SoundPool sound;
sound = new SoundPool(1, AudioManager.STREAM_MUSIC,0);
sound.load(getBaseContext(), R.raw.beep, 1);
sound.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
for (int i=0 ; i<5; i++){
soundPool.play(sampleId, 1, 1, 1, 0, 1);
try {
Thread.sleep(2000); // Waits 2 secs before next beep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
playing = false ;
}
}
}

reduce delay in display progress bar

As I created a Progress bar using below code in a on click method of button. but after clicking button it takes 2-3 seconds to display progress bar.how to reduce that delay to start progress bar.
public void getProgressBar() {
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
progressBarStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = doSomeTasks();////I am loading service
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100 ) {
progressBar.dismiss();
startActivity(new Intent(getApplicationContext(),
StatisticDisplay.class));
}
}
}).start();
}
public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myProgress = 0;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
Use an AsyncTask instead. The example code in the link gives a good introduction on how to do it. In essence you do the job in doInBackground(), publish your progress using onProgressUpdate() and start your activiy in onPostExecute().

Android splash screen and server communication

I am developing an application in android, where i need to display a splash screen and at the same time there will be server communication. The problem here is when i launch the app, first application is communicating with the server and then it is displaying the splash screen. I want to both server communication and splash screen at the same time.
The following is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
try {
Thread thread = new Thread(this);
thread.start();
thread.join();
//Attractions
CommonMethods.getSystemOutput("Response Json Array String Attractions:::"+jArrayMobileAttractions);
attractionsDate = JsonParsing.getLatestDate(jArrayMobileAttractions);
attractionsDate = getDate(attractionsDate);
CommonMethods.getSystemOutput("Attractions Date:::::"+attractionsDate);
//Categories
CommonMethods.getSystemOutput("Response Json Array String Categories:::"+jArrayCategories);
categoryDate = JsonParsing.getLatestDate(jArrayCategories);
categoryDate = getDate(categoryDate);
CommonMethods.getSystemOutput("Category date:::"+categoryDate);
//Contacts
CommonMethods.getSystemOutput("Response Json Array String Contacts:::"+jArrayContacts);
contactsDate = JsonParsing.getLatestDate(jArrayContacts);
contactsDate = getDate(contactsDate);
CommonMethods.getSystemOutput("Contacts Date:::"+contactsDate);
} catch (Exception e) {
CommonMethods.getSystemOutput("Exception in Splash screen thread:::"+e);
}
}
public void run() {
// if (attractionsDate == null) {
jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL);
jArrayCategories = RequestHandler.getJSONfromURL(Constants.CATEGORY_URL);
jArrayContacts = RequestHandler.getJSONfromURL(Constants.CONTACTS_URL);
// } else {
// jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL+"?lastupdateddate="+attractionsDate);
// }
}
You can use the AsynchTask Manager in which it has a method
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// Do Server Interaction Here
return response;
}
#Override
protected void onPreExecute(String result) {
//Show your Splash Screen
}
#Override
protected void onPostExecute(String result) {
//Gone the Splash Screen view
}
}
For this purpose it will be better start from "SplashActivity" - in onCreate() start new Thread for communication with server, and when all communication finished - call startActivityForResult(mainActivityIntent). For correct behavior back button finish splash activity on finish main activity. Approximate code:
public class SplashActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setup view for activity
new Thread(new Runnable() {
public void run() {
// do here some long operation
startActivityForResult(new Intent(SplashActivity.this, MainActivity.class), 0);
}
}).start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
finish();
}
}
I had the same thing to do and I did it this way and it works just fine. I had to show the splashscreen and download some file from the server, unzip it, move files insto proper directories and then start the apps main screen. Here is the code, I used AsyncTask.
So, you have three AsyncTask classes, one for each task and in the onPostExecute() I call the next AsyncTask. I can't say if this is the best way but it works for me.
I removed unneccessary code but for clarity I left a call to a dialog where I ask a user ih he wants to proceed with downloading as it may take a while. Also I check if FIRST_RUN is true just so I know if I should download the package since for my app I need to do it only the first time, so if it is true I do the spashscreen activities and if it is false I proceed to MAINAPP activity.
Hope it helps.
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
boolean firstRun = settings.getBoolean("FIRST_RUN", true);
if (firstRun) {
showDialog(INITIAL_DLG);
} else {
startActivity(new Intent(appContext, MAINAPP.class));
}
}
/***
* First entry after YES on Dialog!
*/
protected void initialize() {
messageTV.setVisibility(TextView.VISIBLE);
progressBar.setVisibility(ProgressBar.VISIBLE);
downloadThread = new DownloadFiles();
downloadThread.execute();
}
protected void rollback() {
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder;
switch (id) {
case INITIAL_DLG:
builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.app_setup)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
initialize();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDlg = builder.create();
return alertDlg;
default:
return null;
}
}
protected class DownloadFiles extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//file download
} catch (Exception e) {
result = false;
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
unzipThread = new DecompressZipFile();
unzipThread.execute();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
messageTV.setText("Step 1/4:Downloading data...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
}
protected class DecompressZipFile extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//unzip files
return true;
} catch(Exception e) {
return false;
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (values[0]<0) progressBar.setMax(values[0]*-1);
else progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
moveDBThread = new MoveDBFile();
moveDBThread.execute();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
messageTV.setText("Step 2/4:Decompressing data...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
}
protected class MoveDBFile extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//moving files
return true;
} catch (Exception e) {
globalE = e;
finish();
return false;
}
}
#Override
protected void onPreExecute() {
messageTV.setText("Step 3/4:Shufflin'...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
getSharedPreferences(PREFS_NAME,0).edit().putBoolean("FIRST_RUN", false).commit();
startActivity(new Intent(appContext, MAINAPP.class));
} else {
rollback();
}
}
}
}

Categories

Resources