AsyncTask class not responding inside AlertDialog - android

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.

Related

How show AlertDialog with AsyncTask

i'am trying develop a game in android that, when my doll crash with a bottle in a screen, show a Dialog with 2 options but i don't know...
public void whenDollCrash(Grafico elementofaba,Grafico elementoBotella){
if((elementofaba.getPosX()+elementofaba.getAncho()>=elementoBotella.getPosX()+15)&&
(elementofaba.getPosX()+elementofaba.getAncho() <= elementoBotella.getPosX()+elementoBotella.getAncho()+15)&&
(elementofaba.getPosY()+elementofaba.getAlto()>=elementoBotella.getPosY())
&& (elementofaba.getPosY()+elementofaba.getAlto() <= elementoBotella.getPosY()+elementoBotella.getAlto())){
juego.detener();
hiloFaba.detener();
sonidoJuego.stop();
golpe.start();
Async a= main.new Async();
a.execute();
Log.i("parada", "esto furruca");
}
and my class AsyncTask is the next.
public class Async extends AsyncTask{
AlertDialog.Builder builder;
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
builder =
new AlertDialog.Builder(MainActivity.this);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
builder.setMessage("¿Confirma la acción seleccionada?")
.setTitle("Confirmacion")
.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
Help me!!
In the logCat always shows NullPointerException
This guy looks really suspicious
Async a= main.new Async();
You should use something like this
public class Async extends AsyncTask<Void, Void, Void> {
AlertDialog.Builder builder;
WeakReference<Activity> activityWeakRef;
public Async(Activity context) {
activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (activityWeakRef != null && activityWeakRef.get() != null) {
builder = new AlertDialog.Builder(activityWeakRef.get());
builder.setMessage("¿Confirma la acción seleccionada?").setTitle("Confirmacion").setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
}
}
and use it like this in your custom view
Async a = new Async((Activity) getContext());
a.execute()

Set Progress Dialog properly in asynctask

I currently trying to show a progress dialog on OnclickListener of a Dialogbox since my items are taking too long to fetch from Server.
I use Async task as suggested here (Android progress dialog) and this post (android problem with progress dialog) to show progress dialog The progress dialog is shown , however the code returns exception when it goes to do background that " Looper is not set". And when I set looper nothing happens.
I am not sure at this stage what is it that I am doing wrong.
public void firstMethod()
{
final CustomObj obj = getCustomObj();//not imp
Messages.getInstance().showAlert(MainActivity.this, "message", false, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
}, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
gotoAnotherPge(obj);
}
});
}
public void gotoAnotherPge(final CustomObject obj)
{
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
new AsyncTask<Object, Object, Boolean>()
{
protected void onPreExecute()
{
pd.setMessage(String.format(Statics.getText(MainActivity.this, R.raw.dictionary, "subscriptions_loading_unsubscribing")));
pd.show();
}
protected Boolean doInBackground(Object... params)
{
try{
Looper.prepare();
final LocalPopulator lp = new LocalPopulator(MainActivity.this, 0)
{
#Override
public void populate()
{
List<Serializable> items = Arrays.asList(getItemHere(obj));
List<Serializable> listItems = new ArrayList<Serializable>();
listItems.addAll(items);
Serializable[] sItems = listItems.toArray(new Serializable[menuItems.size()]);
result = sItems;
}
};
showNextPage(true, 1, 0, lp);
Looper.loop();
}catch (Exception e){
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
return true;
}
protected void onPostExecute(Boolean result)
{
pd.dismiss();
}
};
MainActivity.this.runOnUiThread (new Runnable()
{
#Override
public void run()
{
// dismiss the progressdialog
pd.dismiss();
}
});
}

Android ProgressDialog doesn't show

I create an AlertDialog to let the user choose if download something from the server.
If the user choose to download, the AlertDialog is dismissed, and came up a ProgressDialog connected to a AsyncTask.
The ProgressDialog is never showed. The "ok" button of AlertDialog remains selected until the end of the operations of the AsyncTask.
If I "comment" the AsyncTask operation in the code, the AlertDialog is correctly dismissed, and the ProgressDialog shows up.
I haven't tried the application on a real device, but only the simulator.
Which is the problem?
Try this code this may help you
private class allinfo extends AsyncTask<String, Void, JSONObject> {
private ProgressDialog dialog;
protected void onPreExecute(){
dialog = ProgressDialog.show(collection.this, "Loading", "Loading. Please wait...", true,false);
}
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
return json;
}
protected void onPostExecute(JSONObject json)
{
dialog.dismiss();
info(json);
}
}
final AlertDialog d = new AlertDialog.Builder(youclassname.this)
.setView(input)
.setTitle(R.string.message)
.setPositiveButton(android.R.string.ok,
new Dialog.OnClickListener() {
public void onClick(DialogInterface d, int which) {
//Do nothing here. We override the onclick
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
d.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startDownload();//begin downloading
d.dismiss();
}
});
}
});
d.show();
here is startDownload part.
private void startDownload() {
String url ="file download link";
Toast.makeText(dwn.this, url,Toast.LENGTH_LONG).show();
new DownloadFileAsync().execute(url);
}
here is the asynctask
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file.type");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
here is the code for progress dialog
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading PDF file");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
ProgressDialog implementation in AsyncTask example using AlertDialog positive button:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to go to AsyncTask!")
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
new MyAsyncTaskClass().execute();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// Here is the start of the AsyncTask
class MyAsyncTaskClass extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
progressDialog.setMessage("Dialog Message");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
}
#Override
protected Void doInBackground(String... params) {
// TODO stuff
}
protected void onPostExecute(Void v) {
this.progressDialog.dismiss();
}
}
}

ProgresDialog doesn't show up

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()

Android - How to make some validations in sequence

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();
}
}
}

Categories

Resources