I want to display user chats from a Firebase List in a ListView with a custom Adapter. But somehow it does not work. I get a response when I try to look at the data in the logcat but when I pass the list to the CustomAdapter it does not display anything in my ListView. What is the issue?
My Adapter:
public class ChatAdapter extends ArrayAdapter<String> {
private Activity context;
private List<Chats> chatsList = new ArrayList<>();
public ChatAdapter(Activity Context, List<Chats> chatsList) {
super(Context, R.layout.abc_main_chat_item);
this.context = Context;
this.chatsList = chatsList;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.abc_main_chat_item, null, true);
TextView tvusername = (TextView) listViewItem.findViewById(R.id.group_name);
TextView tvuid = (TextView) listViewItem.findViewById(R.id.useruid);
TextView tvlastmessage = (TextView) listViewItem.findViewById(R.id.latestMessage);
TextView tvlastmessagetime = (TextView) listViewItem.findViewById(R.id.latestMessageTime);
ImageView ivphoto = (ImageView) listViewItem.findViewById(R.id.profileImg);
tvusername.setText(chatsList.get(position).getUsername());
tvlastmessage.setText(chatsList.get(position).getLastMessage());
tvlastmessagetime.setText(chatsList.get(position).getLastMessageTime());
tvuid.setText(chatsList.get(position).getUseruid());
Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(ivphoto);
listViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, Chat_Room.class);
i.putExtra("room_name", chatsList.get(position).getUsername());
i.putExtra("room_uid", chatsList.get(position).getUseruid());
context.startActivity(i);
}
});
listViewItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.abcd_listview_alertdia_layout);
ArrayList<String> list_of_chats = new ArrayList<>();
final ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, list_of_chats);
list_of_chats.add(0, "Chatverlauf mit "+ chatsList.get(position).getUsername()+" löschen?");
list_of_chats.add(1, "Profil von "+chatsList.get(position).getUsername()+" anschauen");
arrayAdapter.notifyDataSetChanged();
final ListView lv = (ListView) dialog.findViewById(R.id.lv);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position2, long id) {
if (position2 == 0) {
dialog.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Chatverlauf mit "+chatsList.get(position).getUsername()+" löschen?")
.setMessage("Du kannst das Löschen nicht rückgängig machen. Bist du dir sicher?")
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(chatsList.get(position).getUseruid()).setValue(null);
FirebaseDatabase.getInstance().getReference().child("chats").child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("messages").child(chatsList.get(position).getUseruid()).setValue(null);
}
}).setCancelable(true)
.show();
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
if (position2 == 1) {
Intent intent = new Intent(context, ViewContact.class);
intent.putExtra("useruid", chatsList.get(position).getUseruid());
context.startActivity(intent);
}
}
});
dialog.show();
return true;
}
});
ivphoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.abcd_profile_pic_dialog_layout);
ImageView imageView = (ImageView) dialog.findViewById(R.id.alertImage);
TextView textView = (TextView)dialog.findViewById(R.id.alertdialogtv);
ImageView message = (ImageView)dialog.findViewById(R.id.alertMessage);
ImageView profile = (ImageView)dialog.findViewById(R.id.alertProfile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ViewContact.class);
intent.putExtra("useruid", chatsList.get(position).getUseruid());
context.startActivity(intent);
dialog.dismiss();
}
});
message.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), Chat_Room.class);
intent.putExtra("room_name", chatsList.get(position).getUsername());
intent.putExtra("room_uid", chatsList.get(position).getUseruid());
context.startActivity(intent);
}
});
Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(imageView);
textView.setText(chatsList.get(position).getUsername());
dialog.setCancelable(true);
dialog.show();
}
});
return listViewItem;
}
...
}
And this is how I get the data for the List:
FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(myUiD).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<chatapp.chatapp2.Chats.Chats> chatsList = new ArrayList<chatapp.chatapp2.Chats.Chats>();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
chatapp.chatapp2.Chats.Chats chats = new chatapp.chatapp2.Chats.Chats();
chats.setUsername(snapshot.child("roomname").getValue().toString());
chats.setPhotoURL(snapshot.child("photoURL").getValue().toString());
chats.setLastMessage(snapshot.child("lastMessage").getValue().toString());
chats.setLastMessageTime(snapshot.child("lastMessageTime").getValue().toString());
chats.setUseruid(snapshot.child("userUiD").getValue().toString());
chatsList.add(chats);
Log.d("CHATS", chats.getUsername());
Log.d("CHATS", chats.getUseruid());
}
ChatAdapter chatAdapter = new ChatAdapter(getActivity(), chatsList);
chatAdapter.notifyDataSetChanged();
listView.setAdapter(chatAdapter);
listView.setVisibility(View.VISIBLE);
}
...
});
I dont really know why it does not worked, but I found the Solution:
You have to override the getCount method like this:
#Override
public int getCount() {
return chatsList == null ? 0 : chatsList.size();
}
I do not know what it does but it works :) :)
Related
I have a code in adapter listview. I want to hide the button "image2" when show listview, but it doesn't work. Where is my fault? Anyone can help me?
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Database = new SQLite(context);
db = Database.getReadableDatabase();
if (convertView == null) {
inflater = context.getLayoutInflater();
convertView = inflater.inflate(resource, null);
}
final Model_CheckStock itempos = ListViewCheckStock.get(position);
TextView txproduk = (TextView) convertView.findViewById(R.id.txproduk);
final TextView txqty = (TextView) convertView.findViewById(R.id.txqty);
final TextView txexpired = (TextView) convertView.findViewById(R.id.txexpired);
TextView txidproduk = (TextView) convertView.findViewById(R.id.txidproduk);
final Spinner spin = (Spinner) convertView.findViewById(R.id.spin);
ImageView imgexpired = (ImageView) convertView.findViewById(R.id.imgexpired);
Button image = (Button) convertView.findViewById(R.id.image);
final Button image2 = (Button) convertView.findViewById(R.id.image2);
txproduk.setText(ListViewCheckStock.get(position).gettxproduk());
txidproduk.setText("Produk " + ListViewCheckStock.get(position).getjnsprod());
txqty.setText(ListViewCheckStock.get(position).gettxqty());
txexpired.setText(ListViewCheckStock.get(position).getexpired());
// image2.setVisibility(View.INVISIBLE);
if (txidproduk.getText().toString().contains("NON")) {
Log.w("ADAPTERCHECKSTOCKLIST", "getView non: "+txidproduk.getText().toString() );
List<Model_Unit> chekstok = Database.getUnitAll();
ArrayAdapter<Model_Unit> dataAdapter = new ArrayAdapter<Model_Unit>(
context, android.R.layout.simple_spinner_item, chekstok);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(dataAdapter);
spin.setSelection(getIndex(spin, ListViewCheckStock.get(position).getunit()));
image2.setVisibility(View.INVISIBLE);
notifyDataSetChanged();
} else {
Log.w("ADAPTERCHECKSTOCKLIST", "getView sgf: "+txidproduk.getText().toString() );
List<Model_Unit> chekstok = Database.getUnit(ListViewCheckStock.get(position).getidprod());
ArrayAdapter<Model_Unit> dataAdapter = new ArrayAdapter<Model_Unit>(
context, android.R.layout.simple_spinner_item, chekstok);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(dataAdapter);
spin.setSelection(getIndex(spin, ListViewCheckStock.get(position).getunit()));
image2.setVisibility(View.INVISIBLE);
notifyDataSetChanged();
}
imgexpired.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatePickerDialog();
myCalendar = Calendar.getInstance();
dialog = new DatePickerDialog(context,
dateListener, year, month, day);
dialog.show();
image2.setVisibility(View.VISIBLE);
}
});
image2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(
context);
dialog.setMessage("Anda Yakin Ingin Menyimpan Perubahan Data Ini ?");
dialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
String saving;
saving = String.valueOf((ListViewCheckStock.get(position).getidtable()));
System.out.println("saving" + saving);
db = Database.getWritableDatabase();
Database.updateSavingCheckstok(ListViewCheckStock.get(position).getunit(), saving, ListViewCheckStock.get(position).gettxqty(), ListViewCheckStock.get(position).getexpired());
image2.setVisibility(View.GONE);
}
});
dialog.setNegativeButton("Kembali",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
});
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int arg2, long id) {
if ((txqty.getText().toString().contains(".") && !spin.getSelectedItem().toString().equals("CAR")) &&
(txqty.getText().toString().contains(".") && !spin.getSelectedItem().toString().equals("KG"))) {
CustomDialog.init.setDialog(context,
"Format angka", "Desimal tidak diperbolehkan dalam unit ini.",
"ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
txqty.setText("");
}
});
}
String prod;
ListViewCheckStock.get(position).setunit(adapterView.getSelectedItem().toString());
Log.w("TAG >>", "onItemSelected: " + ListViewCheckStock.get(position).getunit());
spin.setSelection(arg2);
image2.setVisibility(View.VISIBLE);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
private int getIndex(Spinner spinner, String myString) {
int index = -1;
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString()
.equalsIgnoreCase(myString)) {
index = i;
break;
}
}
return index;
}
}
i want to hide the save button (image2) when listview is show.but the button always show.
and then, when flagstatus is not 0 the button still show.
I want to programm a ChatApp with Firebase. Right now I am displaying the Users I chat with. But now I want them to be sorted by a Date String I am using:
For Example: 21-06-2017 17:20. It should be sorted from the latest Time to the earliest Time.
My Adapter:
public class ChatAdapter extends ArrayAdapter<String> {
private Activity context;
private List<Chats> chatsList = new ArrayList<>();
public ChatAdapter(Activity context, List<Chats> chatsList) {
super(context, R.layout.abc_main_chat_item);
this.context = context;
this.chatsList = chatsList;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.abc_main_chat_item, null, true);
TextView tvusername = (TextView) listViewItem.findViewById(R.id.group_name);
TextView tvuid = (TextView) listViewItem.findViewById(R.id.useruid);
TextView tvlastmessage = (TextView) listViewItem.findViewById(R.id.latestMessage);
TextView tvlastmessagetime = (TextView) listViewItem.findViewById(R.id.latestMessageTime);
ImageView ivphoto = (ImageView) listViewItem.findViewById(R.id.profileImg);
tvusername.setText(chatsList.get(position).getUsername());
tvlastmessage.setText(chatsList.get(position).getLastMessage());
tvlastmessagetime.setText(chatsList.get(position).getLastMessageTime());
tvuid.setText(chatsList.get(position).getUseruid());
Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(ivphoto);
listViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, Chat_Room.class);
i.putExtra("room_name", chatsList.get(position).getUsername());
i.putExtra("room_uid", chatsList.get(position).getUseruid());
context.startActivity(i);
}
});
listViewItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.abcd_listview_alertdia_layout);
ArrayList<String> list_of_chats = new ArrayList<>();
final ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, list_of_chats);
list_of_chats.add(0, "Chatverlauf mit "+ chatsList.get(position).getUsername()+" löschen?");
list_of_chats.add(1, "Profil von "+chatsList.get(position).getUsername()+" anschauen");
arrayAdapter.notifyDataSetChanged();
final ListView lv = (ListView) dialog.findViewById(R.id.lv);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position2, long id) {
if (position2 == 0) {
dialog.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Chatverlauf mit "+chatsList.get(position).getUsername()+" löschen?")
.setMessage("Du kannst das Löschen nicht rückgängig machen. Bist du dir sicher?")
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(chatsList.get(position).getUseruid()).setValue(null);
FirebaseDatabase.getInstance().getReference().child("chats").child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("messages").child(chatsList.get(position).getUseruid()).setValue(null);
}
}).setCancelable(true)
.show();
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
if (position2 == 1) {
Intent intent = new Intent(context, ViewContact.class);
intent.putExtra("useruid", chatsList.get(position).getUseruid());
context.startActivity(intent);
}
}
});
dialog.show();
return true;
}
});
ivphoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.abcd_profile_pic_dialog_layout);
ImageView imageView = (ImageView) dialog.findViewById(R.id.alertImage);
TextView textView = (TextView)dialog.findViewById(R.id.alertdialogtv);
ImageView message = (ImageView)dialog.findViewById(R.id.alertMessage);
ImageView profile = (ImageView)dialog.findViewById(R.id.alertProfile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ViewContact.class);
intent.putExtra("useruid", chatsList.get(position).getUseruid());
context.startActivity(intent);
dialog.dismiss();
}
});
message.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), Chat_Room.class);
intent.putExtra("room_name", chatsList.get(position).getUsername());
intent.putExtra("room_uid", chatsList.get(position).getUseruid());
context.startActivity(intent);
}
});
Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(imageView);
textView.setText(chatsList.get(position).getUsername());
dialog.setCancelable(true);
dialog.show();
}
});
return listViewItem;
}
This is how i got my ArrayLists:
`for(DataSnapshot snapshot : dataSnapshot.getChildren()){
username.add(snapshot.child("roomname").getValue().toString());
photoURL.add(snapshot.child("photoURL").getValue().toString());
lastmessage.add(snapshot.child("lastMessage").getValue().toString());
lastmessagetime.add(snapshot.child("lastMessageTime").getValue().toString());
useruid.add(snapshot.child("userUiD").getValue().toString());
}
ChatAdapter chatAdapter = new ChatAdapter(getActivity(), username, useruid, photoURL, lastmessage, lastmessagetime);
listView.setAdapter(chatAdapter);`
But how can I pass it as a List ??
How can I add them to the list?
Is it even possible to sort it?
I hope you Guys can help me :)
Thanks.
This is of course possible.
But first, your data structure looks weird and unpractical.
Your messages are passed in single arrays which makes it quite complicated:
ArrayList<String> username, ArrayList<String> useruid, ArrayList<String> photoURL, ArrayList<String> lastmessage, ArrayList<String> lastmessagetime
Better would be to have a list of Messageobjects, where a message object contains the single items, something like this:
public class Message {
String username;
String useruid;
String photoURL;
String message;
Date timestamp;
//...getter and setter
}
Even better would be to have a Message object just contain a userId, messageText and timeStamp. that's all you would need.
Then you could pass a List<Message> messages into your adapter.
To sort the message list you can implement the Comparable class where you can then sort the objects in a way you like.
public class Message implements Comparable<Message>{
String username;
String useruid;
String photoURL;
String message;
Date timestamp;
#Override
public int compareTo(#NonNull Message o) {
return this.timestamp.compareTo(o.timestamp)
}
}
If you have added Comparable to your Messageclass, you can use
Collections.sort(messages); to sort the list.
Just have a look at the java comparable, there are various examples. Also check out this stackoverflow answer.
edit: to answer your additional question:
in your case, when you are getting your elements you would do something like:
List<Message> messages = new ArrayList<Message>();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Message message = new Message();
message.setName(snapshot.child("roomname").getValue().toString());
…
//set all your properties and then add that object to the messages list
messages.add(message);
}
Collections.sort(messages); // sort the message list
ChatAdapter chatAdapter = new ChatAdapter(getActivity(), messages);
listView.setAdapter(chatAdapter);
When I reopen my app file is present and have length zero.
How to delete it permanently?
I am using the list view to display all song in external storage using Media Store and added delete option to it.
After deleting the file when I reopen my app song file is again in list view but with file length zero.
Please see onClickListener for delete:
public class TracksFragment extends Fragment {
songDetailloader loader = new songDetailloader();
ArrayList<Songs> give = new ArrayList<>();
public int pos = -1;
MediaPlayer mp ;
MusicService musicService;
boolean mBound;
Context context;
public TracksFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v =inflater.inflate(R.layout.listviewofsongs,container,false);
final ListView listView = (ListView) v.findViewById(R.id.listView);
loader.set(getContext());
give = loader.allsongs();
final ListViewAdapter listViewAdapter = new ListViewAdapter(getContext(),give);
listView.setAdapter(listViewAdapter);
listView.setSelector(R.drawable.selector);
new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getActivity(),MusicService.class);
getActivity().bindService(i, serviceConnection, Context.BIND_AUTO_CREATE);
}
}).start();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.d("Uri of ",""+give.get(position).getSonguri());
musicService.setplaylist(give,position);
musicService.setMediaPlayer();
view.setSelected(true);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View v =LayoutInflater.from(getContext()).inflate(R.layout.select_dialog_layout,null);
builder.setView(v);
builder.setTitle(give.get(position).gettitle()+"\n "+give.get(position).getalbum());
builder.create();
final AlertDialog d=builder.show();
//seting click listner.....
TextView play = (TextView) v.findViewById(R.id.dialogplay);
TextView playnext = (TextView) v.findViewById(R.id.dialogplaynext);
TextView queue = (TextView) v.findViewById(R.id.dialogqueue);
TextView fav = (TextView) v.findViewById(R.id.dialogaddtofav);
TextView album = (TextView) v.findViewById(R.id.dialogalbum);
TextView artist = (TextView) v.findViewById(R.id.dialogartist);
TextView playlist = (TextView) v.findViewById(R.id.dialogaddtoplaylsit);
TextView share = (TextView) v.findViewById(R.id.dialogshare);
TextView delete = (TextView) v.findViewById(R.id.dialogdelete);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File f= new File(give.get(position).getSonguri().getLastPathSegment());
Log.d("LENGTH IS",""+f.length());
musicService.setplaylist(give,position);
musicService.setMediaPlayer();
d.dismiss();
}
});
playnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
queue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
DataBaseClass db = new DataBaseClass(getContext());
int i=db.insetintoliked(give.get(position));
if(i==1)
{
Toast.makeText(getContext(),"Added to Favorites",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getContext(),"Already in Favorites",Toast.LENGTH_SHORT).show();
}
});
album.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent i = new Intent( getActivity() , AlbumDetail.class);
Bundle b= new Bundle();
b.putCharSequence("album",give.get(position).getalbum());
i.putExtras(b);
startActivity(i);
}
});
artist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setMessage("Audio '"+give.get(position).gettitle()+"' will be deleted permanently !");
b.setTitle("Delete ?");
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
b.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
loader.deleteSong(getContext(),give.get(position).getPosition());
File f= new File(give.get(position).getSonguri().getPath());
boolean b = f.delete();
Log.d("Is file exist",f.exists()+"");
Log.d("File Length",""+f.length());
Log.d("Return value",""+b);
give.remove(position); // give is Arraylist of Songs(datatype);
listViewAdapter.notifyDataSetChanged();
if(b)
{
Toast.makeText(getContext(),"Deleted",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getContext(),"Fail to Delete",Toast.LENGTH_SHORT).show();
}
}
});
b.create().show();
d.dismiss();
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");`enter code here`
share.putExtra(Intent.EXTRA_STREAM, give.get(position).getSonguri());
startActivity(Intent.createChooser(share, "Share Sound File"));
}
});
return true;
}
});
container.addView(v);
return v;
}
}
LogCat:
01-14 05:19:54.189 18010-18010/com.developmentforfun.mdnafiskhan.mp3player D/Is file exist: false
01-14 05:19:54.190 18010-18010/com.developmentforfun.mdnafiskhan.mp3player D/File Lenth:0
01-14 05:19:54.190 18010-18010/com.developmentforfun.mdnafiskhan.mp3player D/Return value: false
I am kind of new to android. For the life of me I can not figure out how to delete an item from a ListView from within my Adapter. Each row in the list view has an edit and delete option. I populate a dialog asking user to confirm deletion, after confirming, i'd like the ListView to remove that Item. Any help would be greatly appreciated.
Contacts.java
public class Contacts extends ActionBarActivity {
private Button mButton;
private ContactsAdapter mAdapter;
private ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emergency_contacts);
mAdapter = new ContactsAdapter(Contacts.this,new ArrayList<SingleContactInfo>());
mListView = (ListView) findViewById(R.id.listView);
mListView.setAdapter(mAdapter);
mButton = (Button) findViewById(R.id.addContactButton);
updateData();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goToAddContacts = new Intent(getApplicationContext(), AddContactInfo.class);
startActivity(goToAddContacts);
}
});
}
public void updateData(){
ParseQuery<SingleContactInfo> query = ParseQuery.getQuery(SingleContactInfo.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<SingleContactInfo>() {
#Override
public void done(List<SingleContactInfo> contacts, ParseException error) {
if(contacts != null){
mAdapter.clear();
for (int i = 0; i < contacts.size(); i++) {
mAdapter.add(contacts.get(i));
mAdapter.notifyDataSetChanged();
}
}
}
});
}
ContactsAdapter.java
public class ContactsAdapter extends ArrayAdapter<SingleContactInfo> {
private final Context mContext;
private List<SingleContactInfo> mContacts;
public TextView mContactName;
public TextView mNumber;
public TextView mEdit;
public TextView mDelete;
public ContactsAdapter(Context context, List<SingleContactInfo> objects) {
super(context, R.layout.add_emergency_contacts_two, objects);
this.mContext = context;
this.mContacts = objects;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null) {
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.add_emergency_contacts_two, null);
}
final SingleContactInfo contact = mContacts.get(position);
mContactName = (TextView) convertView.findViewById(R.id.emergency_contact_name);
mNumber = (TextView) convertView.findViewById(R.id.emergency_contact_number);
mEdit = (TextView) convertView.findViewById(R.id.edit_textView);
mDelete = (TextView) convertView.findViewById(R.id.delete_textView);
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteContactDialog(contact, mContext, position);
Toast.makeText(getContext(), "Deleted", Toast.LENGTH_LONG).show();
}
});
mContactName.setText(contact.getName());
mNumber.setText(contact.getNumber());
return convertView;
}
//TODO Look below here
public void deleteContactDialog(final SingleContactInfo contact, Context context, final int position) {
AlertDialog.Builder confirmDelete = new AlertDialog.Builder(context);
confirmDelete.setMessage("Are You Sure You Want to Delete Contact Person")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
} catch (ParseException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = confirmDelete.create();
dialog.show();
}
}
You just need to remove the item at the desired position from the ArrayList of contacts, and then notify the dataset:
public void onClick(DialogInterface dialog, int which) {
try {
mContacts.remove(position);
notifyDataSetChanged();
}
catch (ParseException e) {
e.printStackTrace();
}
}
Also, it's enough to call mAdapter.notifyDataSetChanged(); from outside your for cycle.
public void deleteContactDialog(final SingleContactInfo contact, Context context, final int position) {
AlertDialog.Builder confirmDelete = new AlertDialog.Builder(context);
confirmDelete.setMessage("Are You Sure You Want to Delete Contact Person")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Just add these two lines and you should be good.
mContacts.remove(position);
ContactsAdapter.this.notifyDataSetChanged();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = confirmDelete.create();
dialog.show();
}
sir, how do i refresh my listview if i pressed the back button in android emulator? i've clicked an item on activityA then goes to an edit form in activityB. after saving updates, if i pressed the back button, it should refresh the list.
here is my activityA
public class CustomListView extends Activity {
final Context context = this;
public static String name;
public static String number;
int REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
final ListView lv = (ListView) findViewById(R.id.srListView);
lv.setAdapter(new MyCustomBaseAdapter(this, searchResults));
info.close();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// TODO Auto-generated method stub
Object o = lv.getItemAtPosition(position);
final Contact fullObject = (Contact)o;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage("Select action")
.setCancelable(false)
.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(getApplicationContext(), "Edit ", Toast.LENGTH_LONG).show();
name = fullObject.getName();
number = fullObject.getPhoneNumber();
Intent intent = new Intent();
intent.setClass(CustomListView.this, EditDetails.class);
startActivityForResult(intent, REQUEST_CODE);
}
})
.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(getApplicationContext(), "Delete ", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel", 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();
}
});
}
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
info.close();
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_CODE) {
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
info.close();
}
}
//edit or delete list when clicked
public void deleteEditOption()
{
}//end deleteEditOption()
}
and here is my activityB
public class EditDetails extends Activity{
public String nameChanged;
public String numChanged;
public String name;
public String num;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editdetails);
final EditText sqlName = (EditText)findViewById(R.id.editName);
final EditText sqlNumber = (EditText)findViewById(R.id.editNumber);
name = CustomListView.name;
num = CustomListView.number;
Button bUpdate = (Button)findViewById(R.id.editUpdate);
Button bView = (Button)findViewById(R.id.editView);
sqlName.setText(name);
sqlNumber.setText(num);
bUpdate.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
nameChanged = sqlName.getText().toString();
numChanged = sqlNumber.getText().toString();
GroupDb info = new GroupDb(EditDetails.this);
info.open();
long rowid = info.getRowId(name, num);
info.updateNameNumber(rowid+1, nameChanged, numChanged);
Toast.makeText(getApplicationContext(), rowid+" "+nameChanged+" "+numChanged, Toast.LENGTH_LONG).show();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
mcba.updateResults(searchResults);
Toast.makeText(getApplicationContext(), "Update Successful!", Toast.LENGTH_LONG).show();
info.close();
}
});
bView.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(EditDetails.this, CustomListView.class);
startActivityForResult(intent, 0);
}
});
}
}
if i clicked this bView button in my activityB, it updates the listview. but pressing the back button just shows my previous unupdated listview. thanks for help in advance
edit
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<Contact> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<Contact> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public void updateResults(ArrayList<Contact> results) {
searchArrayList = results;
//Triggers the list update
notifyDataSetChanged();
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
holder.status = (TextView) convertView.findViewById(R.id.status);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtPhone.setText(searchArrayList.get(position).getPhoneNumber());
holder.status.setText(searchArrayList.get(position).getStatus());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtPhone;
TextView status;
}
}
Rewrite
While I recommend customizing a CursorAdapter to work with your database. Let's change a couple points with your current code:
First create a field variable for mbca, (just like name and number).
MyCustomBaseAdapter mcba;
Second update how you initialize mbca in onCreate():
mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
//mcba.updateResults(searchResults); this line isn't necessary here
Third make a small change to onResume():
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
GroupDb info = new GroupDb(this);
info.open();
mcba.updateResults(info.getView());
info.close();
}
This works because updateResults() calls notifyDataSetChanged() and this updates the ListView automatically.