Android AlertDialog remembers string from previous shown? - android

The problem I am having with my Alert dialog is that, I have a custom dialog which has 3 edittext end 3 textview on it. when I pick up a contact from contacts I just filled the information in the dilaog edtitext like contactName.setText(bla); however the strange thing happens here that if I cancel the dialog and again pick another contact the details on the dialog is not getting changed and remembers the details from the first picked contact? is int weird? it seems that once it creates the dialog even though if I call the same process creating again the dialog it keeps the first dialog and keeps showing the same dialog. is there anyone whom have had the same experience and know how to solve this?
Here is the code that handles the result comes back from the contact picker.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI,
null, Email.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
contactUEmail=email;
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
// EditText emailEntry = (EditText) findViewById(R.id.invite_email);
// emailEntry.setText(email);
if (email.length() == 0) {
Toast.makeText(this, "No email found for contact.",
Toast.LENGTH_LONG).show();
}
}
showDialog(DIALOG_ADD_NEW_CALL);// this is where I call the dialog.
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
and here is the dialog DIALOG_ADD_NEW_CALL;
case DIALOG_ADD_NEW_CALL:
{
builder = new AlertDialog.Builder(this);
entryView = getLayoutInflater().inflate(R.layout.entry, null);
builder.setView(entryView);
CNameEditor = (EditText) entryView.findViewById(R.id.cName);
CEmailEditor = (EditText) entryView.findViewById(R.id.cEmail);
CPhoneEditor = (EditText) entryView.findViewById(R.id.cPhone);
if(!contactUEmail.equals(""))//here is the code that I am setting the text.
CEmailEditor.setText(contactUEmail);
else{}
builder.setTitle(R.string.addDialogTitle);
builder.setPositiveButton(R.string.addItem,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancelItem,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
return builder.create();
}

To destroy the dialog, you can call removeDialog. Alternatively, you could override onPrepareDialog and update the dialog before it's shown. Just FYI, both methods are deprecated in favor of DialogFragment along with FragmentManager but you probably have to redo a lot of code to use those.

Override onPrepareDialog
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_ADD_NEW_CALL:
AlertDialog callDialog = (AlertDialog) dialog;
View entryView = callDialog;
CNameEditor = (EditText) entryView.findViewById(R.id.cName);
CEmailEditor = (EditText) entryView.findViewById(R.id.cEmail);
CPhoneEditor = (EditText) entryView.findViewById(R.id.cPhone);
// do stuff to those variables here
}
}

Related

Iterate through arraylist and show alert dialog for each item in array list and then move to next item when click positive button

I am creating an auto caller app in which i have used a button which takes data from arrayList, iterate through the arraylist and ask user on each element if want to do next call or pause on that for this i have used alert dialog, but the loop is not getting pause on each element it went to the last element and show alert dialog for that contact number.
private List<ContactEntity> mContactsList = new ArrayList<>();
private ContactEntity c;
private int i = 0;
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.start_call) {
Toast.makeText(this, "Call Started" + mContactsList.size(), Toast.LENGTH_LONG).show();
startAutoCall();
}
return super.onOptionsItemSelected(item);
}
private void startAutoCall() {
if (mContactsList.isEmpty()) {
Toast.makeText(this, "Import Contacts ", Toast.LENGTH_LONG).show();
} else {
c = mContactsList.get(i);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getPersonContactNumber()));
startActivity(intent);
while(i < mContactsList.size()){
c = mContactsList.get(i);
Log.d(TAG, "startAutoCall: " + c.getId());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Auto Dialer Start");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getPersonContactNumber()));
startActivity(intent);
}
});
AlertDialog dialog = builder.create();
dialog.show();
i++;
}
}
}
It's not a good idea to build alert dialog inside a loop. Instead, create one and update the value for each element in the list on button click. Override onClickListener for the dialog so that you can control the flow better.
Here's a snippet in kotlin.
if(mContactList.isNotEmpty()){
c = mContactList.get(i)
val builder = AlertDialog.Builder(this)
builder.setTitle("Auto Dialer Start")
builder.setMessage("Your message here...")
builder.setPositiveButton("OK", null)
val dialog = builder.create()
dialog.setOnShowListener{ dialogInterface->
val btnOk = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
btnOk.setOnClickListener{
//Your code here...
if(i == mContactList.size-1){
dialogInterface.dismiss()
}else {
i++
c = mContactList.get(i)
}
}
}
dialog.show()
}

Registration condition not working? Android

