My program is to get the Tutor's LastName, FirstName, and MiddleName from an EditText in DialogFragment. Here's the code of my DialogFragment:
public class AddInstructorDialog extends android.app.DialogFragment
{
DatabaseHelper myDb;
View myView;
public AlertDialog.Builder builder;
private EditText tutorLastName, tutorFirstName, tutorMiddleName;
private dialogListener listener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
myDb = new DatabaseHelper(getActivity());
View mView = getActivity().getLayoutInflater().inflate(R.layout.alert_dialog_add_instructor, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Add Instructors")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
myDb.getInstructorNumber();
if(myDb.instructorNumber == null)
{
Toast.makeText(getActivity(), "IN1", Toast.LENGTH_SHORT).show();
}
else
{
String sum = myDb.instructorNumber;
String total = "IN" + sum;
EditText txtLastName = myView.findViewById(R.id.tutor_LastName);
EditText txtMiddleName = myView.findViewById(R.id.tutor_MiddleName);
EditText txtFirstName = myView.findViewById(R.id.tutor_FirstName);
String LastName = txtLastName.getText().toString();
String MiddleName = txtMiddleName.getText().toString();
String FirstName = txtFirstName.getText().toString();
listener.applyValuse(LastName, FirstName, MiddleName);
String fullName = LastName + ", " + FirstName + LastName;
boolean isInserted = myDb.addInstructorData(
total,
LastName,
FirstName,
MiddleName,
fullName
);
if(isInserted == true)
{
Toast.makeText(getActivity(), "Inserted", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Not inserted", Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
myDb.insertInsData();
}
});
builder.setView(mView);
AlertDialog dialog = builder.create();
dialog.show();
return dialog;
}
I have no problem in getting the value of instructorID. My problem is that, after getting the value of instructorID, it will proceed in fetching the inputted data from the EditText of DialogBox the the app will crash. It doesn't read the line of
EditText txtLastName = myView.findViewById(R.id.tutor_LastName);
inthat line, the app will crash.
Did I miss somethin? I tried moving that line around but it doesn't work.
Related
In this activity I am creating an account for users. I am using mobsandgeeks.saripaar API for validation features. To allow the activity to work I currently print the errors to an invisible text field, if this textfield has text, the activity does not go onto the next activity (i.e. there is an issue with user input).
I am having a problem with the if statement that checks if the username or email already exists in the database. When condition is true (checked in logs), the account is not created, but the 'Account created' message is still displayed and the application still goes to the next activity.
Any help on this would be much appreciated. Thanks
CreateAccount.java
DatabaseHelper myDb;
private static final String TAG = "CreateAccount";
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#NotEmpty
#Length(min = 3, max = 10)
private EditText etUsername;
#NotEmpty
private EditText etUserAddress;
#NotEmpty
private EditText etFirstName;
#NotEmpty
private EditText etLastName;
#NotEmpty
#Email
private EditText etEmail;
#NotEmpty
#Pattern(regex = "(^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$)")
private EditText etPhone;
#NotEmpty
private EditText etPaypal;
//Valid = abcABC123!
#NotEmpty
#Password(scheme = Password.Scheme.ALPHA_NUMERIC_SYMBOLS)
private EditText etPassword;
#ConfirmPassword
EditText etConfirmPassword;
Button btnCreateAccount;
TextView check;
//https://www.youtube.com/watch?v=rt-8PgncIio
ImageView profileImageView;
Button btnProfilePic;
private static final int SELECT_PHOTO = 1;
private static final int CAPTURE_PHOTO = 2;
ProgressDialog progressBar;
int progressBarStatus;
Handler progressBarHandler = new Handler();
Bitmap thumbnail;
private Validator validator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
myDb = new DatabaseHelper(this);
validator = new Validator(this);
validator.setValidationListener(this);
etUsername = findViewById(R.id.etUsername);
etFirstName = findViewById(R.id.etFirstName);
etLastName = findViewById(R.id.etLastName);
etUserAddress = findViewById(R.id.etAddress);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPasswordLogin);
etConfirmPassword = findViewById(R.id.etConfirmPasswordLogin);
etPhone = findViewById(R.id.etPhoneNo);
etPaypal = findViewById(R.id.etPaypalName);
btnCreateAccount = findViewById(R.id.btnCreateAccount);
check = findViewById(R.id.tvCheck);
btnProfilePic = findViewById(R.id.btnProfilePicture);
profileImageView = findViewById(R.id.imageProfile);
btnProfilePic.setOnClickListener(this);
//(https://www.youtube.com/watch?v=rt-8PgncIio) Image
//had to change permissions in the Android Manifest file to allow for camera to be used
if (ContextCompat.checkSelfPermission(CreateAccount.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
profileImageView.setEnabled(false);
ActivityCompat.requestPermissions(CreateAccount.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
} else {
profileImageView.setEnabled(true);
}
createAccount();
}
public void createAccount() {
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validator.validate();
//(https://www.youtube.com/watch?v=rt-8PgncIio) Image
profileImageView.setDrawingCacheEnabled(true);
profileImageView.buildDrawingCache();
Bitmap bitmap = profileImageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
String email1 = etEmail.getText().toString().trim();
Log.d(TAG, "onClick: email " + email1);
String username = etUsername.getText().toString().trim();
Log.d(TAG, "onClick: username " + username);
boolean emailExists = myDb.checkIfEmailAlreadyExists(email1);
Log.d(TAG, "onClick: emailExists " + emailExists);
boolean usernameExists = myDb.checkIfUsernameAlreadyExists(username);
Log.d(TAG, "onClick: usernameExists " + usernameExists);
//https://stackoverflow.com/questions/6290531/check-if-edittext-is-empty
if (etUsername.getText().toString().matches("") | etFirstName.getText().toString().matches("") | etLastName.getText().toString().matches("")
| etEmail.getText().toString().matches("") | etUserAddress.getText().toString().matches("") | etPassword.getText().toString().matches("")|
etConfirmPassword.getText().toString().matches("") | etPhone.getText().toString().matches("") | etPaypal.getText().toString().matches(""))
{
Toast.makeText(CreateAccount.this, "Please fill empty fields", Toast.LENGTH_LONG).show();
}
else if(check.getText().toString().matches("") == false) {
Toast.makeText(CreateAccount.this, "Please enter correct details", Toast.LENGTH_SHORT).show();
}
else {
if (usernameExists){
Log.d(TAG, "onClick: userExists " + usernameExists);
Toast.makeText(CreateAccount.this, "This username is already registered", Toast.LENGTH_LONG).show();
check.setText("TEXT");
}
else if (emailExists){
Log.d(TAG, "onClick: emailExists" + emailExists);
Toast.makeText(CreateAccount.this, "This email is already registered", Toast.LENGTH_LONG).show();
check.setText("TEXT");
}
else if (usernameExists == false | emailExists == false) {
boolean checktext = check.getText().equals("");
// original CRUD video - https://www.youtube.com/watch?v=kDZES1wtKUY&list=PLS1QulWo1RIaRdy16cOzBO5Jr6kEagA07&index=8
boolean isInserted = myDb.insertUserData(etUsername.getText().toString(), etUserAddress.getText().toString(), etFirstName.getText().toString(), etLastName.getText().toString(),
etEmail.getText().toString(), etPassword.getText().toString(), etPhone.getText().toString(),
etPaypal.getText().toString(), data);
if (isInserted == true) {
if (checktext == true) {
onValidationSucceeded();
}
else if (checktext == false){
Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
}
}
}
});
}
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
//TextView check = findViewById(R.id.tvCheck);
String message = error.getCollatedErrorMessage(this);
// Display error messages
if (view instanceof EditText) {
((EditText) view).setError(message);
} else {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
check.setText(errors.toString());
}
}
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#Override
public void onValidationSucceeded() {
Toast.makeText(CreateAccount.this, "Account Created, Please sign in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(CreateAccount.this, Login.class);
startActivity(intent);
}
You have a problem in your condition:
Instead of:
else if (usernameExists == false | emailExists == false)
It should be:
else if (usernameExists == false && emailExists == false)
which means user/email not exist, insert them in DB and navigate to next activity.
i have a fragment in that i made a button to collect user mobile number. In the same fragment i have made a button to toast the string value collected from edited text (mobile), I know it's a simple question but i don't know the answer please help me
this is my edit text
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_mobile,(ViewGroup) view.findViewById(R.id.dialog_mobile));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Contact Information").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputMobile = (EditText) dialog.findViewById(R.id.dialog_et_mobile);
if (inputMobile.getText().toString().isEmpty()){
return;
}
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
String mobile = inputMobile.getText().toString();
//DatabaseReference mynum = database.getReference("number");
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
This is my button code
mButtonCheckout = (Button) view.findViewById(R.id.checkout_pay);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
DatabaseReference mylocation = database.getReference().child(userID).child("location");
// mylocation.setValue(mobile); // here i need string
}
});
this is my whole code of fragment
package com.example.guanzhuli.foody.CartPage.fragment;
public class CheckoutFragment extends Fragment {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
// PayPal Initialization
private static final String TAG = "iCartPayment";
//private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "AfNfJY2QLMIzxPpAt97YVg4GKJtMa0k8wQICuFcwIdR6bR73oexStWMQfH0nirg-WlFradZHcPnCleZg";
private static final int REQUEST_CODE_PAYMENT = 1;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Example Merchant")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
// Fragment Component Initialization
private RecyclerView mRecyclerView;
private TextView mTextMobile, mTextTotal, mTextEditAddress, mTextEditMobil;
public static TextView mTextAddress;
private Button mButtonCheckout, mButtonCancel;
public CheckoutFragment() {
// Required empty public constructor
}
DatabaseReference databaseReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_checkout, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_checkout);
mRecyclerView.setAdapter(new CheckoutAdapter(getContext()));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// initial button
mButtonCheckout = (Button) view.findViewById(R.id.checkout_pay);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getContext(),abc, Toast.LENGTH_SHORT).show();
// payOrder();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
DatabaseReference mylocation = database.getReference().child(userID).child("location");
// mylocation.setValue(mobile); // here i need string
}
});
mButtonCancel = (Button) view.findViewById(R.id.checkout_cancel);
mButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().finish();
}
});
// initial text
mTextMobile = (TextView) view.findViewById(R.id.checkout_mobile);
mTextMobile.setText(SPManipulation.getInstance(getActivity()).getMobile());
mTextAddress = (TextView) view.findViewById(R.id.checkout_address);
mTextAddress.setText(SPManipulation.getInstance(getContext()).getAddress());
mTextTotal = (TextView) view.findViewById(R.id.checkout_total);
mTextEditMobil = (TextView) view.findViewById(R.id.checkout_edit_mobile);
mTextEditMobil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Toast.makeText(getContext(), "Edit Number", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_mobile,(ViewGroup) view.findViewById(R.id.dialog_mobile));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Contact Information").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputMobile = (EditText) dialog.findViewById(R.id.dialog_et_mobile);
if (inputMobile.getText().toString().isEmpty()){
return;
}
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
String mobile = inputMobile.getText().toString();
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
}
}).setNegativeButton("Cancel", null).show();
}
});
mTextEditAddress = (TextView) view.findViewById(R.id.checkout_edit_addr);
mTextEditAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_location,(ViewGroup) view.findViewById(R.id.dialog_location));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Delivery Location").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputLocation = (EditText) dialog.findViewById(R.id.dialog_et_location);
if (inputLocation.getText().toString().isEmpty()){
return;
}
mTextAddress.setText(inputLocation.getText().toString());
String bbb = inputLocation.getText().toString();
Toast.makeText(getContext(),bbb, Toast.LENGTH_LONG).show();
}
})
.setNeutralButton("Show Map", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent mapAct = new Intent(getActivity(), MapsActivity.class);
startActivity(mapAct);
}
})
.setNegativeButton("Cancel", null)
.show();
}
});
mTextTotal.setText(String.valueOf(ShoppingCartItem.getInstance(getContext()).getPrice() * 1.06 + 1.99));
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == getActivity().RESULT_OK) {
ShoppingCartItem.getInstance(getContext()).placeOrder(mTextAddress.getText().toString(), mTextMobile.getText().toString());
ShoppingCartItem.getInstance(getContext()).clear();
DBManipulation.getInstance(getActivity()).deleteAll();
PaymentConfirmation confirm =
data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
/**
* TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
* or consent completion.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
* for more details.
*
* For sample mobile backend interactions, see
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
registerOrder();
}
catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
HomePageActivity.cartNumber.setText("0");
getActivity().finish();
} else if (resultCode == getActivity().RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
Toast.makeText(getContext(),"Cancel", Toast.LENGTH_LONG).show();
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
TAG,
"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
getActivity().stopService(new Intent(getContext(), PayPalService.class));
}
private void payOrder() {
/*
* PAYMENT_INTENT_SALE will cause the payment to complete immediately.
* Change PAYMENT_INTENT_SALE to
* - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
* - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
* later via calls from your server.
*
* Also, to include additional payment details and an item list, see getStuffToBuy() below.
*/
PayPalPayment thingToBuy = getStuffToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
/*
* See getStuffToBuy(..) for examples of some available payment options.
*/
Intent intent = new Intent(getContext(), PaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
private PayPalPayment getStuffToBuy(String paymentIntent) {
//--- include an item list, payment amount details
PayPalItem[] items = new PayPalItem[ShoppingCartItem.getInstance(getContext()).getFoodTypeSize()];
for (int position = 0; position < ShoppingCartItem.getInstance(getContext()).getFoodTypeSize(); position++){
int id = ShoppingCartItem.getInstance(getContext()).getFoodInCart().get(position);
final Food curFood = ShoppingCartItem.getInstance(getContext()).getFoodById(id);
final int curFoodNumber = ShoppingCartItem.getInstance(getContext()).getFoodNumber(curFood);
Log.e("PRICE & NUMBER", "price: " + curFood.getPrice() + ", number: " + curFoodNumber);
items[position] = new PayPalItem("Item No." + curFood.getId(),
curFoodNumber,
new BigDecimal(String.valueOf(curFood.getPrice())),"USD", curFood.getName()
);
}
BigDecimal subtotal = PayPalItem.getItemTotal(items);
BigDecimal shipping = new BigDecimal("1.99");
BigDecimal tax = new BigDecimal("" + ShoppingCartItem.getInstance(getContext()).getPrice() * 0.06);
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(amount, "USD", "Foody Inc.", paymentIntent);
payment.items(items).paymentDetails(paymentDetails);
//--- set other optional fields like invoice_number, custom field, and soft_descriptor
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
private void registerOrder() {
}
}
you have two way
1 : Instead on mobile use this
Toast.makeText(getContext(),inputMobile.getText().toString(), Toast.LENGTH_SHORT).show();
2 : Create global string variable mobile like this
first create global mobile number above on onCreateView()
public String mobileNumber;
then in you button click in dialog init mobileNumber
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
mobileNumber = inputMobile.getText().toString();//THIS LINE CHANGED
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
Now you can use mobileNumber anywhere like in button
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),mobileNumber, Toast.LENGTH_SHORT).show();
}
});
declare a String variable to store the value of the EditText
String mobileNumber = inputMobile.getText().toString();
Create your Toast inside the OnClickListener.
Toast.makeText(getContext, mobileNumber,Toast.LENGTH_LONG).show();
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();
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.
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();
}