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....
Related
Ive been trying to get my listview to update after removing an item. Here's what I have so far:
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String str = null;
public void onItemClick(AdapterView<?> arg0, final View view, int arg2, long arg3) {
//TextView txtview = (TextView)view.findViewById(R.id.txtview);
final String item = ((TextView) view.findViewById(R.id.txtview)).getText().toString();
str = item;
final long arr = arg3;
final String arg22 = longToString(arg3);
//Creating an Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(Home.this);
builder.setMessage("Are you sure you want to delete the hike " + str + " ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase db1=openOrCreateDatabase("hikeManager", MODE_PRIVATE, null);
DatabaseHandler db = new DatabaseHandler(Home.this);
String table = "hikes";
Cursor c = db1.rawQuery("select id from "+ table + " where name='"+item+"'", null);
int dhike = c.getColumnIndex("name") + 1;
try {
Hike hike = db.getHike(arr + 1);
db.deleteHike(hike);
Log.d("DLT", "Deleted hike at index " + arr);
//db.updateList(adapter, myList, listItems);
adapter.remove(arg22);
adapter.notifyDataSetChanged();
//updateData();
db.close();
} catch (CursorIndexOutOfBoundsException e) {
Log.d("DLT", "Failed to delete: " + e.getMessage());
db.close();
}
//db.updateList(adapter, myList, listItems);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
I Have quite a bit of unused code in there, as I have tried a few different methods to get this to work, but have failed so far. Here is updateData:
private void updateData() {
// Get all of the notes from the database and create the item list
DatabaseHandler db = new DatabaseHandler(this);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txtview, listItems);
final ListView myList = (ListView) findViewById(R.id.cardListView);
int num = db.getHikesCount();
for (int i=1; i<num+1; ++i){
Hike name = db.getHike(i);
String nam = name.getName();
listItems.add(nam);
}
myList.setAdapter(adapter);
db.close();
}
The updateData does have some unintended consequences when I use it to update the view after adding an item to a non-empty list, but it works for now. The item is successfully deleted, since I can close the app and reload it and the item will be gone. I just cant seem to get it to update properly for me.
Just use
adapter.notifyDataSetChanged();
In my Android app I have a DB where store Phrase objects, and Theme objects, among other data. These phrases have an attribute sourceLanguage (String) and an isSelected attribute (String too, since SQLITE doesn't have boolean - can't recall why I didn't use 0 and 1, but that's not relevant). The themes contain one or more phrases.
I have one activity where the user is given a listView with a list of themes. When he picks a theme, an alert dialog displays with a checkbox list of phrases so he can select one or more. I'd like to update each phrase in the DB using the information from the AlertDialog checkboxes, changing isSelected to "true" or to "false", depending on the user's choice.
My difficulty is that the examples I found online so far allow to save the "true" state of the elements, but not the "false". So if a phrase is stored as "true", and then changed to "false", it will simply not appear in the selectedItems, and I don't have a reference to access it and modify it to "false". I've come up with a couple of solutions, but I'm not confident about any, and this is where you could help me.
My AlertDialog method:
private void showAlertDialog(int themeId, String themeName) {
// TODO Auto-generated method stub
// Build the list of phrases for respective theme and list of previously selected items
final DatabaseHandler db = new DatabaseHandler(this);
List<Phrase> allThemePhr = db.getPhrases("with_theme", themeId, null); // all phrases for selected theme
CharSequence[] sourceLanguageAllPhr = new String[allThemePhr.size()]; // source language of all phrases for selected theme
boolean[] selectedItems = new boolean[allThemePhr.size()]; // selected items only
final List<String> sourceLanguageSelectedPhr = new ArrayList<String>();
final List<String> sourceLanguageNOTSelectedPhr = new ArrayList<String>();
for (int i = 0 ; i < allThemePhr.size() ; i++){
sourceLanguageAllPhr[i] = allThemePhr.get(i).getSource_language();
selectedItems[i] = false;
if (allThemePhr.get(i).getItemSelected() == "true"){
selectedItems[i] = true;
sourceLanguageSelectedPhr.add(allThemePhr.get(i).getSource_language());
}
}
// Build the dialog
#SuppressWarnings("rawtypes")
final ArrayList selectedPhrases = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(PickTheme.this);
builder.setTitle(themeName)
.setMultiChoiceItems(sourceLanguageAllPhr, selectedItems, new DialogInterface.OnMultiChoiceClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
selectedPhrases.add(which);
//sourceLanguageSelectedPhr.add(selectedPhrases.get(which).toString());
} else if (selectedPhrases.contains(which)){
selectedPhrases.remove(Integer.valueOf(which));
//sourceLanguageSelectedPhr.remove(selectedPhrases.get(which).toString());
//sourceLanguageNOTSelectedPhr.add(selectedPhrases.get(which).toString());
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//for (String sourceLanguage : sourceLanguageSelectedPhr){
//db.updatePhrase(sourceLanguage, "true");
//Log.i("selectedPhrase", selectedPhrases.get(which).toString());
//}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
In my DatabaseHelper class, I've defined these methods that can be used to update phrases:
// updating a phrase
public int updatePhrase(Phrase phrase){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_PHRASE_ID, phrase.getWord_id());
values.put(COLUMN_SOURCE_LANGUAGE, phrase.getSource_language());
values.put(COLUMN_TARGET_LANGUAGE, phrase.getTarget_language());
values.put(COLUMN_PHRASE_REMINDER_DATE, phrase.getTarget_language());
values.put(COLUMN_PHRASE_THEME_ID, phrase.getTheme_id());
values.put(COLUMN_PHRASE_REMINDER_ID, phrase.getTheme_id());
int phraseUpdated = db.update(PHRASES_TABLE, values, COLUMN_PHRASE_ID + " =?", new String[] {String.valueOf(phrase.getWord_id())});
db.close();
return phraseUpdated;
}
// updating a phrase based on given source_language
public void updatePhrase(String sourceLanguage, String isSelected){
SQLiteDatabase db = this.getWritableDatabase();
String updateStatement = "UPDATE " + PHRASES_TABLE
+ " SET " + COLUMN_ITEM_SELECTED + " = " + isSelected
+ " WHERE " + COLUMN_SOURCE_LANGUAGE + " = " + sourceLanguage;
db.execSQL(updateStatement);
}
So far, I've thought of a few solutions, this one seemed the best: when a phrase is selected / de-selected, get it from the allThemePhr, update the object accordingly, and save it in another List. If user clicks OK, use that list to update the DB. My problem is: how to I match the value of which with the respective object in allThemePhr ? If I can figure out how to get the checkbox text, that should be acceptable, since it corresponds to the source_language attribute of phrase?
Maybe there is a simpler solution?
Thanks
There is a match between the index which and the index the phrase objects have in the global phrases List allThemePhr, so no need to go through the string of the checkbox / the value of sourceLanguage.
So, I simply created a map where I store the correspondence between the index which and the status of the checkbox (isChecked). Then, if the user presses "OK", I iterate through that map, get the corresponding phrase object from allThemePhr and update it.
Here is the final code:
private void showAlertDialog(int themeId, String themeName) {
// TODO Auto-generated method stub
// Build the list of phrases for respective theme and list of previously selected items
final DatabaseHandler db = new DatabaseHandler(this);
final List<Phrase> allThemePhr = db.getPhrases("with_theme", themeId, null); // all phrases for selected theme
final Map<Integer, Boolean> selectionChanges = new HashMap<Integer,Boolean>();
CharSequence[] sourceLanguageAllPhr = new String[allThemePhr.size()]; // source language of all phrases for selected theme
boolean[] selectedItems = new boolean[allThemePhr.size()]; // selected items only
for (int i = 0 ; i < allThemePhr.size() ; i++){
Phrase phrase = allThemePhr.get(i);
sourceLanguageAllPhr[i] = phrase.getSource_language();
if (phrase.getItemSelected().equals("true")){
selectedItems[i] = true;
}
}
// Build the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(PickTheme.this);
builder.setTitle(themeName)
.setMultiChoiceItems(sourceLanguageAllPhr, selectedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
selectionChanges.put(which, isChecked);
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
for (Map.Entry<Integer, Boolean> entry : selectionChanges.entrySet()){
Phrase phrase = allThemePhr.get(entry.getKey());
phrase.setItemSelected(String.valueOf(entry.getValue()));
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
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();
This is my code to edit/update which I am doing throgh a custom alertdialog which contains the data fetched frm database. Now when the inputs provided are incorrect I want to show other alertdialog on top of this providing some message to user. When the user dismisses this message alertdialog, the previous one which is used for update should be visible. How can I do that?
public class CountryEdit extends ListActivity{
private Long mRowId;
private CountryDbAdapter mDbHelper;
public static final String PROVIDER_NAME = "assignment2.demos.MyCountriesCP";
public static final String uriString = "content://"+ PROVIDER_NAME +"/countries";
public static final Uri CONTENT_URI = Uri.parse(uriString);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(CONTENT_URI, null, null, null, getIntent().getExtras().getString("SORT_ORDER"));
String[] from = new String[] { "year", "country" };
int[] to = new int[] { R.id.year, R.id.country };
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.country_row,
c, from, to);
setListAdapter(sca);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(assignment2.demos.MyCountriesActivity.KEY_ROWID)
: null;
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(assignment2.demos.MyCountriesActivity.KEY_ROWID)
: null;
}
populateFields();
}
private void populateFields() {
LayoutInflater inflater=LayoutInflater.from(this);
final View addView=inflater.inflate(R.layout.add_country, null);
Cursor c = getContentResolver().query(CONTENT_URI.buildUpon().
appendPath(String.valueOf(mRowId)).build(), null, null, null, null);
/* Read alert input */
final EditText editCountry =(EditText)addView.findViewById(R.id.editCountry);
final EditText editYear =(EditText)addView.findViewById(R.id.editYear);
editCountry.setText(c.getString(c.getColumnIndex("country")));
editYear.setText(c.getString(c.getColumnIndex("year")));
new AlertDialog.Builder(this)
.setTitle("Edit country/year")
.setView(addView)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
String country = editCountry.getText().toString();
if(country.trim().length()>0 && editYear.getText().toString().trim().length()>0){
int year = Integer.parseInt(editYear.getText().toString());
ContentValues updateValues = new ContentValues();
updateValues.put(mDbHelper.COUNTRY, country);
updateValues.put(mDbHelper.YEAR, year);
getContentResolver().update(
CONTENT_URI.buildUpon().appendPath(String.valueOf(mRowId)).build(), updateValues, null, null);
finish();
}
else{
new AlertDialog.Builder(CountryEdit.this)
.setTitle("Invalid Inputs!")
.setMessage("You need to enter Country AND Year.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
finish();
}
}).show();
// Toast.makeText(CountryEdit.this,
// "You need to enter Country AND Year.", Toast.LENGTH_LONG).show();
//finish();
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
// ignore, just dismiss
finish();
}
})
.show();
}
}
The first alert dialog is dismissing itself when the second is about to show (when the click listener finishes). You can't avoid that.
There's a dirty hack where you can override the click listener created by the builder like this:
create().getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener( ... }
But I don't recommend to do that if you don't know what you're doing (it might break the internet ;-).
You would have to dismiss the dialog yourself. If you don't do that it will never close, the user will see it forever and would have to kill your app to get it started again.
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();
}
}