listview does not get updated android - android

I am very new to Android and am trying to create an app for travel help. It has a couple of components including -> enabling the user to customize a checklist. Apart from the default list, items can be added and deleted.
For adding,
I'm using a dynamic layout through the class file with no XML. It works perfectly :)
For deleting an item from the list,
I created an adpater, a listview and am trying to delete the selected item. With the help of a couple of "toasts", I am able to derive that, an item is being deleted from the list, but the view is not getting updated.
I have checked and tried numerous solutions, but none of them seem to be working. I am attching my java file, in which the display and customization of the list takes place.
The code seems a little long, but its fairly easy to understand. Any help would be greatly appreciated! :)
public class Dynamic extends ListActivity{
public String[] A = new String[100];
public String[] B = new String[100];
public int j=0, m=0, b=0, tot1=0, tot2=0;
public int a[]=new int[100];
CheckBox c, cc;
ArrayList<String> list2 = new ArrayList<String>();
ArrayList<String> list4 = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayAdapter<String> adapter2;
private SparseBooleanArray sba;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
final LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
final ListView list3=new ListView(this);
list3.setId(android.R.id.list);
list3.setChoiceMode(list3.CHOICE_MODE_MULTIPLE);
ll.addView(list3);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, list2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
A = extras.getStringArray("var");
int i = extras.getInt("var2");
B = extras.getStringArray("var3");
int k = extras.getInt("var4");
for (j=0;j<i;j++)
{
cc = new CheckBox(this);
cc.setText(A[j]);
ll.addView(cc);
list2.add(A[j]);
adapter.notifyDataSetChanged();
}
for (m=0;m<k;m++)
{
cc = new CheckBox(this);
cc.setText(B[m]);
ll.addView(cc);
list2.add(B[m]);
adapter.notifyDataSetChanged();
}
}
Button b = new Button(this);
b.setText("Delete Item");
ll.addView(b);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Dynamic.this);
alertDialog.setTitle("Confirm Delete...");
alertDialog.setMessage("Are you sure you want to delete the selected item from the list?");
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
sba=new SparseBooleanArray();
sba.clear();
sba=list3.getCheckedItemPositions();
ListView lv = getListView();
Toast.makeText(getApplicationContext(), "checked " + sba, Toast.LENGTH_SHORT).show();
int itemCount = getListView().getCount();
Toast.makeText(getApplicationContext(), "calc done " + itemCount, Toast.LENGTH_SHORT).show();
for(int i=itemCount-1; i >= 0; i--){
Toast.makeText(getApplicationContext(), "in the loop " + i, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), " " + sba.get(i), Toast.LENGTH_SHORT).show();
list2.add((list2.get(i)));
Toast.makeText(getApplicationContext(), " " + list2.get(i), Toast.LENGTH_SHORT).show();
adapter.remove(list2.get(i));
list3.invalidate();
adapter.notifyDataSetChanged();
list3.setAdapter(adapter);
Toast.makeText(getApplicationContext(), " " + list2, Toast.LENGTH_SHORT).show();
}
sba.clear();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Toast.makeText(getApplicationContext(), "The item has NOT been deleted!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
alertDialog.show();
setListAdapter(adapter);
}
});
this.setContentView(sv);
}
}

in order to update your listView try this in your adampter
notifyDataSetChanged();
But You should run it on the UI thread. Create an handler within the UI thread and then post Runable to it
like this
private class Asyn_SaveData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//Do something here that will run in backGround
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//and this function is called automatically by doInBackground
// after it finish its work
//in your example refresh your ListView
notifyDataSetChanged();
}
}
and to use the AsyncTask
new Asyn_SaveData().execute(null,null,null);
Just remembre AsyncTask must be subClassed
or
myListView.invalidateViews();

Related

ListView updates the entry only when the application is restarted again

In this application, I have a listview and a sqlitedatabase. There is a floating action button which on clicking displays a dialog box containing two edittext one for name and another for number. The problem is that the after clicking on the add option of the dialog box the entry is not shown on the listview. But when the activity is destroyed and onCreate is called again on the activity , the entry is shown.
I tried using adapter.notifyDataSetChanged() but it doesn't work. The code is shown below :
Code
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
Cursor cursor=manager.fetch();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),
R.layout.row_item, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
/*adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();*/
insertData(name.getText().toString(),phone.getText().toString());
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
Some of the statements are commented because I tried to get the desired result but couldn't get it.
There's a couple things here you have to change. Taking a look at this code:
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) && !TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(), "Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
When you click the "Add" button, right away you call adapter.notifyDataSetChanged();. In your case, you are only supposed to call that after you have added items to listView, but you haven't added anything yet.
You insert into your database using manager.insert(name.getText().toString(), phone.getText().toString());, but you don't update listView with your newly added data. You need to insert that data to the database, and then also add that data to listView.
Now you can call adapter.notifyDataSetChanged();.
I would recommend that when you want to insert into your database, create a method which will insert the data, add the new data to the listView, and then tell the adapter to refresh.
Edit
Regarding your recent edit, there's still a few things that need to be taken care of.
You should not have listView.setAdapter(adapter) in the method. You had it right the first time (in onCreate() but before the dialog builder).
You call manager.insert(fname,phnumber);, but still do not add the newly inserted data to listView.
Here's pseudocode for what you should have in your method:
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
// Code to add the data you just inserted into the manager above to `listView`.
adapter.notifyDataSetChanged();
}
Remember, adapter.notifyDataSetChanged(); only updates listView if there's changes to listView, and as of right now you haven't added/deleted/modified listView.
After you insert the entries in your database, you should fetch the data again so that your list has the newest entry. So you can either modify your code to be able to add a data point to the list you are passing to the adapter or refetch the data from the database after insertions and before notifyDatasetChanged().
i have did some changes into the code please try it and let me know if it is helpful or not
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),R.layout.row_item, cursor, from, to, 0);
//adapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
Cursor cursor = manager.fetch();
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}}
Try to use notifyDataSetChanged after insert operation. In all place where you call(try to call) notify manager data isn't change yet.

