Accessing Variables in AlertDialog in Android - android

In one of my Activity there are some calculations and total price will be calculated.After pressing the submit button it should show an alert dialog with Are you sure you want to pay Rupees:XXX...? here XXX should be the final price which I'm storing in the variable.
in alertdialog.setTitle() I should able to access the variable.
Please help me to solve this.
public void onPay()
{
getItems();
int rate = 0;
if(spare1_item.equals("Tyres") || qty_1.equals("Quantity"))
{
}
else
{
//Toast.makeText(getApplicationContext(), "Now you can pay", 5000).show();
db = this.openOrCreateDatabase("mobile_cycle_clinic", MODE_PRIVATE, null);
c = db.rawQuery("select price from sparelist where name = '"+spare1_item+"'", null);
if(c.moveToNext())
{
do{
price = c.getInt(c.getColumnIndex("price"));
}
while(c.moveToNext());
}
fianl1_qty = Integer.parseInt(qty_1);
rate = rate + price * fianl1_qty;
db.execSQL("insert into spares_items(cycle_id,item_name,quantity,total_price)values('"+cycle_id+"','"+spare1_item+"',"+fianl1_qty+","+rate+")");
//Toast.makeText(getApplicationContext(), ""+rate, 5000).show();
}
Here rate is a static variable and in another method I should use that variable in alertDialog.setMeaasge().
public void storeData(View v)
{
cycle_id = id.getText().toString();
if(cycle_id.equals("") || cycle_id.equals("null"))
{
Toast.makeText(getApplicationContext(), "Please Scan Cycle",5000).show();
}
else
{
AlertDialog.Builder pauseBuild = new AlertDialog.Builder(this);
pauseBuild.setTitle("Pay Alert");
pauseBuild.setMessage("Do you really want to Pay..?"+rate);
pauseBuild.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
//time = sdf.format(new Date());
onPay();
finish();
return;
} });
pauseBuild.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();
}
});
// show it
pauseBuild.show();
}

You can use a function to show or create the AlertDialog.
For example:
private void showConfirmAlertDialog(int price) {
AlertDialog.Builder builder = new AlertDialog.Builder();
builder.setTitle("Are you sure you want to pay rupees: " + price);
....
builder.show();
}
If you perfer getting an instance of AlertDialog, you can change the function to private AlertDialog createConfirmAlertDialg(int price), and use return builder.create(); at the end of function.

Related

How to parse result of QR-scanning Zbar android?

I use Zbar library for QR-scanning.
I try to parse result of this scanning, but I lost some information. For parsing I use this library.
Does any other library can parse handleResult(Result rawResult) rawResult?
This my code :
#Override
public void handleResult(final Result rawResult) {
Log.v("myLog", rawResult.getContents()); // Prints scan results
Log.v("myLog", rawResult.getBarcodeFormat().getName()); // Prints the scan format (qrcode, pdf417 etc.)
unswer = rawResult.getContents();
if (unswer.contains("VCARD")){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Содержимое");
builder.setMessage(unswer = rawResult.getContents());
builder.setPositiveButton("Добавить контакт", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String parseVcard = unswer;
VCard vCard = VCardParser.parse(parseVcard);
String name = vCard.getName();
String fname = vCard.getFormattedName();
Log.d("myLog", name + " " + fname);
addContact(fname + " " + name);
}
});
builder.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mScannerView.resumeCameraPreview(SimpleScannerActivity.this);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
vCard.getFormattedName() is not going to return you a value because your rawResult does not contain a "FN" value. When you look at the value you sent it only contains "N" which means you'll only have value with vCard.getName();

how to show values in the second edittext only if user puts all the correct values in the first edit text

