Set timeout function with AsyncTask [Android] - android

In my case, I would like to get the button pressed and get process with the timeout. When button clicked then it will verify the accNo with web services, if the verification (ProgressDialog) is over 5 seconds then it will stop and display the alertDialog to notice user "Timeout".
But now I have not idea when I in testing with 1 milliseconds, in logically it will pause in alertDialog until get pressed, but now it will display the dialog in milliseconds then auto dismiss and intent to next activity. Here is my code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information3);
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title.getText().toString().equals("INFO")) {
InfoAsyncTask infoAsyncTask = new InfoAsyncTask();
try {
infoAsyncTask.execute().get(1, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Verify Timeout. Please try again.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
});
}
private class InfoAsyncTask extends AsyncTask<Void, Void, String> {
private String results;
private ProgressDialog pDialog;
private Object resultRequestSOAP;
String accNo = et_accNo.getText().toString().trim();
int timeout = 15000;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Information3.this);
pDialog.setMessage("Verifying...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Code", InfoCode);
request.addProperty("AccNo", accNo);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, timeout);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
String requestDumpString = androidHttpTransport.requestDump;
Log.d("request Dump: ", requestDumpString);
} catch (Exception e) {
e.printStackTrace();
}
try {
resultRequestSOAP = envelope.getResponse();
results = resultRequestSOAP.toString();
Log.d("Output: ", results);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
if (resultRequestSOAP == null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Connection error, please check your internet connection.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
pDialog.dismiss();
}
} else {
if (results.equals("false")) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in correct account number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_billNo.getText().toString().trim().isEmpty()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in bill number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_amountNo.getText().toString().trim().isEmpty() || Integer.parseInt(et_amountNo.getText().toString().trim()) <= 0) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in amount");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (results.equals("true")) {
Title = title.getText().toString();
String value1 = et_accNo.getText().toString().trim();
String value2 = et_billNo.getText().toString().trim();
int value3 = Integer.parseInt(et_amountNo.getText().toString().trim());
addSearchInput(value1);
addSearchInput(value2);
addSearchInput(String.valueOf(value3));
Intent intent = new Intent(Information3.this, confirmation3.class);
intent.putExtra("name", Title);
intent.putExtra("value1", value1);
intent.putExtra("value2", value2);
intent.putExtra("value3", value3);
startActivity(intent);
} else {
super.onPreExecute();
}
pDialog.dismiss();
}
}
}

get() method will block the UI thread and I guess you don't want this.
You should implement cancel mechanics in doInBackground and call AsyncTask.cancel() by timeout [like that](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long))
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
AsyncTask.cancel();
}
}, 1);
Be aware there are many gotchas with AsyncTask, check my article.

Related

android print "connection timeout" when timeout in loopj

android I finding more but none of get solution..
when occur time out in loopj , I want print Time-out message..
Follow code for time-out which I used.
private static final int DEFAULT_TIMEOUT = 15 * 1000;
private static AsyncHttpClient client = new AsyncHttpClient();
public static void setTimeOutTime() {
client.setTimeout(DEFAULT_TIMEOUT);
System.out.println("timeout");
}
try {
response = client.newCall(request).execute();
jsonObj = new JSONObject(response.body().string());
} catch (IOException e) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (getStatus() == Status.RUNNING) {
cancel(true);
if(!hiddenDialog) {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle("Timeout error")
.setMessage("Sorry server doesn't response!\nCheck your internet connection and try again.")
.setCancelable(true)
.setPositiveButton("Try again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Log.d(TAG, "load again");
}
}).setIcon(R.drawable.ic_dialog_alert_dark);
AlertDialog alert = builder.create();
alert.show();
}
});
} catch (JSONException e) {}
EDIT
for your case it should be the same way
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// make toast
}
});

Use parse.com in android app