Add a Multiple-Delete option in ListView Android

In my app, information like file names are stored in the externally storage. They are then implemented into the app with the help of ListView. I can delete files individually with OnItemLongClickListener() but I want to select multiple files in ListView and then click a Delete button. How can I do this? My MainActivity file is below:
public class MainActivity extends AppCompatActivity {
ArrayList<FileName> filenames;
ListViewAdapter adapter;
ListView lv_filenames;
public Handler handler;
private String _path = Environment.getExternalStorageDirectory() + "/sample_directory/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditorManager manager = new EditorManager(getApplicationContext());
manager.CreateNewDirectory();
lv_filenames = (ListView) findViewById(R.id.list);
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
filenames = manager.GetList();
adapter = new ListViewAdapter(getApplicationContext(), R.layout.listView, filenames);
lv_filenames.setAdapter(adapter);
lv_filenames.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int file_name, long l) {
final File deleteFile = new File(_path + filenames.get(file_name).getName());
final String tempFileName = filenames.get(file_name).getName() + " is deleted";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete File");
builder.setMessage("Do you really want to delete this file?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
boolean deleted = deleteFile.delete();
if (deleted) {
Toast.makeText(getApplicationContext(), tempFileName, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do nothing.
}
});
builder.create();
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
}
}
I deleted the extra code. Thanx for helping!
PS -
I heard that in Android 4.4 + files can't be deleted like this. What should I do?
EDIT -
I have seen those answers. But I want to create a button on whose click the check/uncheck buttons would be available. How can I do that? I want the Check/Uncheck buttons to be visible only when I click delete button. Also the other answers are a bit confusing.
I would have a button with a edit or delete icon and have it change the ListView to one with checkboxes in each view. Either make a new ListView with a new Adapter or just tell adapter and set a boolean in it, and then dataSetChange the Adapter.
I fixed my problem. I use a SparseBooleanAdapter to register the delete options.Then I press delete button to delete them.

How to add a pop up/Dialog box and pass information back to the class in Android

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.

Retaining items in a List View

I'm new to android development having some problems. I created a list view that is based on the user input. User has to enter a category in a dialog box and then it's added into the list. Works like a charm. The question is how do I retain those categories once the user exits from an app and starts it again ? When the user starts the app, the list is blank. Do I have to create a preference screen or something to save what the user types ? Here is my code:
public class MainActivity extends Activity {
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_add_cat:
LayoutInflater li = LayoutInflater.from(context);
View promptAdd = li.inflate(R.layout.prompt_add, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//set prompts.xml to alertDialogBuilder
alertDialogBuilder.setView(promptAdd);
final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);
//set a dialog message
alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*
* add a cat here
*/
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
}
//return super.onOptionsItemSelected(item);
return true;
}
}// end of MainActivity
You can save it in SQLite DB, use CursorAdapter for your list view.
If the amount of data you want to save is relatively small you can use SharedPreferences to save the String data in your onClick method.
#Override
public void onClick(DialogInterface dialog, int which) {
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
// Add all string data to List<String> listItem
listItem.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
When the user leaves your activity, use the onStop() callback method to save your List<Strings> and store it through SharedPreferences.
#Override
private void onStop() {
super.onStop();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(getResources().getString(R.string.list_of_strings), new HashSet<String>(listItem));
editor.commit;
}
Using the onStart() callback, initialize your List and SharedPreferences. When the user navigates to your activity, your list will be reinitialized when it was saved via onStop().
Finally, iterate through your list, add your items to your ArrayList', create yourArrayAdapter` and set it to your list.
#Override
private onStart(){
super.onStart();
SharedPreferences mSharedPreferences;
mSharedPreferences = this.getApplicationContext().getSharedPreferences("MyPreferences", 0);
List<String> listItems = new ArrayList<String>(mSharedPreferences.getStringSet("ListOfStrings", null));
ListIterator li = listItem.listIterator(0);
while (li.hasNext()) {
newStatusList.add((String)li.next());
}
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}

Listview + Adapter - delete item and Refresh, not working - Android

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();

Categories

Resources