I am making a app for training. In my app one video is playing after some second one alert dialog show the dialog contain question and answer student read the question and select the answer until my thread want to wait. Here i successfully get the video timing. I want to do pause the thread until alert dialog close.
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
running = true;
final int duration = mVideoView.getDuration();
new Thread(new Runnable() {
boolean myRunning;
public void run() {
synchronized (mSync) {
myRunning = mSync.running;
}
do {
textView.post(new Runnable() {
public void run() {
int time = Math.round(mVideoView.getCurrentPosition() / 1000);
textView.setText(time + "");
if (time == 5) {
running = false;
mVideoView.pause();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Page02.this);
alertDialogBuilder.setMessage("Are you sure,You wanted to make decision");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
onResume();
mVideoView.start();
arg0.dismiss();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!running) break;
}
while (mVideoView.getCurrentPosition() < duration);
}
}).start();
}
});
}
#Override
protected void onPause() {
super.onPause();
synchronized (mSync) {
running = false;// you can not set it here because
// it is possible for the thread to read it and exit the loop before he posts your message
mSync.mustBePost = true;
mSync.message = "Main Activity is going to pause";
}
}
#Override
protected void onResume() {
super.onResume();
threadNameCounter++;
synchronized (mSync) {
running = true;
mSync.mustBePost = true;
mSync.message = "Main Activity is going to resume";
}
t = new Thread("My Name is " + String.valueOf(threadNameCounter));
t.start();
}
}
Related
Please I want to know how to set my MediaPlayer to playback continuously without stopping when activity screen rotates? The challenge I'm having now is that when playing is in progress and I happen to tilt the screen the music stops and will require another action to have it play again.
this is the part of which plays the music in my Activity
// setting up media players
public void play(View v) {
if (player == null) {
//then here, I sent the position of the chosen song in the intent extras.
//the get back the extra
int position = 0;
try{
position=getIntent().getIntExtra("soundfile",0);
}catch (Exception e)
{
e.printStackTrace();
}
String fileToPlay="song_"+position;
player = MediaPlayer.create(this, position);
Toast.makeText(this, "Hymn Tune Playing", Toast.LENGTH_SHORT ).show();
soundSeekBar = (SeekBar) findViewById(R.id.seekBar1);
soundSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
player.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
soundSeekBar.setProgress(player.getCurrentPosition());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.getCurrentPosition();
}
});
player.setLooping(true);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
}
player.start();
Toast.makeText(this, "Playing Continues...", Toast.LENGTH_SHORT ).show();
soundThread = new Thread(this);
soundThread.start();
}
public void pause(View v) {
if (player != null) {
player.pause();
Toast.makeText(this, "Hymn Tune Paused", Toast.LENGTH_SHORT ).show();
}
}
public void stop(View v) {
stopPlayer();
}
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "Hymn Tune Stoped", Toast.LENGTH_SHORT ).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
#Override
public void run() {
int currentPosition = 0;
int soundTotal = player.getDuration();
soundSeekBar.setMax(soundTotal);
while (player != null && currentPosition < soundTotal){
try {
Thread.sleep(300);
currentPosition = player.getCurrentPosition();
}
catch (InterruptedException soundException){
return;
}
catch (Exception otherException){
return;
}
soundSeekBar.setProgress(currentPosition);
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
You must move your playback code to background service, as those will run constantly while activity is stopped and restarted during tilting. Check out extensive guide to services here
https://developer.android.com/guide/components/services
I've got this code:
#Override
public void onClick(View v) {
progressDoalog = new ProgressDialog(Hack.this);
progressDoalog.setMax(100);
progressDoalog.setMessage("Its loading....");
progressDoalog.setTitle("ProgressDialog bar example");
progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDoalog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
while (progressDoalog.getProgress() <= progressDoalog
.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDoalog.getProgress() == progressDoalog
.getMax()) {
progressDoalog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Handler handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDoalog.incrementProgressBy(1);
}
};
});
}
}
Where can I add a code to open new activity when the ProgressDialog will be at 100%? Which and where exactly? Thanks for your help!
You can't start an Activity from a Dialog, but what you can do is start the Activity from the old one using a OnDismissListener.
Take a look at the documemtation :
https://developer.android.com/reference/android/content/DialogInterface.OnDismissListener.html
I haven't noticed but you can check the progress in your Handler, check if it's 100%, dismiss the dialog and start the new Activity, remember that you gotta do this on the UI thread
I am trying to validate the Nymi band asynchronously . But when I try to do that, I get the following exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I have all the toasts in the following method as you can see:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
But Still I get the exception. The method works fine when run normally in the onCreate() method,but fails to run asynchronously .
Edit: Even after removing all the toasts, I still get the exception.
Here is my Thread class,where I am calling the validate() asynchronously :
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
TestBluetooth tb=new TestBluetooth();
tb.startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
Here is the main class where I have the validate methods:
public class TestBluetooth extends Activity implements OnClickListener,ProvisionController.ProvisionProcessListener,
ValidationController.ValidationProcessListener {
boolean isBluetoothEnabled = false;
static boolean nclInitialized = false;
static final String LOG_TAG = "AndroidExample";
SharedPreferences prefs;
Button checkBlue,proviNymi,validateNymi,disconnectNymi;
ProvisionController provisionController;
ValidationController valiationController;
boolean connectNymi = true;
int nymiHandle = Ncl.NYMI_HANDLE_ANY;
NclProvision provision;
//NclProvision provisionmid;
String temp_ID,temp_Key;
public String keyuse;
public String iduse;
public LinearLayout progressbar;
public ProgressBar pbHeaderProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testbluetooth);
// I tried this too final Handler timedThread= new Handler(Looper.getMainLooper());
final Handler timedThread=new Handler();
timedThread.postDelayed(new Runnable() {
#Override
public void run() {
NymiAsync task=new NymiAsync();
task.execute(1,1,1);
}
},10000);
}
public void startValidatingNymi(){
progressbar = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
pbHeaderProgress=(ProgressBar) findViewById(R.id.pbHeaderProgress);
pbHeaderProgress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#1109EE"), android.graphics.PorterDuff.Mode.SRC_ATOP);
// prefs = getSharedPreferences(Util.SharedPrefKey, Context.MODE_PRIVATE);
// prefs.edit().clear().commit();
prefs=getSharedPreferences(Util.SharedPrefKey,MODE_PRIVATE);
temp_ID = prefs.getString(Util.provID, null);
temp_Key = prefs.getString(Util.provKey, null);
if ((temp_ID!=null) || (temp_Key!=null)){
// SHOW THE SPINNER WHILE LOADING FEEDS
progressbar.setVisibility(View.VISIBLE);
//Toast.makeText(getBaseContext(), "Nymi band is already provisined" , Toast.LENGTH_SHORT ).show();
initializeNcl();
provision = new NclProvision();
load();
if (valiationController == null) {
valiationController = new ValidationController(TestBluetooth.this);
}
else {
valiationController.stop();
}
valiationController.startValidation(TestBluetooth.this, provision);
proviNymi = (Button) findViewById(R.id.provisionNymi);
proviNymi.setOnClickListener(this);
proviNymi.setEnabled(false);
validateNymi = (Button) findViewById(R.id.validateNymi);
validateNymi.setOnClickListener(this);
validateNymi.setEnabled(false);
disconnectNymi = (Button) findViewById(R.id.disconnectNymi);
disconnectNymi.setOnClickListener(this);
disconnectNymi.setEnabled(false);
}else {
// Toast.makeText(getBaseContext(), "provision key is null!" , Toast.LENGTH_SHORT ).show();
checkBlue = (Button) findViewById(R.id.testBLuetooth);
checkBlue.setOnClickListener(this);
proviNymi = (Button) findViewById(R.id.provisionNymi);
proviNymi.setOnClickListener(this);
validateNymi = (Button) findViewById(R.id.validateNymi);
validateNymi.setOnClickListener(this);
validateNymi.setEnabled(false);
disconnectNymi = (Button) findViewById(R.id.disconnectNymi);
disconnectNymi.setOnClickListener(this);
disconnectNymi.setEnabled(false);
}
}
public void load(){
iduse = prefs.getString(Util.provID,null);
Toast.makeText(getBaseContext(), iduse , Toast.LENGTH_SHORT ).show();
keyuse = prefs.getString(Util.provKey,null);
if ((iduse!=null)||(keyuse!=null)) {
provision.id = new NclProvisionId();
provision.id.v = Base64.decode(iduse, Base64.DEFAULT);
provision.key = new NclProvisionKey();
provision.key.v = Base64.decode(keyuse, Base64.DEFAULT);
final String temp= keyuse.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "the temp provision key is " +temp , Toast.LENGTH_SHORT ).show();
}
});
}else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Provision key is null!" , Toast.LENGTH_SHORT ).show();
}
});
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == checkBlue.getId()){
// Toast.makeText(getBaseContext(), "Checking bluetooth is enabled or not!" , Toast.LENGTH_SHORT ).show();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
} else {
if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enable :)
// Toast.makeText(getBaseContext(), " bluetooth is not enabled !" , Toast.LENGTH_SHORT ).show();
isBluetoothEnabled=false;
}else {
// Toast.makeText(getBaseContext(), " bluetooth is enabled !" , Toast.LENGTH_SHORT ).show();
isBluetoothEnabled=true;
Log.d("is nabled", "blue is enalble");
}
}
}
if (v.getId()==proviNymi.getId()){
connectNymi = true;
initializeNcl();
nymiHandle = -1;
if (provisionController == null) {
provisionController = new ProvisionController(TestBluetooth.this);
}
else {
provisionController.stop();
}
provisionController.startProvision(TestBluetooth.this);
}
if (v.getId()==validateNymi.getId()){
proviNymi.setEnabled(false);
if (valiationController == null) {
valiationController = new ValidationController(TestBluetooth.this);
}
else {
valiationController.stop();
}
valiationController.startValidation(TestBluetooth.this, provisionController.getProvision());
}
if (v.getId()==disconnectNymi.getId()){
prefs = getSharedPreferences(Util.SharedPrefKey, Context.MODE_PRIVATE);
prefs.edit().clear().commit();
if (nymiHandle >= 0) {
disconnectNymi.setEnabled(false);
validateNymi.setEnabled(true);
proviNymi.setEnabled(true);
Ncl.disconnect(nymiHandle);
nymiHandle = -1;
}
}
}
/**
* Initialize the NCL library
*/
protected void initializeNcl() {
if (!nclInitialized) {
if (connectNymi) {
initializeNclForNymiBand();
}
}
}
/**
* Initialize NCL library for connecting to a Nymi Band
* #return true if the library is initialized
*/
protected boolean initializeNclForNymiBand() {
if (!nclInitialized) {
NclCallback nclCallback = new MyNclCallback();
boolean result = Ncl.init(nclCallback, null, "NCLExample", NclMode.NCL_MODE_DEFAULT, this);
if (!result) { // failed to initialize NCL
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
return false;
}
nclInitialized = true;
// nclInitialized();
}
return true;
}
#Override
public void onStartProcess(ProvisionController controller) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi start provision ..",
Toast.LENGTH_LONG).show();
}
});
}
public void save(){
final String id = Base64.encodeToString(provision.id.v, Base64.DEFAULT);
final String key = Base64.encodeToString(provision.key.v, Base64.DEFAULT);
SharedPreferences pref = getSharedPreferences(Util.SharedPrefKey, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Util.provID, id);
editor.putString(Util.provKey, key);
editor.apply();
editor.commit();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(TestBluetooth.this, id + key,
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onAgreement(final ProvisionController controller) {
nymiHandle = controller.getNymiHandle();
controller.accept();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Agree on pattern: " + Arrays.toString(controller.getLedPatterns()),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onProvisioned(final ProvisionController controller) {
nymiHandle = controller.getNymiHandle();
provision = controller.getProvision();
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
proviNymi.setEnabled(false);
validateNymi.setEnabled(true);
Toast.makeText(TestBluetooth.this, "Nymi provisioned: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
save();
}
});
}
#Override
public void onFailure(ProvisionController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi provision failed!",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onDisconnected(ProvisionController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
validateNymi.setEnabled(provision != null);
disconnectNymi.setEnabled(false);
Toast.makeText(TestBluetooth.this, "Nymi disconnected: " + provision,
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onStartProcess(ValidationController controller) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi start validation for: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFound(ValidationController controller) {
nymiHandle = controller.getNymiHandle();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi validation found Nymi on: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onValidated(ValidationController controller) {
nymiHandle = controller.getNymiHandle();
runOnUiThread(new Runnable() {
#Override
public void run() {
validateNymi.setEnabled(false);
disconnectNymi.setEnabled(true);
// HIDE THE SPINNER AFTER LOADING FEEDS
progressbar.setVisibility(View.GONE);
Toast.makeText(TestBluetooth.this, "Nymi validated!",
Toast.LENGTH_LONG).show();
prefs.edit().putBoolean(Util.isValidated, true).commit();
//move to new activity once nymi is validated
Intent intent = new Intent(TestBluetooth.this,CustomNotificationTest.class);
startActivity(intent);
}
});
}
#Override
public void onFailure(ValidationController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi validated failed!",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onDisconnected(ValidationController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
disconnectNymi.setEnabled(false);
validateNymi.setEnabled(true);
proviNymi.setEnabled(true);
Toast.makeText(TestBluetooth.this, "Nymi disconnected: " + provision,
Toast.LENGTH_LONG).show();
}
});
}
/**
* Callback for NclEventInit
*
*/
class MyNclCallback implements NclCallback {
#Override
public void call(NclEvent event, Object userData) {
Log.d(LOG_TAG, this.toString() + ": " + event.getClass().getName());
if (event instanceof NclEventInit) {
if (!((NclEventInit) event).success) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
}
}
}
}
}
Edit: After I made the NYmiAssync as inner class, I am able to run the it async using the following :
new Thread() {
public void run() {
TestBluetooth.this.runOnUiThread(new Runnable(){
#Override
public void run() {
try {
NymiAsync task = new NymiAsync();
task.execute(1, 1, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}.start();
But, I have no idea, how to make it run for every 10 seconds.
The problem is in the asynctask:
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
TestBluetooth tb=new TestBluetooth();
tb.startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
Just make the class an inner class of TestBluetooth and then just call startValidatingNymi()
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
that is because the code below in TestBlutooth:
final Handler timedThread=new Handler();
but in doInBackground you create a instance of TestBluetooth, so you get the exception
I have a task to run which takes a long time. So, I'd like to implement a progress dialog, spinning wheel, to show a message to users that the task is still running in the background. I found many solutions online and I used the following code. I ensured to run the task in separate thread. But it is not showing on UI.
OnClickListener confirmPrintButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
final SalesStockController salesStockController = new SalesStockController();
final ArrayList<ProductReload> productReloadList = reloadActivityAdapter
.getReloadList();
if (productReloadList.size() != 0) {
progressDialog = new ProgressDialog(StockReloadActivity.this);
progressDialog.setTitle("ABC Trading");
progressDialog.setMessage("Wait while loading...");
progressDialog.show();
new Thread(new Runnable() {
public void run()
{
// do the thing that takes a long time
try {
salesStockController.reload(productReloadList);
} catch (SQLiteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ABCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run()
{
progressDialog.dismiss();
}
});
}
}).start();
AlertDialog.Builder builder = new AlertDialog.Builder(
v.getContext());
builder.setCancelable(false).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
finish();
}
});
AlertDialog alert = builder.create();
alert.setTitle("ABC Trading");
alert.setMessage("Reload Successfully");
alert.show();
ReloadSlipPrint print = new ReloadSlipPrint(
productReloadList);
print.print();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
v.getContext());
builder.setCancelable(false).setPositiveButton("OK", null);
AlertDialog alert = builder.create();
alert.setTitle("ABC Trading");
alert.setMessage("No Stock To Reload");
alert.show();
}
} catch (Exception e) {
ABCUtil.displayErrorMsg(v.getContext(), e);
}
}
};
Can someone please point me out what is wrong with my code? Any help will be very much appreciated.
Just made up a simple example for you, you can try it.
public class MainActivity extends Activity {
private ProgressDialog mLoadingDialog;
private Handler mHandler = new Handler();
private void showLoadingDialog(final String title, final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
if(mLoadingDialog == null) {
mLoadingDialog = ProgressDialog.show(MainActivity.this, title, msg);
}
mLoadingDialog.setTitle(title);
mLoadingDialog.setMessage(msg);
}
});
}
private void hideLoadingDialog() {
mHandler.post(new Runnable() { //Make sure it happens in sequence after showLoadingDialog
#Override
public void run() {
if(mLoadingDialog != null) {
mLoadingDialog.dismiss();
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
#Override
public void run() {
showLoadingDialog("Loading", "Please wait...");
//DO something
hideLoadingDialog();
}
}.start();
}
}
You can use AsyncTask class to perform long runnning task
below is api link for the same
http://developer.android.com/reference/android/os/AsyncTask.html
I am having trouble with an alert dialog that I cannot hide.
when the user press a button I show a dialog that is created with this code :
new AlertDialog.Builder(this)
.setTitle(R.string.enterPassword)
.setView(textEntryView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = pwdText.getText().toString();
dialog.dismiss();
processUserAction(password,targetUri);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.
create();
There are some heavy operations performed in the 'processUserAction' method, and inside it I am using an AysncTask that displays a ProgressDialog.
The problem I am having is that the dialog prompting for the password never goes of the screen (I have tried with dismiss(), cancel()).
I guess it stays there until the onClick method is finished.
So, my question is how to close that AlertDialog, so I can show the ProgressDialog?
Another approach I have been trying is to set a DismissListener in the AlertDialog and calling the heavy operations from there, but I have had no luck ( it didn't get called ).
EDIT: Adding AsyncTask code
public class BkgCryptOperations extends AsyncTask<File,Void,Integer>{
#Override
protected Integer doInBackground(File... files) {
if (files!=null && files.length > 0){
File source = files[0];
File target = files[1];
return cryptAction.process(source,password, target);
}
return Constants.RetCodeKO;
}
CryptAction cryptAction;
String password;
ProgressDialog progressDialog;
public BkgCryptOperations (CryptAction cryptAction,String password,ProgressDialog progressDialog){
this.cryptAction=cryptAction;
this.password=password;
this.progressDialog=progressDialog;
}
#Override
protected void onPreExecute() {
if (progressDialog!=null){
progressDialog.show();
}
}
protected void onPostExecute(Integer i) {
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
Thanks in advance
Here is a excample how I do it:
public void daten_remove_on_click(View button) {
// Nachfragen
if (spinadapter.getCount() > 0) {
AlertDialog Result = new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(getString(R.string.dialog_data_remove_titel))
.setMessage(getString(R.string.dialog_data_remove_text))
.setNegativeButton(getString(R.string.dialog_no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
// Nicht löschen
dialogInterface.cancel();
}
})
.setPositiveButton(getString(R.string.dialog_yes),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
String _quellenName = myCursor.getString(1);
deleteQuellenRecord(_quellenName);
zuletztGelöscht = _quellenName;
}
}).show();
} else {
// Keine Daten mehr vorhanden
Toast toast = Toast.makeText(Daten.this,
getString(R.string.dialog_data_remove_empty),
Toast.LENGTH_SHORT);
toast.show();
}
}
Here is the code of deleteQuellenRecord:
private void deleteQuellenRecord(String _quellenName) {
String DialogTitel = getString(R.string.daten_delete_titel);
String DialogText = getString(R.string.daten_delete_text);
// Dialogdefinition Prograssbar
dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// set the maximum value
dialog.setMax(4);
// display the progressbar
increment = 1;
dialog.show();
// Thread starten
new Thread(new MyDeleteDataThread(_quellenName)) {
#Override
public void run() {
try {
// Datensatz löschen
myDB.execSQL("DELETE ... ');");
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...);");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...;");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
// Einstellung speichern
try {
settings.edit().putString("LetzteQuelle", "-1")
.commit();
} catch (Exception ex) {
settings.edit().putString("LetzteQuelle", "").commit();
}
} catch (Exception ex) {
// Wait dialog beenden
dialog.dismiss();
Log.e("Glutenfrei Viewer",
"Error in activity MAIN - remove data", ex); // log
// the
// error
}
// Wait dialog beenden
dialog.dismiss();
}
}.start();
this.onCreate(null);
}
Wiht Async Task I do it this way:
private class RunningAlternativSearch extends
AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(SearchResult.this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
#Override
protected void onPreExecute() {
alternativeSucheBeendet = false;
String DialogTitel = getString(R.string.daten_wait_titel);
DialogText = getString(R.string.dialog_alternativ_text);
DialogZweiteChance = getString(R.string.dialog_zweite_chance);
DialogDritteChance = getString(R.string.dialog_dritte_chance);
sucheNach = getString(R.string.dialog_suche_nach);
dialog.setCancelable(true);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
cancleBarcodeWorker();
if (alternativeSucheBeendet==false){
// Activity nur beenden wenn die Suche
// nicht beendet wurde, also vom User abgebrochen
Toast toast = Toast.makeText(SearchResult.this, SearchResult.this
.getString(R.string.toast_suche_abgebrochen),
Toast.LENGTH_LONG);
toast.show();
myDB.close();
SearchResult.this.finish();
}
}
});
dialog.show();
}
...
Can you show the code for processUserAction(..)? There is no need to include the dismiss.
I did something very similar and had no problems...
Here's the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Export data.\nContinue?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String file = getObra().getNome();
d = new ProgressDialog(MenuActivity.this);
d.setTitle("Exporting...");
d.setMessage("please wait...");
d.setIndeterminate(true);
d.setCancelable(false);
d.show();
export(file);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In export(file) I open the thread:
private void export(final String file) {
new Thread() {
public void run() {
try {
ExportData ede = new ExportData(
getApplicationContext(), getPmo().getId(),
file);
ede.export();
handlerMessage("Done!!");
} catch (Exception e) {
handlerMessage(e.getMessage());
System.out.println("ERROR!!!" + e.getMessage());
}
}
}.start();
}
In handlerMessage I dismiss the progressDialog and show the final message.
Hope it helps you.
You could create a listener outside of the AlertDialog, to abstract out the logic within the OnClickListener for the positive button. That way, the listener can be notified, and the AlertDialog will be dismissed immediately. Then, whatever processing of the user's input from the AlertDialog can take place independently of the AlertDialog. I'm not sure if this is the best way to accomplish this or not, but it's worked well for me in the past.
As far as I can tell, I don't see any obvious problems with your AsyncTask code.
public interface IPasswordListener {
public void onReceivePassword(String password);
}
IPasswordListener m_passwordListener = new IPasswordListener {
#Override
public void onReceivePassword(String password) {
processUserAction(password,targetUri);
}
}
public void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.enterPassword);
builder.setView(textEntryView);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
m_passwordListener.onReceivePassword(pwdText.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
}