In my application, I'm providing various Templates for the Text Message Body, as spinner list items , that can be selected and user can send them instead of typing message, But the problem is when user open the menu item to select template the application crashes. Spinner i've put in alert dialog box which is accessible through menu item.
Code for dialog box *
AlertDialog.Builder rdialog = new AlertDialog.Builder(MainActivity.this);
rdialog.setTitle("Select Message");
rdialog.setIcon(android.R.drawable.ic_input_get);
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
alertView = inflater.inflate(R.layout.rptsetting,null);
final Spinner fSpinner = (Spinner)alertView.findViewById(R.id.fSpinner);
String providers[] ={"Busy", "Good Morning", "In office"};
ArrayAdapter<String> adp = new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_spinner_dropdown_item,providers);
fSpinner.setAdapter(adp);
fSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> aparent, View arg1,
int pos, long arg3) {
String selectedItem = fSpinner.getSelectedItem().toString();
if(selectedItem.equals("Busy")){
body = "Currently Busy call again later, Thanks";
}
if(selectedItem.equals("Good Morning")){
body = "A very Good Morning, Have a nice day";
}
if(selectedItem.equals("In office")){
body = "Currently in office";
}
}
#Override
public void onNothingSelected(AdapterView<?> aparent) {
}
});
rdialog.setView(alertView);
rdialog.setNeutralButton("SUBMIT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog rdialog1 = rdialog.create();
rdialog1.show();
I've define body as global String so that it can be accessible by Sms Manager to use it as body of message to be send.
Log Cat
Thanks in advance!
First Correct this one like under onItemSelected(.....)
String selectedItem = aparent.getItemAtPosition(pos).toString();
if(selectedItem.equals("Busy")){
body = "Currently Busy call again later, Thanks";
}
if(selectedItem.equals("Good Morning")){
body = "A very Good Morning, Have a nice day";
}
if(selectedItem.equals("In office")){
body = "Currently in office";
}
And also cross check your body variable is not null
To get selected item from Spinner try using getItemAtPosition method of AdapterView. as:
#Override
public void onItemSelected(AdapterView<?> aparent, View arg1,
int pos, long arg3) {
String selectedItem = aparent.getItemAtPosition(pos).toString();
//...your code...
}
Related
I have a multi choice list inside an AlertDialog.
Reading the documentation of CHOICE_MODE_SINGLE, I thought that you could have one or no item checked but for me it behaves like a Radio Button List. It starts with all checkboxes unchecked by default by once I check one, it cannot be unchecked.
I tried hacking it with manual setItemChecked inside onClick but that is not a solution.
What am I doing wrong? How to achieve one or no checkbox in a ListView?
Here's my code:
builder.setMultiChoiceItems(titles, new boolean[titles.length], new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean b) {
if (selectedId == -1) {
selectedId = position;
} else {
if (selectedId == position) {
mDialog.getListView().setItemChecked(position, false);
selectedId = -1;
} else {
mDialog.getListView().setItemChecked(selectedId, false);
selectedId = position;
}
}
}
});
mDialog = builder.create();
mDialog.getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
your code isn't working because the method that you are using, setItemChecked, doesn't change the selected state when receive a false and is working on CHOICE_MODE_SINGLE, which is the normal behaviour of a group of radio buttons. You can see it by yourself with "Go To Implementation" in Android Studio (Ctrl + RightClick over the method).
Also, it's not recommended to use checkboxes for a single choice selector as it will confuse your users. You can easily get radio buttons replacing setMultipleChoiceItems by setSingleChoiceItems. It also apply the single choice mode to your ListView, so you can get rid of your last line.
To allow the user to perform an empty selection with radio buttons you have mainly 2 options:
Add an extra items to your list representing the empty selection option. Label it as "None", "Uncheck" or something similar
Add an extra button to your dialog to dismiss the dialog and return an empty selection.
Here you have a sample of implementation of the first option adding dynamically the empty item for a better re-usability ;)
Screenshot
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String title = "Select your favourite language";
String[] items = {"English", "Spanish", "Chinese", "Java"};
String emptyItemTitle = "NONE OF THEM";
int initialSelection = 0;
showSingleChoiceDialogWithNoneOption(title, items, initialSelection, emptyItemTitle);
}
private void showSingleChoiceDialogWithNoneOption(String title, final String[] titleItems, int initialSelection, String emptyItemTitle ) {
final String[] extendedItems = addEmptyItem(titleItems, emptyItemTitle);
final int[] selectedPosition = {initialSelection};
new AlertDialog.Builder(this)
.setTitle(title)
.setSingleChoiceItems(extendedItems, initialSelection, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedPosition[0] = which;
Log.d("MyTag", String.format("Selected item '%s' at position %s.", extendedItems[which], which));
}
})
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("MyTag", String.format("Confirmed the selection of '%s' at position %s.", extendedItems[selectedPosition[0]], selectedPosition[0]));
onSelectionConfirmed(selectedPosition[0]);
}
})
.show();
}
#NonNull
private String[] addEmptyItem(String[] titleItems, String emptyTitle) {
String[] tempArray = new String[titleItems.length + 1];
tempArray[0] = emptyTitle;
System.arraycopy(titleItems, 0, tempArray, 1, titleItems.length);
return tempArray;
}
private void onSelectionConfirmed(int position) {
if (position==0){
//Handle your empty selection
}else{
//Selected item at position
}
}
}
I am trying to create a pop-up dialog to allow the user of my android app to add a new field to a list on their main page.
I've done a bit of research and found the Dialog/alertDialog option, but i haven't been able to get it working correctly.
Here is my MainActivity class:
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
//final Dialog dialog = new Dialog(this); //!!! ERROR HERE !!! //
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
Button AddNewStudent = (Button) findViewById(R.id.AddNew);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
//db.addStudentProfile(new StudentProfile("Shannon", "White"));
//db.addStudentProfile(new StudentProfile(1,"Shannon", "White", "WhitehousePS", "30", "21" ));
/*AddNewStudent.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Using an alertDialog to get the user to enter in a new Student
dialog.setContentView(R.layout.add_new_student);
dialog.setTitle("Add a new student");
final EditText firstName=(EditText)dialog.findViewById(R.id.firstName);
final EditText surname=(EditText)dialog.findViewById(R.id.surname);
final EditText school=(EditText)dialog.findViewById(R.id.school);
final EditText age=(EditText)dialog.findViewById(R.id.age);
Button save=(Button)dialog.findViewById(R.id.save);
Button btnCancel=(Button)dialog.findViewById(R.id.cancel);
dialog.show();
}
});*/
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<StudentProfile> contacts = db.getAllStudents();
for (StudentProfile studProf : contacts) {
String log = "Id: "+studProf.getID()+" , First name: " + studProf.getFirstName() + ", Surname: " + studProf.getSurname() + ", School: " + studProf.getSchool() +
", Reading Level: "+ studProf.getReadingLevel() + ", Age: " + studProf.getAge();
// Writing Contacts to log
Log.d("Name: ", log);
}
db.getAllStudents();
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
It's linked to a very simple xml page that just has editible text fields.
My application won't even open with this code - i have tracked the issue down to this line:
final Dialog dialog = new Dialog(this);
at the top of my program.
IS this the best way to go about making a pop up dialog?
Also, what is the easiest way to pass the information back to the class to be stored in a database?
Any help would be much appreciated, thanks! :)
You can create some private variables at the top of your class, and get the text from the editText and put it into those variables in the dialog's button click handler method (where you have the 'sign in the user' comment.)
Sometimes it's also easyer to crate a dialog themed activity.
In my main class i've a button to call a class which shows a dialog box with an edittext. My problem is this - Main activity is not getting edittext value at the first run, if i run it for a second time, i get the old edittext value.
It seems the main activity class executes the full block of code and returns a previous value which is stored in the class, i've tried many methods including shared preference.
MainActivity.java
public class MainActivity extends Activity {
EditText comment_et,input_et;
Spinner spinner;
Button addbutton,reportbut;
String input_string,date,time,comment,item;
TextView date_tv,time_tv;
String temp[];
Datas datatemp;
String savedinput;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences prefs = getSharedPreferences("myprefs", 0);
savedinput= prefs.getString("KEY_SAVEDINPUT","");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)findViewById(R.id.spin1);
input_et = (EditText)findViewById(R.id.input_et);
addbutton = (Button)findViewById(R.id.addbutton);
reportbut = (Button)findViewById(R.id.report);
comment_et = (EditText)findViewById(R.id.comment_et);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
date_tv = (TextView)findViewById(R.id.date_tv);
time_tv = (TextView)findViewById(R.id.time_tv);
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
date = ""+mDay+"/"+mMonth+1+"/"+mYear;
time = ""+mHour+":"+mMinute;
date_tv.setText(date);
time_tv.setText(time);
int max_id = db.getDatasCount();
for(int i = 1; i<max_id+1 ;i++)
{
datatemp = db.getItemOnly(i);
String s = datatemp._item.toString();
list.add(" "+ s);
}
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true);
System.out.println("main : " +savedinput);
}
});
reportbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
startActivity(i);
}
});
spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
item = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Button submit = (Button)findViewById(R.id.save);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
comment = comment_et.getText().toString();
System.out.println("comment:"+comment);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addData(new Datas(item, comment, date, time));
Toast.makeText(getApplicationContext(), "Data Submitted Successfully",
Toast.LENGTH_LONG).show();
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Datas> datas = db.getAllDatas();
for (Datas d : datas) {
String log = "Id: "+d.getID()+" ,Item: " + d.getItem() + " ,Comment: " + d.getComment() + " ,Date: " + d.getDate() + ",Comment: " + d.getTime();
// Writing Contacts to log
Log.d("Item: ", log);
}
}
});
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
AlertDialogManager.java
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
String savedinput;
public void showAlertDialog(final Context context, String title, String message,
Boolean status)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
//setting input
final EditText input = new EditText(context);
alertDialog.setView(input);
// saving input to a string
savedinput = input.getText().toString();
System.out.println(savedinput);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("KEY_SAVEDINPUT", savedinput);
editor.commit();
System.out.println("from class "+savedinput);
}
});
// Showing Alert Message
alertDialog.show();
}
String getItem()
{
return savedinput;
}
}
and here is my logcat, just for further clarification
02-01 13:48:43.372: I/System.out(897): main : firstexecute
02-01 13:48:46.942: W/KeyCharacterMap(897): No keyboard for id 0
02-01 13:48:46.942: W/KeyCharacterMap(897): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-01 13:48:49.532: I/System.out(897): from class secondexecute
You have several issues here.
You shouldn't read savedValue in onCreate, you should do it only when you actually use it. See #ρяσѕρєяK answer.
alert.showAlertDialog is non blocking. So after dialog is shown line System.out.println("main : " + savedInput); is executed. It doesn't wait for your input. So you should call some other action beside saving to shared preferences on dialog's ok buttonn. This action should invoke logic that should happen after user entered some text in the dialog.
Update
public void showAlertDialog(final Context context, String title, String message,
Boolean status, final Spinner spinner)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
//setting input
final EditText input = new EditText(context);
alertDialog.setView(input);
// saving input to a string
savedinput = input.getText().toString();
System.out.println(savedinput);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
// do whatever you want with spinner and savedInput here.
}
});
// Showing Alert Message
alertDialog.show();
}
onClick to show dialog:
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true, (Spinner) findViewById(R.id.spin1));
Update 2
Apparently you need to add new item to your spinner adapter. For this you can create list of all items and pass this list along with adapter to dialog. When user enters string and press OK button onClick method adds this string to the list and call notifyDataSetChanged to update UI:
Add this in MainActivity:
List<String> spinnerItems;
In onCreate:
spinnerItems = new ArrayList<String>();
adapter = enw ArrayAdapter<String>(this, 0, spinnerItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Pass spinnerItems and adapter to showAlertDialog:
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true, spinnerItems, adapter);
And finally add text to list and notify adapter:
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
spinnerItems.add(savedInput);
adapter.notifyDataSetChanged();
}
});
you will need get latest value on Button click instead of onCreate to get latest value from SharedPreferences as :
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true);
savedinput= prefs.getString("KEY_SAVEDINPUT",""); //<<< get value here
System.out.println("main : " +savedinput);
}
});
or you will try to get value from onResume of Activity
This
savedinput = input.getText().toString();
is evaluated when it is run. Not when you call getItem(). The value you'll get is what it was, in this case, before the alert was displayed.
same logic goes for
savedinput= prefs.getString("KEY_SAVEDINPUT","");
I have a dialog setup that has two spinners connected to a cursor. I have worked through a couple of problems with the help of this site, but I can not seem to get past this point. Everything I find are things I have already tried.
The problem is that when I click on a spinner selection or click Submit to exit the dialog, the spinner value is not the value it should be. I am getting the package name with some code. I am trying to get the string from the spinner with .getSelectedItem().toString();
I currently have the code set up to use onItemSelected, but before that I tried to use the getItemSelected once Submit was clicked. Neither seem to work.
Here is the code for this section.
At the end the values are going into a textview. The value shown is "android.database.sqlite.sqliteCursor#414175e0"
Any ideas?
private void transfer() {
dialog = new Dialog(this, android.R.style.Theme_Holo_Light_Dialog_MinWidth);
dialog.setContentView(R.layout.transfer_dialog);
dialog.setTitle(R.string.transfer_accounts);
Button btnCancel = (Button)dialog.findViewById(R.id.btnCancel);
Button btnSubmit = (Button)dialog.findViewById(R.id.btnSubmit);
Cursor load_spinner = mDbHelper.spinnerAccounts();
startManagingCursor(load_spinner);
String[] columns = new String[] { RegisterDbAdapter.ACCOUNTS_ACCOUNT };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, load_spinner, columns, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFrom = (Spinner)dialog.findViewById(R.id.spinnerFrom);
spinnerTo = (Spinner)dialog.findViewById(R.id.spinnerTo);
spinnerFrom.setAdapter(mAdapter);
spinnerTo.setAdapter(mAdapter);
dialog.show();
spinnerFrom.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
fromAccount = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
spinnerTo.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
toAccount = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
btnCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
btnSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tvFrom.setText(fromAccount);
tvTo.setText(toAccount);
dialog.dismiss();
}
});
}
You need two separate adapters for two spinners.
You are only using one... each time you make a selection, the adapter sets your selection to your choice ( for both of the spinners since you have the same adapter backing each one ).
Create a second adapter and things should work more like you expect.
Also, try this in your onItemSelected method (using the parameter names you show):
String fromAccount = parent.getItemAtPosition(arg2).toString();
I think you have to use your cursor to get the String you want. Arg2 should be the selected position. Use it to place your cursor to the right data row and use the getstring method of the cursor to get the string from the database column.
So I finally got it to work. Thanks for the suggestions, I really do appreciate them, but they didn't work for me. I am not sure why the code will not return the value, since the way I tried it supposedly works for others.
Anyway, I found a way to get my values by using 'Long arg3'. Since it holds the rowId of the value in the table, I used that to return the selection in the spinner. I am posting the code for this below.
Thanks again.
The code from the selected spinner:
spinnerFrom.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
getAccountName(arg3);
fromAccount = returnAccount;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
And here is the method I wrote to return the value I wanted. I put it a separate method because it is getting used from multiple spinners. The code:
private void getAccountName(long arg3) {
if (returnAccount != null){
returnAccount = null;
}
RegisterDbAdapter tAdaptor = new RegisterDbAdapter(this);
tAdaptor.open();
Cursor tCursor = tAdaptor.fetchAccount(arg3);
startManagingCursor(tCursor);
returnAccount = tCursor.getString(1);
}
this question is is similar to this
* Android - Listview delete item and Refresh
and this (the same , but I added the full code here to check if I have any problems in my code):
please give me code example. . .
can i call an intent to refresh my list ?
I cant refresh my adapter with :
adapter.notifyDataSetChanged();
I tried:
adapter.remove(adapter.getItem(pos));
but without success, just one time (weird...).
there is another answer there:
Call that Activity once again Using Intent
sombody can give me the exact code for this (or for the adapter/cursor) ?
I am trying this for a couple of hours without success.
my full code:
protected void onCreate (Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.personalmessageview);
headtitle= getIntent().getExtras().getString("head");
setTitle(headtitle);
personalresults = getIntent().getExtras().getStringArrayList("personalres");
personalresultswithtime = getIntent().getExtras().getStringArrayList("personalrestime");
// setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,personalresults));
ListView list = (ListView)findViewById(R.id.listview_personal);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, personalresults);
list.setAdapter(adapter);
registerForContextMenu(list);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
String time = personalresultswithtime.get(pos).toString();
Show_Alert_box(v.getContext(),"Please select action.",time,pos);
return true;
}
});
public void Show_Alert_box(Context context, String message,String time,int position)
final String timestamp = time;
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(getString(R.string.app_name));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try
{
db = databaseHelper.getWritableDatabase();
db.delete("messages","timestamp" + "=?", new String[] { timestamp });
Log.d("DB"," delete! ");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PersonalMessageView.this, android.R.layout.simple_list_item_1, personalresults);
adapter.remove(adapter.getItem(pos)); //not working t all! why ?
list.notify();
list.invalidate();
personalresults.remove(pos);
personalresultswithtime.remove(pos);
adapter.notifyDataSetChanged();
db.close();
}
catch(Exception e)
{
}
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
} });
alertDialog.setMessage(message);
alertDialog.show();
}
Inside your onClick of Dialog, you are dealing with an entirely new Adapter.There is no accociation of adapter(inside onClick()) to the listView Either you should say list.setAdapter(adapter); inside the onClick() method or make the adapter global.
instead of using
adapter.remove(adapter.getItem(pos));
use
string str=list.getItemAtPosition(index).toString();
personalresults.remove(str);
adapter.notifyDataSetChanged();