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();
}
}
Related
I used custom adapter for viewing listview. I tried to define my variables in adapter class but it didnt work. I find a temporary solution using invisible textview for this but i need to solve this problem. How can I overcome this?
Edit 1>
I have a column named date and this column contains datas like 20180723182036 and i grab this data to a list. I want to place this to listview as a variable and i will use this variable later.
My temporary solution is:
I have a code like that in database:
public ArrayList<SimpleNoteItem> getAllData() {
openDatabase();
ArrayList<SimpleNoteItem> newList = new ArrayList<>();
String[] columns = {KEY_ROWTITLE, KEY_ROWCONTENT, KEY_ROWDATE, KEY_ROWSTRDATE};
Cursor cs = db.query(DB_TABLE_NORMAL, columns, null, null, null, null, null);
while(cs.moveToNext()){
SimpleNoteItem allData = new SimpleNoteItem(cs.getString(0), cs.getString(1), cs.getLong(2), cs.getString(3));
newList.add(allData);
}
Collections.reverse(newList);
Log.d(LOGDB, "GETALLDATA STRUCTURE WORKS WELL!");
return newList;
}
Listview longclick constructor is this:
simpleNotesDisplay.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) {
Log.d(TAG, "LONG CLICKED " + position + " ITEM!");
//THIS AREA WILL BE EDITED FOR MORE ANDROID VERSION SUPPORT
AlertDialog.Builder builder;
final TextView getInvisibleDate = (TextView) view.findViewById(R.id.tv_date_invisible);
builder = new AlertDialog.Builder(NotesActivity.this, android.R.style.Theme_Material_Dialog_Alert);
builder.setTitle("Delete?")
.setMessage("Do you want to send this note to hell?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.deleteSimpleNote(getInvisibleDate.getText().toString());
Log.d(TAG, "DELETING SUCCESSFUL ON ID = " + id + "!!!");
NotesActivity.this.recreate();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//empty
}
})
.show();
return true;
}
});
}
And at least my invisible date:
<TextView
android:id="#+id/tv_date_invisible"
android:layout_width="0dp"
android:layout_height="0dp"
android:text="TextView"
android:visibility="invisible"
tools:layout_editor_absoluteX="351dp"
tools:layout_editor_absoluteY="65dp" />
i hope it can help!
you should better to explain more about what you want but:
1)if you want to show some data in listview you most have a list of objects that each one has its data.
2)if you want to show different data in each row of listview then you most fill different data in each object of your list
3) if you want to show different view of each listviews row you most at first define different xml layouts and in your adapter where you define infelater you can use if else statment to decide which layout shows to witch row. below links will help you
Android ListView with different layouts for each row
https://www.javacodegeeks.com/2014/08/android-listview-with-multiple-row-layout.html
I found a different solution for that>>
I grab all data from database with this code:
public ArrayList<SimpleNoteItem> getAllData() {
openDatabase();
ArrayList<SimpleNoteItem> newList = new ArrayList<>();
String[] columns = {KEY_ROWTITLE, KEY_ROWCONTENT, KEY_ROWDATE, KEY_ROWSTRDATE};
Cursor cs = db.query(DB_TABLE_NORMAL, columns, null, null, null, null, null);
while(cs.moveToNext()){
SimpleNoteItem allData = new SimpleNoteItem(cs.getString(0), cs.getString(1), cs.getLong(2), cs.getString(3));
newList.add(allData);
}
Collections.reverse(newList);
Log.d(LOGDB, "GETALLDATA STRUCTURE WORKS WELL!");
return newList;
}
And in another activity i grab this list with this and then initialized it:
private ArrayList<SimpleNoteItem> getList = new ArrayList<>();
getList = db.getAllData();
initialize should be in onCreate method.
And then i used that data:
simpleNotesDisplay.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, final long id) {
Log.d(TAG, "LONG CLICKED " + position + " ITEM!");
//THIS AREA WILL BE EDITED FOR MORE ANDROID VERSION SUPPORT
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(NotesActivity.this, android.R.style.Theme_Material_Dialog_Alert);
builder.setTitle("Delete?")
.setMessage("Do you want to send this note to hell?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.deleteSimpleNote(String.valueOf(getList.get(position).getSimpleNoteDate()));
Log.d(TAG, "DELETING SUCCESSFUL ON ID = " + id + "!!!");
NotesActivity.this.recreate();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//empty
}
})
.show();
return true;
}
});
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "Customer" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
AlertDialog.Builder builder = new AlertDialog.Builder(UserPage.this);
builder.setTitle(rocketName);
builder.setMessage("Are you sure to accept this order ? " + listView.getItemAtPosition(position) + "SMS will be sent to the customer.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Assign value to variable here.
})
How do I get the details of a particular position and extract one of the values out and assign it to a variable when the listview is clicked ?
Sample text in the logcat. One of the items in the listview:
26-John Smith
Address: 41 Texas 55
Time Frame: 5:00pm - 6:00pm
Order ID: 5787
Submitted at: 2015-03-15 11:18:23
I have tried the following method in public void onItemClick:
TextView tv = (TextView)findViewById(android.R.id.text1);
String str = String.valueOf(tv.getText());
String orderID = str.split("Address: ")[1].split("Time Frame: ")[0];
The reason it's not working is because it always display the text of the first position even though other position is clicked.
I want to extract the Address of that particular position in the listview when it is clicked and assign it to a String variable.
Check if this works:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
TextView tv = ((TextView) view);
String str = String.valueOf(tv.getText());
String orderID = str.split("Address: ")[1].split("Time Frame: ")[0];
}
});
i have a Listview which displays list of clients, i have added an onClickListner to Listview so that i can get the detailed information of clicked client.
ListView l = (ListView) findViewById(R.id.jl);
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ClientListView j = JList.get(position);
String mess = "you clicked position " + position + " With Name " + j.GetClientName();
Toast.makeText(Home.this,mess,Toast.LENGTH_LONG).show();
}
}
);
}
i want to display information but not in toast, i will prefer some activity,fragment or some popup king of thing.
can anybody help?
Use ths code:
l.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ClientListView j = JList.get(position);
String mess = "you clicked position " + position + " With Name " + j.GetClientName();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityName.this);//Your activity name
// set title
alertDialogBuilder.setTitle("Hello!");
// set dialog message
alertDialogBuilder.setMessage(mess)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
Hope this will work..
If you want to pass Client Name which you are displaying in list, you can get id from adapter and use it.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String clientName= (String) ((TextView) view
.findViewById(R.id.client_name)).getText();
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("client", clientName);
startActivity(intent);
}
}
}
ListView l = (ListView) findViewById(R.id.jl);
l.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ClientListView j = JList.get(position);
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Keyname", j);
startActivity(intent);
}
}
);
}
You can get the intent value in another activity.
If I have understood, you want to send some information to another activity to display this information.
You can have a look to the "Intent" in Android. It's used to start a component like an activity and can carry information to this new activity to start.
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra("CUSTOMER_INFO", customer.getName());
startActivity(i);
Note: If you want to pass a custom object between activities, like for instance a List of custom object :
List<'CustomObject'>
Your custom object class have to implement Parcelable.
I have a ListView, with three TextViews in each row, that is populated from a Database. The first TextView contains the _id. When I click on an item, an AlertDialog pops up asking if I want to delete the item. How do I extract the information from a specific TextView, in order to update the Database accordingly?
Here is the code snippet I have so far:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Delete this reminder?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//I need the _id to remove the selected item.
db.deleteContact();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
Thanks!
Easiest would be if you got the information from the database that is driving the adapter. You already have the position of the clicked item and the data from your database.
Another possibility is in the onClick method to do
TextView tv = (TextView) view.findViewById(R.id.yourFirstTextView);
String id = tv.getText().toString();
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."