I'm new in android developer and I use parse.com in my first android app.
My problem is when the user singup to the app, the user save in the core. but then the app crashes.
This is my code:
save = (Button) findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(password.getText().toString().equals(againPassword.getText().toString()))) {
Toast.makeText(getApplicationContext(), "You have mistake in password!", Toast.LENGTH_SHORT).show();
} else {
ParseUser newUser = new ParseUser();
newUser.put("name", firstName.getText().toString());
newUser.put("lastName", lastName.getText().toString());
newUser.setEmail(email.getText().toString());
newUser.setUsername(userName.getText().toString());
newUser.setPassword(password.getText().toString());
newUser.put("rosterArray", rosterArray);
myParse parse = new myParse();
try {
parse.saveUserInParse(newUser);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
});
The code of methed 'saveUserInParse' is
public void saveUserInParse(ParseUser newUser)
{
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
AlertDialog.Builder singUpSucceed = new AlertDialog.Builder(context);
singUpSucceed.setTitle("Sing up succeed!!!");
singUpSucceed.setCancelable(true);
singUpSucceed.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = singUpSucceed.create();
alert11.show();
} else {
String theMessage = e.getMessage();
AlertDialog.Builder singUpSucceed = new AlertDialog.Builder(context);
singUpSucceed.setTitle("Sing up feild!!!");
singUpSucceed.setMessage(theMessage);
singUpSucceed.setCancelable(true);
singUpSucceed.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = singUpSucceed.create();
alert11.show();
}
}
});
}
What did I do wrong? This problam is also in login method.
Thank you.
Here is my demo project for parse Sample Parse, you an use for refrence.

progressDialog didn't show with several views in one activity