I am trying to make registration activity without using SQLite in android.
In which user enters data at run time and if he do not fill all sections then user will not proceed to another activity. But the problem is if user is not entering anything then its also proceeding to another activity.
here is my code. Plz help me whats the error.
public void onClick(View v) {
EditText us = (EditText)findViewById(R.id.us);
EditText pas = (EditText)findViewById(R.id.pas);
EditText em = (EditText)findViewById(R.id.em);
EditText ph = (EditText)findViewById(R.id.ph);
String UserName= us.getText().toString();
String Email= em.getText().toString();
String Password= pas.getText().toString();
String PhoneNo= ph.getText().toString();
us.getEditableText().toString();
em.getEditableText().toString();
pas.getEditableText().toString();
ph.getEditableText().toString();
if ((us != null) && (em != null) && (pas != null) &&(ph != null)){
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
SendOfferActivity.class);
startActivity(intent);
}
else{
AlertDialog.Builder builder1 = new AlertDialog.Builder(Registration.this);
builder1.setMessage("Enter Valid Information.");
builder1.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}});
}
But the problem is if user is not entering anything then its also
proceeding to another activity. here is my code
you are just checking if the object are not null, but what you want really check is if the EditTexts contain something. You use
if (!TextUtils.isEmpty(am.getText().toString()) /* do the same for the other */) {
}
to check the content of your EditTexts
You are just checking the EditText elements and you show test if the user typed something.
String usTxt = us.getText().toString();
String emTxt = em.getText().toString();
String pasTxt = pas.getText().toString();
String phTxt = ph.getText().toString();
if (!usTxt.isEmpty() && !emTxt.isEmpty() && !pasTxt.isEmpty() && !phTxt.isEmpty())
{
// your code
}
if ((!UserName.isEmpty()) && (!Email.isEmpty()) && (!Password.isEmpty() &&(!PhoneNo.isEmpty())){}

SQLite Database not updating properly after deleting row

When I delete any data then listitem click is showing error when opening listitem and data are also not correct on custom listview. After deleting row 0 data is not updating properly. Please help..
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
// means this is the view part not the add contact part.
Cursor crs = mydb.getData(Value);
id_To_Update = Value;
crs.moveToFirst();
String nam = crs.getString(crs.getColumnIndex(DBHelper.C_NAME));
String phon = crs.getString(crs
.getColumnIndex(DBHelper.C_PHONE));
String addr = crs.getString(crs
.getColumnIndex(DBHelper.C_ADDRESS));
String dat = crs.getString(crs.getColumnIndex(DBHelper.C_DATE));
String typ = crs.getString(crs.getColumnIndex(DBHelper.C_TYPE));
if (!crs.isClosed()) {
crs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence) phon);
phone.setFocusable(false);
phone.setClickable(false);
type.setText((CharSequence) typ);
type.setFocusable(false);
type.setClickable(false);
address.setText((CharSequence) addr);
address.setFocusable(false);
address.setClickable(false);
date.setText((CharSequence) dat);
date.setFocusable(false);
date.setClickable(false);
}
}
}
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(),
"Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
if (mydb.updateContact(id_To_Update, name.getText().toString(),
phone.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "not Updated",
Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.insertContact(name.getText().toString(), phone
.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
DBHelper.java
public Integer deleteContact(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ",
new String[] { Integer.toString(id) });
}
}
Finally I have got the solution. I have a text view in custom list view which has Table id which is unique for every row and after deleting the row it's value does not change so I am opening the data of that row on different activity.

How to stop my Alert Dialog from being immediately dismissed?

I'm trying to read a boarding pass barcode to inform the user if we have details on their flight and if so why not. I'm using AlertDialogs to communicate with the user as Toast notifications did not appear clearly enough. However they dismiss as soon as they are called without the user clicking ok.
How do I stop this? Is onActivityResult the wrong place to put this code?
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String boardingPassString = intent
.getStringExtra("SCAN_RESULT");
Log.d("Scan Result", "contents: " + boardingPassString);
String flightNumber = dataProcessor.decodeFlightNumber(boardingPassString);
Builder dialogBuilder = new AlertDialog.Builder(this);
String isFlightOld = isFlightOld(boardingPassString);
if(isFlightOld.equals(CURRENT))
{
Log.d("Block", "Current");
postData(flightNumber);
}
else if(isFlightOld.equals(TOO_NEW))
{
dialogBuilder.setTitle(R.string.dialog_title_new);
dialogBuilder.setMessage(R.string.dialog_msg_new1 + flightNumber + R.string.dialog_msg_new2);
dialogBuilder.setPositiveButton(android.R.string.ok, null);
AlertDialog alert = dialogBuilder.create();
alert.show();
Log.d("Block", getResources().getString(R.string.dialog_title_new));
}
else if(isFlightOld.equals(OLD))
{
dialogBuilder.setTitle(R.string.dialog_title_old);
dialogBuilder.setMessage(R.string.dialog_msg_old1 + flightNumber + R.string.dialog_msg_old2);
dialogBuilder.setPositiveButton(android.R.string.ok, null);
AlertDialog alert = dialogBuilder.create();
alert.show();
Log.d("Block", getResources().getString(R.string.dialog_title_old));
}
else
{
dialogBuilder.setTitle(R.string.dialog_title_error);
dialogBuilder.setMessage(R.string.dialog_msg_error).show();
dialogBuilder.setPositiveButton(android.R.string.ok, null);
AlertDialog alert = dialogBuilder.create();
alert.show();
Log.d("Block", getResources().getString(R.string.dialog_title_error));
}
} else if (resultCode == RESULT_CANCELED) {
Log.d("Scan Result", "RESULT_CANCELED");
}
}
}
Calling Code
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Testing shortcut
// =================================
// getXMLFlightDetails("US729");
// ==================================
// Uncomment to return Barcode scanning!!!
// =============================================
Intent intent = new Intent(getApplicationContext(),
CaptureActivity.class);
intent.setAction("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "PDF417_MODE");
intent.putExtra("SAVE_HISTORY", false);
startActivityForResult(intent, 0);
}
});
Just try the following code, hopefully it should work. You need to pass the context in Dialog Builder. Then the Android OS will know which activity the dialog is attached to and where it should be popped.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String boardingPassString = intent
.getStringExtra("SCAN_RESULT");
Log.d("Scan Result", "contents: " + boardingPassString);
String flightNumber = dataProcessor.decodeFlightNumber(boardingPassString);
Builder dialogBuilder = new AlertDialog.Builder(this);
String isFlightOld = isFlightOld(boardingPassString);
if(isFlightOld.equals(CURRENT))
{
Log.d("Block", "Current");
postData(flightNumber);
}
else if(isFlightOld.equals(TOO_NEW))
{
displayAlert(R.string.dialog_msg_new1 + flightNumber + R.string.dialog_msg_new2);
Log.d("Block", getResources().getString(R.string.dialog_title_new));
}
else if(isFlightOld.equals(OLD))
{
displayAlert(R.string.dialog_msg_old1 + flightNumber + R.string.dialog_msg_old2);
Log.d("Block", getResources().getString(R.string.dialog_title_old));
}
else
{
displayAlert(R.string.dialog_msg_error);
Log.d("Block", getResources().getString(R.string.dialog_title_error));
}
} else if (resultCode == RESULT_CANCELED) {
Log.d("Scan Result", "RESULT_CANCELED");
}
}
}
displayAlert(String message)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyActivity.this);
alertDialog.setTitle(getResources().getString(R.string.alert_title));
alertDialog.setMessage(message);
alertDialog.setPositiveButton(getResources().getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
//your action here
}
});
alertDialog.setNegativeButton(getResources().getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your Action here
}
});
alertDialog.show();
}
If this does not solve your problem. Then you need to show ur entire activity code, as it may be possible that your activity is getting finished soon after the dialog is displayed to the screen.
This turned out to be a multi-threading issue. The method postData used a HTTPResponse call so was not on the main thread. This method would finish a few milliseconds after tyhe dialog had been displayed and was what was dismissing the alertDialogs.
A simple join() call to get the main thread to wait for the postData method to do it's buisness before displaying the alertDialogs was all it took.

