Displaying a custom AlertDialog in Android while catching an Exception - android

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

Related

Unable to close AlertDialog after onResume()

I checking when the activity starts up whether Location Services are turned on or not, if not I am opening a dialog that starts the "Enable Location Activity" intent. Once I am returning from it I am checking if the location has really been enabled or not, if so I am dismissing the alert dialog.
In theory this should work, but when my activity resumes and call dialog.dismiss() absolutely nothing happens.
My code is as follows-:
public class LocationUtils {
private static AlertDialog dialog_ = null;
public static void checkAndEnableLocationServices(final Activity context) {
LocationManager lm = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("gps_enabled = " + gps_enabled);
System.out.println("network_enabled = " + network_enabled);
if (!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Location services are disabled");
builder.setPositiveButton("Enable Location Services", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
context.finish();
}
});
//For future reference.
AlertDialog dialog = builder.create();
dialog_ = dialog;
dialog.show();
} else {
if(dialog_!=null) {
dialog_.dismiss();
}
}
}
}
In my main activity I have a onResume callback that does the following-:
#Override
protected void onResume() {
super.onResume();
System.out.println("Activity resume()");
LocationUtils.checkAndEnableLocationServices(this);
}
What am I missing ? Why is this is dialog not closing ? The code is not throwing any errors. This a WTF moment for me.
Your are calling alertDialog.show method for the local alert dialog.
Replace code,
AlertDialog dialog = builder.create();
dialog_ = dialog;
with
dialog_ = builder.create();
dialog_.show
and onResume()
if(dialog_!=null) {
dialog_.dismiss();
}
Yo can dismiss dialog when positive button clicked and show it in OnResume if Location Service not enambled

Set timeout function with AsyncTask [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.

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.

delay an alertdialog

is it posible ??
I have an activity and an alertdialog on it.
but i need the activity run first and then 2 seconds later appears the alertdialog.
i have no idea how. regards
pd: iam not an english speaker
public class Pantalladeinicio extends Activity {
private final int SPLASH_DISPLAY_LENGTH = 2000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.index);
if(checkInternetConnection()==true) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent mainIntent = new Intent(Pantalladeinicio.this,
NetworkingActivity.class);
mainIntent.putExtra("MAIN", true);
startActivity(mainIntent);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
else
{
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
}
public void aceptar() {
// Toast t=Toast.makeText(this,"Bienvenido a probar el programa.", Toast.LENGTH_SHORT);
super.onDestroy();
finish();
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
//Log.v("TAG", "Internet Connection Not Present");
return false;
}
}
}
I don't understand your question, but looking at the accepted answer I suggest changing the order of your existing code:
new Handler().postDelayed(new Runnable() {
public void run() {
if(checkInternetConnection()) {
Intent mainIntent = new Intent(Pantalladeinicio.this, NetworkingActivity.class);
mainIntent.putExtra("MAIN", true);
startActivity(mainIntent);
finish();
}
else
{
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
}
}, SPLASH_DISPLAY_LENGTH);
Change your code as using Thread and runOnUiThread
//Your Code here...
else
{
myThread();
}
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
Pantalladeinicio.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(Pantalladeinicio.this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
I assume you want to wait for 2 seconds after you get into the else block.
You could do this by calling Thread.sleep(2000); before you call dialogo1.show();. However, this will make your program appear to "freeze". In order to avoid this you can create a seperate thread that sleeps and then displays the dialog.

((Dialog issue ))android.view.WindowManager$BadTokenException:

In my Application I need to call a function(Which update the valuesof textviews),I need to call this function inside AlertDialg when OK button is pressed.
the issue is how i can call RefreshData.execute() after ok button of dialog is pressed ?
this is one of the Errors :
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application.
the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.details);
Bundle extras = getIntent().getExtras();
if (extras != null) {
x = extras.getString("key").toString();
} else {
Toast.makeText(getBaseContext(), "null", 0).show();
}
tv_summary = (TextView) findViewById(R.id.tv_summary);
tv_servings_result = (TextView) findViewById(R.id.tv_servings_result);
tv_calories_result = (TextView) findViewById(R.id.tv_calories_result);
tv_fat = (TextView) findViewById(R.id.tv_fat);
tv_monofat = (TextView) findViewById(R.id.tv_monofat);
tv_satfat = (TextView) findViewById(R.id.tv_satfat);
tv_ch = (TextView) findViewById(R.id.tv_ch);
tv_sug = (TextView) findViewById(R.id.tv_sug);
new LoadDetails().execute();
Button MealSize = (Button) findViewById(R.id.btn_size);
MealSize.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
show();
Toast.makeText(getBaseContext(), F + "", 0).show();
}
});
}
void Refresh() {
new RefreshData().execute();
}
void show() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
F = Float.parseFloat(input.getText().toString());
new RefreshData().execute();
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
private class RefreshData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(getBaseContext(), "",
" Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try {
this.progressDialog.dismiss();
tv_servings_result.setText(servings_result + "" + F);
tv_calories_result.setText(cal + "g");
tv_fat.setText(ff + "");
tv_monofat.setText(mm + "");
tv_satfat.setText(sasa + "");
tv_ch.setText(chch + "");
tv_sug.setText(sugar + "");
} catch (Exception e) {
Log.e("log_tag",
"Eraaaaaaaaaaaaaaaaaaa connection" + e.toString());
}
}
#Override
protected Void doInBackground(Void... params) {
try {
sugar = Float.valueOf(sug).floatValue();
sugar *= F;
cal = Float.valueOf(calories_result).floatValue();
cal *= F;
ff = Float.valueOf(fat).floatValue();
ff *= F;
mm = Float.valueOf(monofat).floatValue();
mm *= F;
} catch (Exception e) {
Log.e("log_tag",
"Eraaaaaaaaaaaaaaaaaaa connection" + e.toString());
}
return null;
}
}
}
instead using
this.progressDialog = ProgressDialog.show(getBaseContext(), ""," Loading...");
try with
this.progressDialog = ProgressDialog.show(yourActivity.this, ""," Loading...");

Categories

Resources