I created 3 views in one activity depending on the process of the workflow.
i.e. viewA->viewB->viewC, then on viewC, when I do HTTP-POST(using AsyncTask), show progress dialog.
I tried 2 ways to show progress dialog:
using runOnUiThread() to show progressDialog, it didn't show.
write show progressDialog code in AsyncTask. Make progress dialog show in onPreExecute() and dismiss in onPostExecute(), it shows after doinbackground task, and onPostExecute() didn't execute as well.
Anyone can help?
Thanks
sam
Here is the main activity code:
public void setA(){
setContentView(R.layout.a_fm);
Button aNextBtn=(Button)findViewById(R.id.aNextBtn);
aNextBtn.setOnClickListener(this);
}
public void setB(){
setContentView(R.layout.b_fm);
Button bNextBtn=(Button)findViewById(R.id.bNextBtn);
bNextBtn.setOnClickListener(this);
}
public void setC(){
setContentView(R.layout.c_fm);
Button cNextBtn=(Button)findViewById(R.id.cNextBtn);
cNextBtn.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.aNextBtn:
setB();
break;
case R.id.bNextBtn:
setB();
break;
case R.id.cNextBtn:
postmsg();
break;
}
}
public void postmsg(final Info info)
{
postDialog=new ProgressDialog(AssistFm.this);
postDialog.setMessage(getString(R.string.alert_sendmsg_sending));
postDialog.show();
this.runOnUiThread(new Runnable() {#Override
public void run() {
// TODO Auto-generated method stub
send_online=sendlogtowebservice(info);
SEND_COUNT++;
if (send_online)
{
postDialog.dismiss();
AlertDialog.Builder builder = new Builder(A_activity.this);
builder.setMessage(getString(R.string.alert_sendmsg_success));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setA();
SEND_COUNT=0;
}
});
builder.create().show();
}
else
{
postDialog.dismiss();
if (SEND_COUNT<SEND_COUNT_MAX)
{
AlertDialog.Builder builder = new Builder(A_activity.this);
builder.setMessage(getString(R.string.alert_sendmsg_retry));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
postmsg(info);
SEND_COUNT++;
}
});
builder.create().show();
}
else
{
AlertDialog.Builder builder = new Builder(AssistFm.this);
builder.setMessage(getString(R.string.alert_sendmsg_error));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setA();
}
});
builder.create().show();
}
}
}
});
}
private boolean sendlogtowebservice(Info info) {
boolean isTrue = false;
int result_code = 0;
Object []param = new Object[3];
HttpResponse response = null;
String result_str;
try {
String sURL=url;
HttpClient client = new DefaultHttpClient();
ArrayList<BasicNameValuePair> paierList = new ArrayList<BasicNameValuePair>();
paierList.add(new BasicNameValuePair("person_firstname", info.person_firstname));
paierList.add(new BasicNameValuePair("person_lastname", info.person_lastname));
paierList.add(new BasicNameValuePair("person_mobile", info.person_mobile));
param[0] = sURL;
param[1] = paierList;
param[2] = client;
AsyncTask<Object, Object, HttpResponse> res = new HttpReqTask().execute(param);
response = (HttpResponse) res.get();
result_code=response.getStatusLine().getStatusCode();
result_str = EntityUtils.toString(response.getEntity());
if ( result_str.equals("00"))
{
isTrue = true;
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e)
{
Log.e("HttpAPI.callHttpPost()", "Error", e);
}
return isTrue;
};
Here is the HTTP-POST AsyncTask code:
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.HTTP;
import android.os.AsyncTask;
public class HttpReqTask extends AsyncTask<Object, Object, HttpResponse>{
#Override
protected HttpResponse doInBackground(Object... params){
String url = (String)params[0];
ArrayList<NameValuePair> paierList = (ArrayList<NameValuePair>)params[1];
HttpClient httpclient = (HttpClient)params[2];
HttpPost request = new HttpPost(url);
HttpResponse response = null;
try {
request.setEntity(new UrlEncodedFormEntity(paierList, HTTP.UTF_8));
response = httpclient.execute(request);
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
}
No one know how this happened?
I changed the AsyncTask to below, the progress dialog just show a flush away when it is trying to dismiss the progress dialog.
public class HttpReqTask extends AsyncTask<Object, Object, HttpResponse>{
private Context mCtx;
private ProgressDialog progressDialog;
public HttpReqTask(Context context){
myLog.i("HttpReqTask constructor, before show dialog!");
progressDialog = new ProgressDialog(mCtx);
progressDialog.setMessage("Your progress dialog message...");
progressDialog.show();
myLog.i("HttpReqTask constructor finish, start show dialog!");
}
#Override
protected HttpResponse doInBackground(Object... params){
myLog.i("do in background execute");
String url = (String)params[0];
ArrayList<NameValuePair> paierList = (ArrayList<NameValuePair>)params[1];
HttpClient httpclient = (HttpClient)params[2];
String s=null;
HttpPost request = new HttpPost(url);
HttpResponse response = null;
try {
request.setEntity(new UrlEncodedFormEntity(paierList, HTTP.UTF_8));
response = httpclient.execute(request);
//add for longer process time.
for (int i=0;i<10000000;i++)
{
s="a";
}
} catch (Exception e) {
throw new RuntimeException(e);
}
myLog.i("finish in background execute");
return response;
}
#Override
protected void onPostExecute(HttpResponse result) {
myLog.i("HttpReqTask onPostExecute(), before dismiss dialog!");
if (progressDialog!=null) progressDialog.dismiss();
myLog.i("HttpReqTask onPostExecute(), after dismiss dialog!");
}
}
It seems no one knows the answer...
Under my research, I can make the progessDialog shown by creating a new thread, however the AlertDialog in the new thread, can not be shown now...
public void postmsg(final OnlineHistoryInfo info)
{
dialog=new ProgressDialog(mActivity.this);
dialog.setMessage(getString(R.string.alert_sendmsg_sending));
dialog.setCancelable(false);
dialog.show();
myLog.i("dialog show!");
new Thread(){
#Override
public void run()
{
try
{
myLog.i("new thread: run!");
// TODO Auto-generated method stub
send=sendlogtowebservice(info);
//send_online=true;
SEND_COUNT++;
}
finally
{
dialog.dismiss();
if (send)
{
myLog.i("send:true!");
new DataRule(AssistFm.this).saveOnlineHistory(info);
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_success));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setA();
SEND_COUNT=0;
}
});
builder.create().show();
}
else
{
myLog.i("send:false!");
if (SEND_COUNT<SEND_COUNT_MAX)
{
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_retry));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
postmsg(info);
SEND_COUNT++;
}
});
builder.create().show();
}
else
{
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_error));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setA();
}
});
builder.create().show();
}
}
}
}
}.start();
}//postmsg() finish

how can open alert dialog box in android

