public Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.ctx = this;
//another code......)
send = (Button)findViewById(R.id.wyslij_zapytanie_ofertowe);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ProgressDialog dialog = ProgressDialog.show(ctx, "Loading", "Please wait...", true);
try {
GMailSender sender = new GMailSender("dasdda#gmail.com", "ddx");
sender.sendMail("This is Subject",
"This is Body",
"staxxxowe#gmail.com",
"xxxyk#gmail.com");
dialog.dismiss();
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
dialog.dismiss();
}
}
});
I try also instead ctx put ClassName.class and also doesn't work. Any one have idea how to solve this problem?
Most likely your problem is that you call dialog.dismiss(); "immediately" after you call dialog.show() and this may cause this "not showing" efect.
dialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Its probably getting dismissed even before it gets created since only a few lines later you call dialog.dismiss()
Related
I am trying to do a file download using the below code. Everything works fine as far as the download is concerned. One problem I have is whenever there is a download failure, progress dialog does not show up. Am I missing anything obvious here? What is the cause for this?
Any help is much appreciated
public void onButtonClick(View view) {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Downloading File");
mDialog.setCancelable(false);
mDialog.show();// Does not show during download exceptions- is it because the below download code fails abruptly?
new NTLMTestData ().asyncNTLMTest("http://myurl/FileName.csv", this, getApplicationContext());
}
// The below call backs get fired from async
#Override
public void onSuccess(String msg) {
mDialog.dismiss();
}
#Override
public void onFailure(Exception ex) {
mDialog.dismiss();
}
Try this way instead
public void onButtonClick(View view) {
try{
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Downloading File");
mDialog.setCancelable(false);
mDialog.show();
new NTLMTestData ().asyncNTLMTest("http://myurl/FileName.csv", this,
getApplicationContext());
} catch (Exception e){
showError();
}
}
private void showError(){
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setTitle("Error")
mDialog.setMessage("An error has occurred during download");
mDialog.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mDialog.dismiss();
}
})
mDialog.setCancelable(false);
mDialog.show();
}
// The below call backs get fired from async
#Override
public void onSuccess(String msg) {
mDialog.dismiss();
}
#Override
public void onFailure(Exception ex) {
//Leave blank
}
Hope it helps
I am trying to show a custom dialog within Activity and this error occur. I know why this error occur from here and here and also know it's solution. But the problem is I can't find the problem in my code. I've spent anlot of time in finding the error with no luck.
I've called below method on button click
public void changePassword(View view){
DialogChangePassword dialogChangePassword = new DialogChangePassword(ActivityMyAccount.this);
dialogChangePassword.show();
Window window = dialogChangePassword.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
I am showing the dialog here while Activity should live. My question;
I can't dismiss the dialog here, I am dismissing it from within Dialog class.
I am not finishing the activity. If error occurs because the activity is finishing, why is it finishing?
If error is not because of finishing the activity then why does this error occur?
I have a NetworkOperation to be performed in Dialog class, does it have to do something with that?
Here is my Dialog class
public class DialogChangePassword extends Dialog {
Context context;
Button confirm, cancel;
CustomEditText edtOldPwd, edtNewPwd, edtConfirmNewPwd;
ProgressDialog progressDialog;
String PASSWORD_INCORRECT_MESSAGE = "Old password is incorrect.";
public DialogChangePassword(Context context) {
super(context);
this.context = context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_change_password);
if(progressDialog != null)
progressDialog = null;
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Please wait...");
progressDialog.setMessage("Updating Password.");
progressDialog.show();
confirm = (Button) findViewById(R.id.btnChangePassword);
cancel = (Button) findViewById(R.id.btnCancel);
edtOldPwd = (CustomEditText) findViewById(R.id.edtOldPassword);
edtNewPwd = (CustomEditText) findViewById(R.id.edtNewPassword);
edtConfirmNewPwd = (CustomEditText) findViewById(R.id.edtConfirmNewPassword);
edtConfirmNewPwd.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!edtNewPwd.getText().toString().equals(edtConfirmNewPwd.getText().toString()))
edtConfirmNewPwd.setError("Password doesn't match");
}
});
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!edtNewPwd.getText().toString().equals(edtConfirmNewPwd.getText().toString())) {
Toast.makeText(context, "Password doesn't match", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
return;
}
HashMap<String, String> params = new HashMap<>();
params.put("email", Utility.classUser.getEmailId());
params.put("password", edtOldPwd.getText().toString());
params.put("newPassword", edtNewPwd.getText().toString());
new NetworkOperation().execute(params);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
}
private class NetworkOperation extends AsyncTask<HashMap<String,String>, Void, String> {
#Override
protected String doInBackground(HashMap<String, String>... params) {
try {
ClassAPIRoutes routes = ClassAPIRoutes.initializeRoutes();
return routes.editUserPassword(params[0]);
} catch (final IOException e) {
e.printStackTrace();
getOwnerActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
});
return "error";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.cancel();
dismiss();
if(!s.equals("error")){
JSONObject jsonObject;
try {
jsonObject = new JSONObject(s);
if (jsonObject.get("success").toString().equals("true")) {
Toast.makeText(context, "Password successfully changed.", Toast.LENGTH_SHORT).show();
dismiss();
} else if (jsonObject.get("success").toString().equals("false")) {
if (jsonObject.get("message").toString().equals(PASSWORD_INCORRECT_MESSAGE)) {
Toast.makeText(context, PASSWORD_INCORRECT_MESSAGE, Toast.LENGTH_SHORT).show();
resetFields();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
}
}
}
}
private void resetFields(){
edtOldPwd.setText("");
edtNewPwd.setText("");
edtConfirmNewPwd.setText("");
}
}
I've removed showing progress dialog from onCreate(...) and put it in Async class inside OnPreExecute(...) and it's working fine
I am trying to run login class inside AlertDialog but no result as expected even no logcat error for login class. Hope someone can help me.
public class MainActivity extends Activity
//Inflation
button1= (Button)findViewById(R.id.btnOrderSubmit);
textView1= = (TextView)findViewById(R.id.editenquiry);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Intent method
}
});
//OnclickListener for TextView
textView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder login = new AlertDialog.Builder(MainActivity.this);
login.setMessage("For Enquiry, Please Login");
login.setPositiveButton("Log In", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
enquirylogin();
}
});
login.setNegativeButton("Continue", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int arg1) {
//Intent here
}
});
login.show();
}
private void enquirylogin() {
// TODO Auto-generated method stub
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View promptsView = li.inflate(R.layout.enqlogin, null);
AlertDialog.Builder enqLogin = new AlertDialog.Builder(MainActivity.this);
enqLogin.setView(promptsView);
enusername=(EditText) promptsView.findViewById(R.id.enqusername);
enpassword=(EditText) promptsView.findViewById(R.id.enqpassword);
enqLogin.setCancelable(true);
enqLogin.setMessage("Please Login Now");
enqLogin.setPositiveButton("Submit",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
new ELogin();
}
});
enqLogin.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
enqLogin.show();
}
Alertdialog contains promptsView where Elogin class is calling
class ELogin extends AsyncTask<String, JSONObject, JSONObject>{
ProgressDialog pDialog;
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
}
protected JSONObject doInBackground(String... arg0) {
strELogin=enusername.getText().toString();
strEPassword=enpassword.getText().toString();
//String response =null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("txtUName", strELogin));
params.add(new BasicNameValuePair("txtPass", strEPassword));
JSONObject json = jsonParser.makeHttpRequest (LOGIN_URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
try {
pDialog.dismiss();
int success = result.getInt(TAG_SUCCESS);
if(success == 1) {
Log.d("Login Successful!", result.toString());
Toast.makeText(MainActivity.this, "Authentication Success",Toast.LENGTH_LONG).show();
String role_rs = result.getString(TAG_ROLE_RS);
String role_id = result.getString(TAG_CID_RS);
}else{
Toast.makeText(MainActivity.this, "try again!!!!!!", Toast.LENGTH_LONG).show();
Log.d("try Again!", result.getString(TAG_MESSAGE));
}
}catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
});
}
When creating a new instance of ELogin, you should call .execute() on it to start the task.
The official docs tells you about all the things of threading and AsyncTasks: http://developer.android.com/guide/components/processes-and-threads.html.
Missing below:
new ELogin().execute();
You must have to execute() your ASYNC task.
Hope this will help you.
I need to do some validations sequentially and some of them involve complex database operations.
So, I need to do this in a separated thread of UI Thread, ok?
But some validations show messages to user, what need confirmation and
when user confirm, the next validation should be call.
This code example explains what I want to implement:
void makeValidation1(){
if(condition1Valid()){
makeValidation2();
}else{
DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
makeValidation2();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("really want to do this?")
.setPositiveButton("Yes", onClick);
builder.create().show();
}
}
void makeValidation2(){
if(condition2Valid()){
}else{
//...
}
}
boolean condition1Valid() {
// complex database Operations
return false;
}
boolean condition2Valid() {
//complex database Operations
return false;
}
//...
void makeValidation9(){
//...
}
My question is: What the best way/pattern to implement this?
1 - Create one asyncTask for each validation? (I cant create only one AsyncTask, because confirmation messages can stop flux).
2 - Create a Runnable for each validation and create thread to run that when need call next validation?
3 - ???
edit
I tested this code #BinaryBazooka, but isnt work. Any help?
public class MainActivity extends Activity implements OnClickListener {
Thread mThread;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Start");
setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mThread = new Thread(new Runnable() {
#Override
public void run() {
validations();
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Start Thread?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.show();
mThread.run();
}
});
builder.create().show();
}
void validations(){
//this method go on separated thread
validation1();
validation2();
validation3();
}
void validation1(){
if(true){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Validation 1 failed. Go validation 2?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
//if user confirm, continue validation thread
mThread.notify();
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//if user cancel, stop validation thread
mThread.interrupt();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (mThread) {
//wait for user confirmation
mThread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation2() {
if(true){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("validacao 2 failed. Go validation 3?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
mThread.notify();
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
mThread.interrupt();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (mThread) {
mThread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation3() {
Log.i("TAG", "<<<<<<<<<< >>>>>>>>>>>>");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT);
}
});
}
}
I would create a new thread and sleep it during these dialog calls, you can access the UI directly from within your runnable with..
runOnUiThread(new Runnable() {
public void run() {}
});
So something like..
Thread someThread = new Thread(new Runnable() {
#Override
public void run(){
runOnUiThread(new Runnable() {
public void run()
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.msg);
builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
someThread.notify();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
someThread.wait();
Works with AsyncTask. Ty.
Code:
public class MainActivity extends Activity implements OnClickListener {
//Thread mThread;
ProgressDialog mProgressDialog;
private ValidationsAsyncTask async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Start");
setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Start Thread?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.show();
async = new ValidationsAsyncTask();
async.execute();
}
});
builder.create().show();
}
void validation1(){
if(true){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Validation 1 failed. Go validation 2?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
//if user confirm, continue validation thread
synchronized (async) {
async.notify();
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//if user cancel, stop validation thread
async.cancel(true);
}
});
mProgressDialog.hide();
builder.create().show();
}
});
Log.i("TAG - validation1", Thread.currentThread().getName());
try {
synchronized (async) {
//wait for user confirmation
async.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation2() {
if(true){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("validacao 2 failed. Go validation 3?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
synchronized (async) {
async.notify();
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
async.cancel(true);
}
});
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (async) {
async.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation3() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT).show();
}
});
}
class ValidationsAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
validation1();
validation2();
validation3();
return null;
}
#Override
protected void onCancelled() {
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_LONG).show();
}
}
}
I wanted to display an Alert Dialogue inside thread or alternatively such a way that AlertDialogue opens up directly after finding some records in database negative, w/o clicking on any button..
Alert dialogue may contain Few lines and 2-3 buttons..
referred following link and tried on my own but not getting how to create an AlertDialogue without using onClickListener as its working with it(onClickListener) very smoothly:
http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog
Thanks in Advance.
public class jar_layut extends Activity {
/** Called when the activity is first created. */
boolean out=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new Runnable()
{ public void run()
{
try {
out=first_check_pic_on_device();
mHandlerMySpace5.post(mUpdateResultsMySpace5);
} catch (Exception e) {
// TODO Auto-generated catch block
mHandlerMySpace5.post(mUpdateResultsMySpace5);
}
}
} ).start();
}
private boolean first_check_pic_on_device()
{
Context contextMySpace= this;;
try {
FileInputStream stream =contextMySpace.openFileInput("prf.png");
try {
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
return false;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
}
}
final Handler mHandlerMySpace5 = new Handler();
final Runnable mUpdateResultsMySpace5 = new Runnable() {
public void run() {
if(!out)
{
showDialog();
}
}
};
private void showDialog()
{
final CharSequence[] items = {"one", "two"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(item==0)
{
}
if(item==1)
{
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
check out the below link
http://developer.android.com/guide/topics/ui/dialogs.html ---> expand(click) on "Example ProgressDialog with a second thread". This will solve your problem.