what should add in the code so that values are shown in the other text box only when the user have entered only corrected values...because with this code it is showing both the corrected values in the text box and incorrect in the dialog box..
String s=editText1.getText().toString();
String z[]=s.split("\\s");
editText2.setText("");
String a = "";
String b = " Not valid";
boolean is_open_dialog=false;
for(int i=0;i<z.length;i++)
{
int j=Integer.parseInt(z[i]);
if(j>=65 && j<=97)
{
editText2.setText(editText2.getText() + "" + String.valueOf((char) j));
}
else {
is_open_dialog = true;
a += z[i]+"\t";
}
}
if(is_open_dialog){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setMessage(a+b)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
I do not know if I have clear your problem, but try this:
...
if(is_open_dialog){
editText2.setText("");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
...
}

Android call same alert dialog in the entire application

I have a menu on Action Bar to change the password. And below is the code for it. I want to place this code such that I can call the same code anywhere in my application by clicking that menu. Is there any way?
--- ChangingPassword.java---
public void showDialog(final Context ctx, final String user_id, final String storedPass)
{
LayoutInflater layoutInflater = LayoutInflater.from(ctx);
View promptView = layoutInflater.inflate(R.layout.change_password, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctx);
// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(promptView);
final EditText old_password = (EditText) promptView.findViewById(R.id.old_password);
final EditText new_password = (EditText) promptView.findViewById(R.id.new_password);
final EditText c_new_password = (EditText) promptView.findViewById(R.id.c_new_password);
final int error_count;
/*old_password.setTypeface(font);
new_password.setTypeface(font);
c_new_password.setTypeface(font);
*/
final String old_pwd = old_password.getText().toString();
final String new_pwd = new_password.getText().toString();
final String c_new_pwd = c_new_password.getText().toString();
// setup a dialog window
alertDialogBuilder
.setTitle("Change Login Password")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(old_pwd.equalsIgnoreCase("") || (old_pwd.equalsIgnoreCase(storedPass)))
{
old_password.setError(Html.fromHtml("<font color='red'>Enter a valid password</font>"));
old_password.requestFocus();
}
else if( new_pwd.equalsIgnoreCase(""))
{
new_password.setError(Html.fromHtml("<font color='red'>Enter a valid password</font>"));
new_password.requestFocus();
}
else if( c_new_pwd.equalsIgnoreCase(""))
{
c_new_password.setError(Html.fromHtml("<font color='red'>Enter a valid password</font>"));
c_new_password.requestFocus();
}
else if(!new_pwd.equals(c_new_pwd))
{
c_new_password.setError(Html.fromHtml("<font color='red'>Password & Confirm Passwords do not match</font>"));
c_new_password.requestFocus();
}
else
{
try {
UserTask task = new UserTask();
String result = task.execute(new String[] {"changePassword",user_id,new_pwd}).get();
System.out.print(result);
}
catch (Exception e)
{
Toast.makeText(ctx, ""+e.toString(), Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();
//return alertD;
}
---Calling Activity ---
new ChangePassword().showDialog(TeacherMain.this, user_id, password);
return true;
public class MyDialog{
public void showDialog(Context ctx)
{
/* Create dialog here and do whatever you are doing right now in your method*/
dialog.show();
}
}
and call from your activity classes as below
new MyDialog().showDialog(ActivityName.this);
For your checking part you have to remove nested if statements
if(old_pwd.equalsIgnoreCase("")){
//print: Enter old password
}else if( new_pwd.equalsIgnoreCase("")){
//print: Enter new password
}else if( c_new_pwd.equalsIgnoreCase("")){
//print: Enter c_new_pwd
}else if(! new_pwd.equals(c_new_pwd)){
//print password doesnot match
}else
{
try {
UserTask task = new UserTask();
String result = task.execute(new String[] {"changePass",user_id}).get();
System.out.print(result);
}catch (Exception e){
Toast.makeText(TeacherMain.this, ""+e.toString(),Toast.LENGTH_LONG).show();
}
}
instead of creating new AlertDialog use
alertDialogBuilder.show();

Android 4.4 SQLite Not Updating

I have a fully functional SQLite database in my Android App which works perfect on my testing devices (Android 4.0 - 4.3), but I have a user running KitKat and they are unable to update the database. To summarize my code, I have a user click a switch, then asks whether they want to make the change, if so it updates the database table.
Here is my calls to the database from the Activity:
StatusData statusData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_macro);
statusData = new StatusData(getBaseContext());
}
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder;
AlertDialog alertDialog;
switch (v.getId())
case R.id.switchOffSeason:
String season,
seasonHeading = "";
alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog message
if (switchOffSeason.isChecked()) {
season = "This will delete all your current settings and default to the standard diet. This cannot be undone";
seasonHeading = "Set Standard Diet";
} else {
season = "This will delete all your current settings and default to Off-Season diet. This cannot be undone.";
seasonHeading = "Set Off-Season Diet";
}
// set title
alertDialogBuilder.setTitle(seasonHeading);
alertDialogBuilder
.setMessage(season)
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
String passedTask = "offSeason";
dropTable task = new dropTable(passedTask);
task.execute(passedTask);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (switchOffSeason.isChecked()) {
switchOffSeason.setChecked(false);
} else {
switchOffSeason.setChecked(true);
}
dialog.cancel();
}
});
alertDialog = alertDialogBuilder.create();
private class dropTable extends AsyncTask<String, Void, String> {
String task;
public dropTable(String passedTask) {
super();
task = passedTask;
}
#Override
protected String doInBackground(String... params) {
if (task.equals("reset")) {
String offSeason = statusData.profileTable()[10];
profileTable = statusData.profileTable();
statusData.dropReloadMacrosTable(new String[] {
profileTable[11], profileTable[12], profileTable[13],
profileTable[14], profileTable[15], profileTable[16],
profileTable[17], offSeason });
} else if (task.equals("offSeason")) {
if (switchOffSeason.isChecked()) {
statusData.updateFieldProfile(new String[] { "offseason",
"1" });
} else {
statusData.updateFieldProfile(new String[] { "offseason",
"0" });
}
String offSeason = statusData.profileTable()[10];
statusData.dropReloadMacrosTable(new String[] {
profileTable[11], profileTable[12], profileTable[13],
profileTable[14], profileTable[15], profileTable[16],
profileTable[17], offSeason });
}
return "Executed";
}
Here is my StatusData (Database) class:
public void updateFieldProfile(String updateArray[]) {
open();
Log.i("log", "in method");
String fieldToUpdate = updateArray[0];
String valueToUpdate = updateArray[1];
String query = "UPDATE PROFILE SET " + fieldToUpdate + "="
+ "= ?";
Log.i("logQuery", query);
Cursor c = db.rawQuery(query, new String[] {valueToUpdate});
c.moveToFirst();
c.close();
db.close();
}

AlertDialog in custom Hashmap array adapter

I am creating a custom Hash map array adapter.In that,when the user clicks on an element, an AlertDialog pops up,in that user can see his messaages,
For this I am using this code,
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("PassWord Protected Message");
alert.setMessage("Please Enter The Password to See The Messages");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton)
{
// Editable value = input.getText();
// Do something with value!
String we=input.getText().toString();
// Toast.makeText(getApplicationContext(), we, Toast.LENGTH_SHORT ).show();
if (we.equalsIgnoreCase("password"))
{
try
{
String[] splitted = smsList.get( pos ).split("\n");
String sender = splitted[0];
for ( int i = 1; i < splitted.length; ++i )
{
//some code here
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
This AlertDialog will ask user to enter a password.Then user will be able to see the messages.
But I am getting error ,
String[] splitted = smsList.get( pos ).split("\n");
In this,I am getting error on split function and the error is "The method split(String) is undefined for the type HashMap".
You'll have to type cast the smsList to String
String[] splitted = ((String)smsList.get( pos )).split("\n");

Categories

Resources