I want to open alert dialog box after successfully submitted data.
I am using following code but not work.
dialog = ProgressDialog.show(TanantDetails.this, "", "Please Wait...", true);
new Thread(new Runnable() {
public void run() {
String response;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences sp=getSharedPreferences("login",MODE_WORLD_READABLE);
try {
Utility utility=new Utility();
//
new_url=url+mobile_no.getText().toString();
response = utility.getResponse(utility.urlEncode(new_url));
dialog.dismiss();
if (response.equals("Success"))
{
AlertDialog alertbox = new AlertDialog.Builder(getBaseContext())
//.setIcon(R.drawable.no)
.setTitle("Submit successfully")
.setMessage("“Police will verify documents between preferred timing")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
TanantDetails.this.finish();
Intent i=new Intent(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);
}
})
.show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}).start();
}
toast show the message response success.
I am new to android
Simple Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Alert")
.setTitle("Warning");
AlertDialog alert =builder.create();
alert.show();
If you want to add ok, cancel buttons then add
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked cancel button
}
});
Try this code:
new AlertDialog.Builder(this)
.setTitle("Your title")
.setMessage("Your message")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
Your alert dialog needs to be displayed on the UI thread. The code you are running is on a separate thread. In most cases when you want to update a UI element while in a separate thread it is done by using runOnUiThread()
Please see the code below
if (response.equals("Success"))
{
runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog alertbox = new AlertDialog.Builder(getBaseContext())
//.setIcon(R.drawable.no)
.setTitle("Submit successfully")
.setMessage("“Police will verify documents between preferred timing")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
TanantDetails.this.finish();
Intent i=new Intent(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);
}
}).show();
}
});
}

Displaying a custom AlertDialog in Android while catching an Exception