Android - Nullpointer Exception when clicking a listitem to show AlertDialog

I have a listview and when I click on a item it should show a AlertDialog with Radiobuttons in it. But when calling the alertDialog, the app crashes. Logcat gives a NullPointerException. What am I doing wrong?
private void registerClickCallBack() {
ListView list = (ListView) findViewById(R.id.settingsList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
if (position == 0) {
final AlertDialog levelDialog
final CharSequence[] items = { " Easy ", " Medium ",
" Hard ", " Very Hard " };
AlertDialog.Builder builder = new AlertDialog.Builder(
MyActivity.this);
builder.setTitle("Select The Difficulty Level");
builder.setSingleChoiceItems(items, -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
Intent i = new Intent(
getApplictionContext(),
MyActivity.class);
switch (item) {
case 0:
String msg = "Alert A";
Toast.makeText(
MyActivity.this,
msg, Toast.LENGTH_LONG).show();
break;
case 1:
String msga = "Alert B";
Toast.makeText(
MyActivity.this,
msga, Toast.LENGTH_LONG).show();
break;
case 2:
String msgz = "Alert C";
Toast.makeText(
MyActivity.this,
msgz, Toast.LENGTH_LONG).show();
break;
case 3:
String msge = "Alert E";
Toast.makeText(
MyActivity.this,
msge, Toast.LENGTH_LONG).show();
break;
}
}
});
levelDialog.dismiss();
levelDialog = builder.create();
levelDialog.show();
}
else if (position == 1) {
String msg = "1";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
} else if (position == 2) {
String msg = "2";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
}
else if (position == 3) {
String msg = "3";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
}
}
});
}
You are calling a function on levelDialog before instantiating it
levelDialog.dismiss();
levelDialog = builder.create();
levelDialog.show();
change it to
levelDialog = builder.create();
levelDialog.show();
levelDialog.dismiss();
But I'm not sure why you are calling dismiss() right there. If this doesn't solve it then please post logcat so we know where the NPE is. To be more clear, switching these lines should fix your NPE but dismiss() shouldn't be called right there.
Edit
Take out this
AlertDialog levelDialog=null;
and declare and initialize it here like so
final AlertDialog levelDialog = builder.create();
levelDialog.show();
and call dismiss() in your onClick() but use dialog.dismiss() instead of levelDialog.dismiss()
Also, its typically better to use Activity Context instead of Application Context so in your Intent you might change getApplicationContext() to MyActivity.this

Categories

Resources