I have a list view where my SQL query will be displayed.
Now I have added an OnItemClickListener to delete entrys on click:
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0,View arg1,int arg2, long arg3){
ListView lv = (ListView) findViewById(R.id.listView1);
final String Name = lv.getAdapter().getItem(arg2).toString();
final String ID = String.valueOf(arg3);
CharSequence dbeintrag = getString(R.string.dbeintrag);
CharSequence yes = getString(R.string.yes);
CharSequence no = getString(R.string.no);
Builder alertDialog = new AlertDialog.Builder(EP.this);
alertDialog.setTitle(Name);
alertDialog.setMessage(dbeintrag);
alertDialog.setCancelable(true);
alertDialog.setPositiveButton(yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteentry(Name,ID);
fillSQLData(); // refresh
} });
alertDialog.setNegativeButton(no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
} });
alertDialog.show();
}
});
}
public void deleteentry(String Name,long ID) // Lösche Eintrag
{
DataBaseHelper myDbHelper = new DataBaseHelper(null);
myDbHelper = new DataBaseHelper(this);
ID = ID+1; // Anpassen zur DB
SQLiteDatabase database = myDbHelper.getWritableDatabase();
database.execSQL("DELETE FROM Heute WHERE Name='"+Name+"' and _id='"+ID+"'");
mPLAdapter.notifyDataSetChanged();
}
Now I have the problem that my ID in the Database is not the ID I get from the onItemClick function.
For example, I'll add 3 entries, delete all, add 3 new ones. For the function the first entry is 0, in the SQL database its 4...
What is the best solution to fix this?
Than you very much!
Override this method to your adapter class so you can retrieve the id in onItemClick.
#Override
public long getItemId(int position) {
return yourList.get(position);
}
In onItemClick
final String ID = String.valueOf(lv.getAdapter().getItemId(arg2));
//long id = ((YourAdapter)parent.getAdapter()).getItemId(arg2);
Please see Android OnItemClickListener long id parameter is not giving field id and view.getId() returning wrong id in OnItemClickListener
Edit: so here's Oli's changes:
final long id = ((EPListAdapter)arg0.getAdapter()).getItemId(arg2);
"Its important to use .notifyDataSetChanged(); on the Adapter. Else it wont work."
Related
I'm trying to save text from the selected item of a ListView in OnItemClick.
I've tried so many different methods to no avail, I think I'm missing something really stupidly obvious here...
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
The data is being displayed fine, I just can't seem to reference it.
The line causing the exception:
String choice = SnakesListView.getItemAtPosition(position).toString();
Full code for this activity
public class SnakeList extends Activity {
ListView SnakesListView;
Cursor cursor;
Button NewSnakeBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_list);
SnakesListView = (ListView) findViewById(R.id.SnakesListView);
NewSnakeBtn = (Button) findViewById(R.id.NewSnake);
SQLiteDatabase db = openOrCreateDatabase("snakeDB", Context.MODE_PRIVATE, null); // ACCESSES DB
cursor = db.rawQuery("SELECT name FROM snakes", null); // SETS cursor TO RESULTS OF QUERY
List<String> SnakeNamesList = new ArrayList<String>();
ArrayAdapter SnakeNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SnakeNamesList);
SnakeNamesList.clear(); // REMOVES ANY NAMES CURRENTLY IN NAME ARRAY TO AVOID DUPLICATES
SnakesListView.setAdapter(SnakeNamesAdapter);
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // MOVES CURSOR TO FIRST POSITION
do SnakeNamesList.add(cursor.getString(0)); // RETURNS STRING FROM FIRST COLUMN (NAME)
while (cursor.moveToNext());
}
NewSnakeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(SnakeList.this, NewSnake.class));
}
});
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
}
No use of referencing the ListView; you can get the value from adapter itself.
Change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesAdapter.getItem(position).toString();
declare the string arraylist(SnakeNamesList) as global variable and
change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesList.get(position);
Hi Every one I'm facing with a problem in android what i need is I'm having a list view in my Activity which is dynamically set with the values from database, If i select a particular item in the list view any action should not be occur and it should be get highlighted.Now I'm having a button(Submit) in the same Activity when ever i click the button the item in the list view value should be displayed in the second activity in a text view.Please help me in solving this
I have created the list view using array adapter
What i need is user should select a name from the list view and click on submit button so that his name should be displayed in the next activity.
Thanks in advance
public class Unitselctn extends Activity{
Button b1;
LinearLayout ll1;
ListView lv;
Cursor c;
SQLiteDatabase db;
Spinner sp1;
protected void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.selection);
sp1=(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> unt= ArrayAdapter.createFromResource(this, R.array.Units,android.R.layout.simple_spinner_item);
unt.setDropDownViewResource(android.R.layout.simple_spinner_item);
sp1.setAdapter(unt);
//sp1.setOnItemSelectedListener(this);
b1=(Button)findViewById(R.id.button1);
lv=(ListView)findViewById(R.id.listView1);
lv.setBackgroundColor(Color.WHITE);
//create database if not already exist
db= openOrCreateDatabase("Hangman", MODE_PRIVATE, null);
//create new table if not already exist
db.execSQL("create table if not exists user_reg(name varchar not null, phnum number not null,email varchar not null)");
displayData();
}
public void onNew(View v){
insertData();
}
public void insertData(){
//Toast.makeText(this, "Button1",5000).show();
AlertDialog.Builder adb=new AlertDialog.Builder(this);
ll1=new LinearLayout(this);
ll1.setOrientation(1);
final EditText name= new EditText(this);
final EditText phno= new EditText(this);
final EditText email= new EditText(this);
ll1.addView(name);
ll1.addView(phno);
ll1.addView(email);
name.setHint("UserName");
phno.setHint("Mobile No");
email.setHint("Email-id");
adb.setTitle("Registration");
adb.setView(ll1);
adb.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String nme=name.getText().toString();
String phn=phno.getText().toString();
String mail=email.getText().toString();
name.setText("");
phno.setText("");
email.setText("");
db.execSQL("insert into user_reg values('"+nme+"','"+phn+"','"+mail+"')");
Toast.makeText(getApplicationContext(), "Registered Successfully",5000).show();
displayData();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
adb.show();
}
public void displayData(){
List<String> array = new ArrayList<String>();
db=this.openOrCreateDatabase("Hangman",MODE_PRIVATE, null);
c=db.rawQuery("select name from user_reg", null);
if(c.moveToFirst()){
do{
String usr=c.getString(c.getColumnIndex("name"));
array.add(usr);
}while(c.moveToNext());
}
ArrayAdapter<String> adptr= new ArrayAdapter<String>(this,R.layout.row,R.id.member_name,array);
lv.setAdapter(adptr);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), adptr[pos], 5000).show();
}
});
adptr.notifyDataSetChanged();
}
}
1.have on arraylist add the item that get clicked to it
2.pass condition
if(yourArrayList.contains(item)){
return true;
}else
{
return false;
}
3.Set allItemareClickble to false
Sorry Now I can't post code, Just an Idea.
Create a variable SelectedItem;
Inside lv.setOnItemClickListener(new OnItemClickListener() { } assign the value of the selected list item to the variable(SelectedItem).
Inside OnClickListener method of the button Send this variable(SelectedItem) to the next activity using Intent.
I create a listview in Android. My listview data is from sqlite database. When user click the item on the list. Alert dialog to delete confirmation will appear.
this is my code to delete from list:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(todaycode.this);
alertDialog.setTitle("Delete from list");
alertDialog.setMessage("Are you sure to delete?");
final int del_position=position;
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,int which) {
//delete from database
mDb.deleteContact(list_food.get(+ del_position).getId());
//reload
final ArrayList<food_object> list_food = mDb.getAllfood();
final ListView list;
final String[] food_name = new String[list_food.size()];
for(int i=0;i<list_food.size();i++){
food_name[i]=list_food.get(i).getName();}
Integer[] imageId = {
R.drawable.image1,};
final customlist adapter = new customlist(todaycode.this, food_name, imageId);
list=(ListView)findViewById(R.id.listToday);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
and this is my code to delete from my database in DBAdapter:
public boolean deleteContact(int id)
{
return db.delete(TABLE_NAME, COL_ID + "=" + id, null) > 0;
}
this code is work. but sometimes user can't delete an item from the list until they reload this activity (move to other activity and back). The Alert dialog is appear, but after user click "Yes" there's nothing happen.
this only happen sometime. And only occure in one item on the list, so if user choose other item on the list to delete, it's still working. does anybody knows why this is happen?
EDITED
after many try, I conclude that the error (the item can't deleted) always started after user delete the second item (user deleting consecutively), and I'm still no idea why this is happen
this is my DBAdapter code, I simplified it See the Code
this is my customlist code See the Code
The problem is that you probably use autoincrement id in your table. When you get the id from the setOnItemClick it's actually the index of the item and not the id. So when you delete one at index 3 that id will be deleted and next time you want to delete at same index there won't be an item whit that id.
put this listener it will work then bro..!
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,int which) {
//delete from database
mDb.deleteContact(list_food.get(+ del_position).getId());
//reload
final ArrayList<food_object> list_food = mDb.getAllfood();
final ListView list;
final String[] food_name = new String[list_food.size()];
for(int i=0;i<list_food.size();i++){
food_name[i]=list_food.get(i).getName();}
Integer[] imageId = {
R.drawable.image1,};
final customlist adapter = new customlist(todaycode.this, food_name, imageId);
list=(ListView)findViewById(R.id.listToday);
list.setAdapter(null);
list.setAdapter(adapter);
}
});
I am building an application where I am using a ListView. Currently when the user clicks a row of the ListView, the following code executes. This code basically deletes some data concerned with the selected row. The code is a snippet from MainActivity.class.
//understanding this code is not crucial. list is the ListView, adapter is an
//ArrayAdapter object and displayDataMap is a Hashmap object.
list.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long id) {
String key = adapter.getItem(position); //position of ListView row
String data = displayDataMap.get(key);
displayDataMap.remove(key);
//"aqlpzaml" is used as a regex.
String addressee = data.split("aqlpzaml")[1];
long time = Long.valueOf(data.split("aqlpzaml")[0]);
int finalID = Integer.valueOf(data.split("aqlpzaml")[3]);
String dateTime = sdf.format(time);
adapter.remove(addressee + " " + dateTime);
adapter.notifyDataSetChanged();
}
Now I want that before deleting this data, the user is prompted with a Dialog, where he is asked if he is sure to make the changes.
I know how to create a Dialog and display it. But I don't know how to trigger change in the values of adapter and displayDataMap based on the Dialog input. I think if I'll use another class to create a Dialog object (using DialogFragment), then I won't be able to access the private variables of MainActivity class in the setPositiveButton() of that dialog.
Any suggestions ?
Thanks.
Just insert your Dialog creation in onItemLongClick and make the Adapter "adapter", "addressee" and "dateTime" final so you can access it in the setPositiveButton() method.
Cause i don't know how your Adapter is created it should look like this and in the same function as list.setOnItemLongClickListener or a class variable:
final ArrayAdapter<String> adapter = ...
also your datamap:
final Hashmap<String, ...> displayDataMap = ...
And your function should look like this:
list.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long id)
{
final String key = adapter.getItem(position); //position of ListView row
String data = displayDataMap.get(key);
//"aqlpzaml" is used as a regex.
final String addressee = data.split("aqlpzaml")[1];
long time = Long.valueOf(data.split("aqlpzaml")[0]);
int finalID = Integer.valueOf(data.split("aqlpzaml")[3]);
final String dateTime = sdf.format(time);
Builder dialog = new Builder(view.getContext());
dialog
.setMessage("Want to delete?")
.setPositiveButton("delete",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
displayDataMap.remove(key);
adapter.remove(addressee + " " + dateTime);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
dialog.create().show();
}
}
I am building an application in which I'm populating data from the database into the listview of my activity. Now, on longItemClick Listener I want to delete that value from the database and update my listview in the app.
Here my code for longClickListener on the listview:
private ListView showing_history;
private ListAdapter mHistoryListAdapter;
private ArrayList<SearchHistoryDetails> searchArrayList;
private ArrayList<SearchHistoryDetails> HistoryObjArrayList;
mHistoryListAdapter = new ArrayAdapter<String>(this,
R.layout.mylistlayout, populateList());
showing_history.setAdapter(mHistoryListAdapter);
HistoryObjArrayList = new ArrayList<SearchHistoryDetails>();
/**
* Long tap on listview to delete the selected item from the history
* list.
* */
showing_history
.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
final AlertDialog.Builder b = new AlertDialog.Builder(
MainActivity.this);
b.setIcon(android.R.drawable.ic_dialog_alert);
b.setMessage("Delete this from history?");
b.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Toast.makeText(getApplicationContext(),
"Yes", Toast.LENGTH_LONG)
.show();
}
});
b.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.cancel();
}
});
b.show();
return true;
}
});
By this code I'm inserting data into the database:
/**
* Inserting the string when user searches for anything into the database.
* */
public void insertHistory(SearchHistoryDetails paraHistoryDetailsPojoObj) {
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(
this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj
.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_HISTORY_STRING,
paraHistoryDetailsPojoObj.getHistoryName());
#SuppressWarnings("unused")
long affectedColumnId = sqliteDatabase.insert(
AndroidOpenDbHelper.TABLE_NAME_HISTORY, null, contentValues);
sqliteDatabase.close();
}
Here is the code from which I'm retrieving data from the database and repopulating it into the list view:
public List<String> populateList() {
List<String> HistoryNamesList = new ArrayList<String>();
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase
.query(AndroidOpenDbHelper.TABLE_NAME_HISTORY,
new String[] { AndroidOpenDbHelper.COLUMN_NAME_HISTORY_STRING },
null, null, null, null, AndroidOpenDbHelper.ID
+ " DESC");
startManagingCursor(cursor);
while (cursor.moveToNext()) {
String ugName = cursor
.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_HISTORY_STRING));
SearchHistoryDetails histPojoClass = new SearchHistoryDetails();
histPojoClass.setHistoryName(ugName);
searchArrayList.add(histPojoClass);
HistoryNamesList.add(ugName);
}
sqliteDatabase.close();
int history_db = cursor.getCount();
if (history_db == 0) {
history_layout.setVisibility(LinearLayout.GONE);
} else {
history_layout.setVisibility(LinearLayout.VISIBLE);
}
return HistoryNamesList;
}
Retrieving and inserting data all things are perfectly, but deleting of a particular row is not working for me. Right now I have done some action using toast and it is working, what should I do so that, the database data updates after deletion of the row from the listview. Please give me any idea to overcome this problem.
Try this..,.
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
DatabaseHandler db=new DatabaseHandler(getApplicationContext());
db.delete(arg3+"");
list.remove(position);
YourActivity.this.adapter.notifyDataSetChanged();
}
});
and in DatabaseHandler class
public void delete(String id)
{
SQLiteDatabase db = this.getReadableDatabase();
db.delete(TABLE_NAME, KEY_ID + "=?", new String[]{id});
db.close();
}
most proper solution is to use Loaders.. especially CursorLoader along with Content Provider.
If Content Provider is an overkill for what you are doing try CursorLoader from commonsware. The update after deletion happens automatically and not in the ui thread which is good.
https://github.com/commonsguy/cwac-loaderex.. its pretty easy once you get your head around this.
However if you still want to delete the row as per your code. Just delete it in your longpress listener. But after that refresh the adapter.
How to refresh Android listview?
To update list.. Firstly call the method where you specified the delete query from builder positive button.
After that delete the item from HistoryNamesList array list
Now the data removed from both database and arraylist but listview still show previous data so you have to notify listview adapter as show below
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
Solved!
Changes made on onCLick():
public void onClick(DialogInterface dialog,
int whichButton) {
HistoryNamesList.remove(pos);
((BaseAdapter) mHistoryListAdapter)
.notifyDataSetChanged();
}