I'm trying to display an alert message for the users in a catch block. The difference is that my try/catch is inside the onCreate() from the main activity, so it's executed as soon as the application is opened.
I've tried this (I have an OnClick() for Dialogs in the end of the Activity with dialog.dismiss() and this.finish() after):
catch (SQLException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.label_title_error))
.setIcon(R.drawable.error_icon)
.setMessage(getString(R.string.msg_error_sql))
.setPositiveButton(getString(R.string.label_ok), this);
AlertDialog dialogSQL = builder.create();
dialogSQL.show();
e.printStackTrace();
}
and I also tried this:
catch (NumberFormatException e) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(getString(R.string.label_title_error));
dialog.setIcon(R.drawable.error_icon);
dialog.setMessage(getString(R.string.msg_error_numberformat));
dialog.setNeutralButton(getString(R.string.label_ok), null);
dialog.create().show();
e.printStackTrace();
}
Forced the exceptions while debugging and I can see that it simply catches the exception, displays in the LogCat (as warning) and keep with the flow until it hits another untreated exception and then display that default "Sorry!/Force Close" Android dialog. And there are no other exceptions related to the dialog in the LogCat.
Why it does not display my custom AlertDialogs for the catch? I thought about the context that the Builder needs, but if the super() from onCreate() is before this code so why it does displays the message?
Thanks Everyone.
UPDATE: Ok, as requested, here goes more code.
public class PinActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener{
private Facade facade = null;
public static int INSERT_SAL = 0;
public static int INSERT_OK = 1;
public static int INSERT_CANCEL = 2;
EditText edtIniPin;
TextView txtSelecPin;
TextView txtCancPin;
int pinMaxLengthInt;
private String[] serviceNames;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v("FLUXO", "PIN -->> ON CREATE");
super.onCreate(savedInstanceState);
facade = Facade.getInstance();
try {
serviceNames = facade.loadApplication(this);
facade.loadParameters(0);
setContentView(R.layout.pin_screen);
//Instanciando Views da Tela
edtIniPin = (EditText) findViewById(R.id.editTextPin);
txtSelecPin = (TextView) findViewById(R.id.btn_select_pin);
txtCancPin = (TextView) findViewById(R.id.btn_cancel_pin);
pinMaxLengthInt = Facade.getInstance().getPinSize();
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(pinMaxLengthInt);
edtIniPin.setFilters(FilterArray);
edtIniPin.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (edtIniPin.getText().length() > 0) {
txtCancPin.setText(getString(R.string.btn_clean));
}
else if (edtIniPin.getText().length() == 0){
txtCancPin.setText(getString(R.string.btn_exit));
}
else if (edtIniPin.getText().length() == Facade.getInstance().getPinSize()){
edtIniPin.setEnabled(false);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
} catch (SQLException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.label_title_error))
.setIcon(R.drawable.error_icon)
.setMessage(getString(R.string.msg_error_sql))
.setPositiveButton(getString(R.string.label_ok), this);
AlertDialog dialogSQL = builder.create();
dialogSQL.show();
e.printStackTrace();
} catch (CorruptedAppException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.label_title_error))
.setIcon(R.drawable.error_icon)
.setMessage(getString(R.string.msg_error_corrupted))
.setPositiveButton(getString(R.string.label_ok), this);
AlertDialog dialogCorrupted = builder.create();
dialogCorrupted.show();
e.printStackTrace();
} catch (NoServiceAvailableException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.label_title_error))
.setIcon(R.drawable.error_icon)
.setMessage(getString(R.string.msg_error_noservice))
.setPositiveButton(getString(R.string.label_ok), this);
AlertDialog dialogNoService = builder.create();
dialogNoService.show();
e.printStackTrace();
} catch (NumberFormatException e) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(getString(R.string.label_title_error));
dialog.setIcon(R.drawable.error_icon);
dialog.setMessage(getString(R.string.msg_error_numberformat));
dialog.setNeutralButton(getString(R.string.label_ok), null);
dialog.create().show();
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("FLUXO", "PIN -->> ON ACTIVITY RESULT");
if (resultCode == INSERT_OK) {
String[] initCode = (String[]) data.getSerializableExtra("init_code");
try {
Facade.getInstance().insertInitCode(serviceNames[0], initCode, this);
} catch (NumberFormatException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.label_title_error))
.setIcon(R.drawable.error_icon)
.setMessage(getString(R.string.msg_error_numberformat))
.setPositiveButton(getString(R.string.label_ok), this);
AlertDialog dialog = builder.create();
dialog.show();
e.printStackTrace();
} catch (SQLException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.label_title_error))
.setIcon(R.drawable.error_icon)
.setMessage(getString(R.string.msg_error_sql))
.setPositiveButton(getString(R.string.label_ok), this);
AlertDialog dialog = builder.create();
dialog.show();
e.printStackTrace();
} catch (CorruptedAppException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.label_title_error))
.setIcon(R.drawable.error_icon)
.setMessage(getString(R.string.msg_error_corrupted))
.setPositiveButton(getString(R.string.label_ok), this);
AlertDialog dialog = builder.create();
dialog.show();
e.printStackTrace();
}
}
else if (resultCode == INSERT_CANCEL){
this.finish();
}
}
#Override
protected void onStart() {
Log.v("FLUXO", "PIN -->> ON START");
super.onStart();
txtSelecPin.setOnClickListener(this);
txtCancPin.setOnClickListener(this);
}
#Override
protected void onResume() {
Log.v("FLUXO", "PIN -->> ON RESUME");
super.onResume();
if (!facade.isInitialized(serviceNames[0], this)) {
Intent itInicial = new Intent(this, InitialActivity.class);
startActivityForResult(itInicial, INSERT_SAL);
}
}
#Override
protected void onStop() {
Log.v("FLUXO", "PIN -->> ON STOP");
super.onStop();
}
#Override
protected void onPause() {
Log.v("FLUXO", "PIN -->> ON PAUSE");
super.onPause();
}
#Override
public void onBackPressed() {
Log.v("FLUXO", "PIN -->> ON BACK KEY PRESSED");
super.onBackPressed();
moveTaskToBack(true);
}
#Override
protected void onDestroy() {
Log.v("FLUXO", "PIN -->> ON DESTROY");
super.onDestroy();
}
/**
* Método chama próxima tela
*/
private void nextScreen(){
Log.v("FLUXO", "PIN -->> NEXT SCREEN");
Intent it = new Intent(this, ValueActivity.class);
startActivity(it);
}
#Override
public void onClick(View v) {
//lots of stuff (...)
}
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
System.exit(0);
}
}
AlertDialog generally needs its parent Context to be visible to work correctly (in my experience; someone correct me if I'm wrong). Barring other errors (hard to tell without the full code) you could probably make that work right if you move it into your onResume() function.
It was a problem with the life cicle of the Activity!
Heres what I did:
} catch (NumberFormatException e) {
showDialog(
R.string.label_title_error,
R.drawable.error_icon,
R.string.msg_error_noservice,
R.string.label_ok);
error = true;
e.printStackTrace();
}
and this:
#Override
protected void onResume() {
Log.v("FLUXO", "PIN -->> ON RESUME");
super.onResume();
if (!error) {
if (!facade.isInitialized(serviceNames[0], this)) {
Intent itInicial = new Intent(this, InitialActivity.class);
startActivityForResult(itInicial, INSERT_SAL);
}
}
}

Categories

Resources