In my code i want to close alert dialog immediately and start activities, when i select options mentioned in if- elseIf statements. I do not want ok and cancel buttons . My code work fine (statements inside if statements work but alert dialogue still there ). Thanks for help
final AlertDialog.Builder builder =
new AlertDialog.Builder(arg0.getContext());
builder.setTitle("Favourities Management");
// TODO Auto-generated method stub
int selected = 0;
builder.setSingleChoiceItems(values, selected, new DialogInterface.OnClickListener() {
#
Override
public void onClick(DialogInterface dialog, int which) {
if (values[which] == "Select Benificiary") {
Intent registerUser = new Intent(FinalUtilityBillPayment.this, ListViewBeneficiaryBillPayment.class);
FinalUtilityBillPayment.this.startActivity(registerUser);
startActivityForResult(registerUser, 1);
} else if (values[which] == "Add Benificiary") {
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE + " (ID INTEGER PRIMARY KEY, ReferenceNo TEXT, Mobile Text);");
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG).show();
}
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
mydb.execSQL("INSERT INTO " + TABLE + "(ReferenceNo, Mobile) VALUES('" + ref.getText().toString() + "','" + mob.getText().toString() + "')");
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error in inserting into table", Toast.LENGTH_LONG).show();
}
} else if (values[which] == "Delete Benificiary") {
Intent registerUser = new Intent(FinalUtilityBillPayment.this, ListViewDeleteBeneficiaryBillPayment.class);
//startActivityForResult(registerUser, 1);
FinalUtilityBillPayment.this.startActivity(registerUser);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
My sugestion is;
final AlertDialog.Builder builder = new AlertDialog.Builder(arg0.getContext());
builder.setTitle("Favourities Management");
// TODO Auto-generated method stub
int selected = 0;
builder.setSingleChoiceItems(values,
selected,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(values[which]=="Select Benificiary"){
selectBenificiary();
//see more about "dialog.dismiss()" in http://developer.android.com/reference/android/app/Dialog.html#dismiss()
dialog.dismiss();
} else if (values[which]=="Add Benificiary"){
addBenificiary();
//see more about "dialog.dismiss()" in http://developer.android.com/reference/android/app/Dialog.html#dismiss()
dialog.dismiss();
} else if (values[which]=="Delete Benificiary"){
deleteBenificiary();
//see more about "dialog.dismiss()" in http://developer.android.com/reference/android/app/Dialog.html#dismiss()
dialog.dismiss();
}
}
});
AlertDialog alert = builder.create();
alert.show();
//Add parameter case necessary
public void selectBenificiary(){
Intent registerUser = new Intent(FinalUtilityBillPayment.this,ListViewBeneficiaryBillPayment.class);
// FinalUtilityBillPayment.this.startActivity(registerUser);
startActivityForResult(registerUser, 1);
}
//Add parameter case necessary
public void addBenificiary(){
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY, ReferenceNo TEXT, Mobile Text);");
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG).show();
}
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("INSERT INTO " + TABLE + "(ReferenceNo, Mobile) VALUES('"+ref.getText().toString() +"','"+ mob.getText().toString() +"')");
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error in inserting into table", Toast.LENGTH_LONG).show();
}
}
//Add parameter case necessary
public void deleteBenificiary(){
Intent registerUser = new Intent(FinalUtilityBillPayment.this, ListViewDeleteBeneficiaryBillPayment.class);
//startActivityForResult(registerUser, 1);
FinalUtilityBillPayment.this.startActivity(registerUser);
}
Try this... in that onClick() you can see the DialogInterface dialog that dialog name.
use this dialog.cancel(); before calling the other activity
dialog.cancel();
Intent registerUser = new Intent(FinalUtilityBillPayment.this,ListViewBeneficiaryBillPayment.class);
//FinalUtilityBillPayment.this.startActivity(registerUser);
startActivityForResult(registerUser, 1);
call .dismiss() for closiong it, also use simple Dialog to get the possibility of setting custom layout for it
Dialog alert = new Dialog(context);
alert.setContentView(layoutResID);
You have to dismiss the alert dialogue. Try this:
Dialogue.dismiss();
Related
I've been having a weird issue lately regarding my database-driven android app. I use the code UPDATE before with no problem but now it won't allow me to update changes to my records.
I did try to log if it's saving the changes I've made but it doesn't.
Here's the code I'm using:
private void initControls() {
userInput = (EditText) findViewById (R.id.editTextDialogUserInput);
save = (Button) findViewById (R.id.btSave);
cancel = (Button) findViewById (R.id.btCancel);
save.setOnClickListener(this);
cancel.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
stID = extras.getString("dog_id");
dog_name = extras.getString("dog_name");
cursor = dbHelper.fetchbBreedByName(dog_name);
strDesc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
Log.d("Animal ID", "Animal ID is " + stID + " and breed is " + dog_name);
userInput.setText(strDesc);
}
}
private void checkDatabaseConnection() {
// TODO Auto-generated method stub
dbHelper = new DBHelper(this);
try {
dbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btSave:
if(userInput.equals("")){
Toast.makeText(this, "No input", Toast.LENGTH_SHORT).show();
}
else {
id = Long.valueOf(stID);
dbHelper.updateDescription( id, userInput.getText().toString() );
Toast.makeText(this, "Description has been updated successfully!",
Toast.LENGTH_SHORT).show();
strDesc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
Log.d("Updated", dog_name + " " + strDesc);
Intent i = new Intent(this, DogClass.class);
startActivity(i);
finish();
}
break;
case R.id.btCancel:
userInput.setText("");
break;
}
}
#Override
protected void onDestroy() {
dbHelper.close(); // close DB
cursor.close(); // close cursor
super.onDestroy();
}
Whole code can be viewed here
I really don't know what's wrong, anybody here has experienced this before? Might as well help me figure out what I'm missing in my code. Help is pretty much appreciated. Thanks.
Try to use update method like this..
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(IConstants.FOLDER_LOCKED, isSelected);
database.update(FOLDER_TABLE, cv, IConstants.FOLDER_NAME + "= ?",
new String[] { foldername });
Hello I’m making a budget application that will allow you to look at expeances entered and if need be delete them I can call the method run thro it and it wont have a issue but when I check to see if it worked it hasnt I’ve tried but cant figure out why this doesn’t work. I use a alert dialog to confirm that they want to delete.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle("DELETE "+position);
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you whant to delete Expeance "+position)
.setCancelable(false)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String[] po = position.split(" ");
String date = po[0];
date = date +".tar.gz";
entry.open();
entry.deleteByDate(date);
entry.close();
recreate();
}
})
.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();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
and here is the code for the method
public SQLiteDatabase deleteByDate(String date2)
{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE2, KEY_DATE + " =?", new String[] { date2 });
ourDatabase.delete(DATABASE_TABLE4, KEY_DATE + " =?", new String[] { date2 });
return ourDatabase;
}
use Pattern.compile for replacing "/" with "-" as instead of date.replace("/", "_"):
Pattern p = Pattern.compile("/");
String date = po[0];
Matcher matcher = p.matcher(date);
date = matcher.replaceAll("_");
date = date +".tar.gz";
//your code here....
My question is how can i clear the editText field after i have saved what i have written to it to the database? I currently can input text using the nameEditText field but when i click the InsertButton, it does not clear the for. I just want to clear the form not the value or string in the Database...This is the insert button i want to also use as a clear method:
class InsertButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
if("".equals(nameEditText.getText().toString()))
{
Toast toast = Toast.makeText(Entername.this, "Sorry, you must input both the name and the address!", Toast.LENGTH_LONG);
toast.show();
}
else
{
long flag = 0;
int id = 1;
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("user_name", new String[]{"count(*) ID"}, null, null, null, null, null);
while(cursor.moveToNext())
{
int idFromDatabase = cursor.getInt(cursor.getColumnIndex("ID"));
if(idFromDatabase != 0)
{
id = 1 + idFromDatabase;
}
}
ContentValues values = new ContentValues();
values.put("ID", id);
values.put("name", nameEditText.getText().toString().trim());
//values.put("address", addressEditText.getText().toString().trim());
flag = db.insert("user_name", null, values);
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this, "You have successful inserted this record into database! ", Toast.LENGTH_LONG);
toast.show();
db.close();
return;
}
else
{
Toast toast = Toast.makeText(Entername.this, "An error occured when insert this record into database!", Toast.LENGTH_LONG);
toast.show();
db.close();
return;
}
}
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
You need to call:
nameEditText.setText("");
addressEditText.setText("");
So, do the following change in your if condition when adding to database is successful:
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this,
"You have successful inserted this record into database! ",
Toast.LENGTH_LONG);
toast.show();
db.close();
//clearing edittexts
nameEditText.setText("");
addressEditText.setText("");
return;
}
you last insert after editText in to set null values
EditText text;
text.setText("");
this is my code
`I have created one table, but i want to create two and when i hit the "show" button, i want to be able to select contents from both tables and show them...this is my code...am having problems creating two tables and showing them:
public class Entername extends Activity {
private Button showButton;
private Button insertButton;
private TextView nameEditText;
private TextView addTextView;
private Button doneButton;
public DatabaseHelper dbHelper = new DatabaseHelper(Entername.this,"pubgolfdatabase",2);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.entername);
addTextView = (TextView)findViewById(R.id.textView1);
doneButton= (Button)findViewById(R.id.doneButton);
insertButton = (Button)findViewById(R.id.addButton);
nameEditText = (EditText)findViewById(R.id.name);
showButton =(Button)findViewById(R.id.button1);
showButton.setOnClickListener(new showButtonListener());
insertButton.setOnClickListener(new InsertButtonListener());
doneButton.setOnClickListener(new DoneButtonListener());
/** create the database if it dosen't exist **/
SQLiteDatabase db = dbHelper.getWritableDatabase();
try
{
db.execSQL("create table user_name(ID integer, name varchar(90));");
}
catch(Exception e)
{
e.printStackTrace();
}
}
class InsertButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
if("".equals(nameEditText.getText().toString()))
{
Toast toast = Toast.makeText(Entername.this, "Sorry, you must input both the name and the address!", Toast.LENGTH_LONG);
toast.show();
}
else
{
long flag = 0;
int id = 1;
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("user_name", new String[]{"count(*) ID"}, null, null, null, null, null);
while(cursor.moveToNext())
{
int idFromDatabase = cursor.getInt(cursor.getColumnIndex("ID"));
if(idFromDatabase != 0)
{
id = 1 + idFromDatabase;
}
}
ContentValues values = new ContentValues();
values.put("ID", id);
values.put("name", nameEditText.getText().toString().trim());
flag = db.insert("user_name", null, values);
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this, "You have successful inserted this record into database! ", Toast.LENGTH_LONG);
toast.show();
db.close();
//clear fields //clearing edittexts
nameEditText.setText("");
return;
}
else
{
Toast toast = Toast.makeText(Entername.this, "An error occured when insert this record into database!", Toast.LENGTH_LONG);
toast.show();
db.close();
//clear fields
//clearing edittexts
nameEditText.setText("");
return;
}
}
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
class DoneButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
Intent myIntent = new Intent(v.getContext(), Pickholespubs.class);
startActivityForResult(myIntent, 0);
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
class showButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
String display = "";
SQLiteDatabase db = dbHelper.getWritableDatabase();
/** the result will be loaded in cursor **/
Cursor cursor = db.query("user_name", new String[]{"ID","name"}, null, null, null, null, null);
/** check if the table is empty **/
if (!cursor.moveToNext())
{
addTextView.setText("No data to display, please make sure you have already inserted data!");
db.close();
return;
}
cursor.moveToPrevious();
/** if the table is not empty, read the result into a string named display **/
while(cursor.moveToNext())
{
int ID = cursor.getInt(cursor.getColumnIndex("ID"));
String name = cursor.getString(cursor.getColumnIndex("name"));
display = display + "\n"+"Player"+ID+", Name: "+name;
}
/** display the result on the phone **/
addTextView.setText(display);
db.close();
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
}`
A Simple Answer would be No you can not do it. As Create Table Syntax doesn't allow two DML operations at a same time.
But the alternet way is like as follows,
Create Table table1 ( column list ); Create Table table2 ( column list );
This could be possible. Moral is there must be a ; (semicolon) after each Create Table syntax is completed).
I want to pass a variable to an outer function when user clicks on "OK" in AlertDialog.
I'm trying this for example but it won't recognize the Variable (Yup).
public final void deleteBookmark(Cursor cur, int pos) {
//fetching info
((Cursor) cur).moveToPosition(pos);
String bookmark_id = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns._ID));
String bookmark_title = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns.TITLE));
//asking user to approve delete request
AlertDialog alertDialog = new AlertDialog.Builder(Dmarks.this).create();
alertDialog.setTitle("Delete" + " " + bookmark_title);
alertDialog.setIcon(R.drawable.icon);
alertDialog.setMessage("Are you sure you want to delete this Bookmark?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
**String Yup = "yes";**
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Context context = getApplicationContext();
Toast.makeText(context, "canceled" , Toast.LENGTH_SHORT).show();
} });
alertDialog.show();
**if (Yup == "yes")** {
//deleting if user approved
getContentResolver().delete(Browser.BOOKMARKS_URI, "_id = " + bookmark_id, null);
//notifying user for deletion
Context context = getApplicationContext();
Toast.makeText(context, bookmark_title + " " + "deleted" , Toast.LENGTH_SHORT).show();
}
}
I know the code is a bit messed up but it's only for the sake of understanding.
Appreciate the help!
Yup is not being recognized because you create the string in the onClick method, and it gets recycled when onClick is done.
I recommend just getting rid of Yup, because even if you fix this, you'll have problems. The dialog will pop up, but by the time the user selects, the application will already have gone through the if statement, so Yup never has a chance to equal "Yes". In other words, the dialog box doesn't pause your code and wait for the user input before going through "if (Yup == "yes"). Also, the if statement should look like this: if (Yup.equals("yes")), otherwise, it will return false everytime.
I would make your code look like this:
public final void deleteBookmark(Cursor cur, int pos) {
//fetching info
((Cursor) cur).moveToPosition(pos);
final String bookmark_id = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns._ID));
final String bookmark_title = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns.TITLE));
//asking user to approve delete request
AlertDialog alertDialog = new AlertDialog.Builder(Dmarks.this).create();
alertDialog.setTitle("Delete" + " " + bookmark_title);
alertDialog.setIcon(R.drawable.icon);
alertDialog.setMessage("Are you sure you want to delete this Bookmark?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//deleting if user approved
getContentResolver().delete(Browser.BOOKMARKS_URI, "_id = " + bookmark_id, null);
//notifying user for deletion
Context context = getApplicationContext();
Toast.makeText(context, bookmark_title + " " + "deleted" , Toast.LENGTH_SHORT).show();
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Context context = getApplicationContext();
Toast.makeText(context, "canceled" , Toast.LENGTH_SHORT).show();
} });
alertDialog.show();
}
}