Sort a Custom Listview Adapter by Date - android

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

Related

CustomAdapter does not show any items in Listview

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 :) :)

How can I convert ListView to GridView?

I have created an applicaton that shows a listview of some pictures from the internet in ListView. I want to show it in a GridView.I have tried using base adapter in place of list adapter! But that doesn't work as it cant take arg (the arg is in the code)
Can anyone help me to show this images in gridview?
Here is my code.
MainPage.java
public class MainPage extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
setContentView(R. layout. contacts_list);
final List<Model> list = new ArrayList<Model>();
/** This block is for getting the <span id="IL_AD9" class="IL_AD">image url</span> to <span id="IL_AD2" class="IL_AD">download from</span> the server **/
final GetDataFromDB getvalues = new GetDataFromDB();
final ProgressDialog dialog = ProgressDialog.show(MainPage.this,
"", "Gettting values from DB", true);
final CountDownLatch latch = new CountDownLatch(1);
new Thread (new Runnable() {
public void run() {
String response = getvalues.getImageURLAndDesciptionFromDB();
System.out.println("Response : " + response);
dismissDialog(dialog);
if (!response.equalsIgnoreCase("")) {
if (!response.equalsIgnoreCase("error")) {
dismissDialog(dialog);
// Got the response, now split it to get the image Urls and description
String all[] = response.split("##");
for(int k = 0; k < all.length; k++){
String urls_and_desc[] = all[k].split(","); // urls_and_desc[0] contains image url and [1] -> description.
list.add(get(urls_and_desc[1],urls_and_desc[0]));
}
}
} else {
dismissDialog(dialog);
}
latch.countDown();
}
}).start();
/*************************** GOT data from Server ********************************************/
try {
latch.await();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent intent = new Intent(MainPage.this, ViewImage.class);
Model model = list.get(position);
String myURL = model.getURL();
intent.putExtra("image", myURL);
startActivity(intent);}
});
}
public void dismissDialog(final ProgressDialog dialog){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
private Model get(String s, String url) {
return new Model(s, url);
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle("Exit!");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to leave?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainPage.this.finish();
}
})
.setNegativeButton("No",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();
}
// your code.
}
MyCustomArrayAdapter.java
public class MyCustomArrayAdapter extends ArrayAdapter<Model> {
private final Activity context;
private final List<Model> list;
public MyCustomArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.list_layout_relative, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected ImageView image;
protected ProgressBar pb;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.list_layout_relative, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.text.setTextColor(Color.BLACK);
viewHolder.image = (ImageView) view.findViewById(R.id.image);
viewHolder.image.setVisibility(View.GONE);
viewHolder.pb = (ProgressBar) view.findViewById(R.id.progressBar1);
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.image.setTag(list.get(position).getURL());
holder.image.setId(position);
PbAndImage pb_and_image = new PbAndImage();
pb_and_image.setImg(holder.image);
pb_and_image.setPb(holder.pb);
new DownloadImageTask().execute(pb_and_image);
return view;
}
}
Model.java
public class Model {
private String name;
private String url;
public Model(String name, String url) {
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getURL() {
return url;
}
public void setURL(String url) {
this.url = url;
}
}
i wanna ask something else too.kinda off topic.. i am downlaoding images from the urls and display in gridview. but it downloads huge images that takes lots of data. is there anyway i can download thumbnails to that images to reduce data usage?
same code but instead of extend listActivity extend normal activity and defining xml with GridView with id foo or what ever you want.
GridView foo = (GridView) findViewById(R.id.foo);
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
foo.setAdapter(adapter);

Remove item from another activity using button

The problem: I want to remove a item from my listview using a button in another activity.
I have tried several kinds of code, but it just doesn't seem to work.
Right know I use serializable to bundle the object to the other activity.
But I don't know how to remove it, from the other activity.
Can anybody help me with that?
Can I use the button from the second activity, in the first activity to delete the item from the listview?
Class A where I got my ListView
public class ListActivity extends Activity {
ListView list;
Button exit;
SimpleAdapter adapter;
final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
#Override``
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
for (int i = 0; i < title.length; i++) {
Map<String, String> datalist = new HashMap<String, String>();
datalist.put("title", title[i]);
datalist.put("subtitle", subtitle[i]);
data.add(datalist);
}
// getDataInList();
adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, new String[] { "title",
"subtitle" }, new int[] { android.R.id.text1,
android.R.id.text2 });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
Class B where I got my accept button.
When I click accept, the item from the listview in Class A should be removed.
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
int requestCode = 1;
SimpleAdapter adapter;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});``
//Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You should not directly remove the item from the view, but from the data displayed in it.
For example if your ListView is displaying items from an ArrayList, just remove the item in the ArrayList from you Activity B, and call myAdapter.notifyDataSetChanged() when back in the Activity A, which contains the adapter.
You can remove items by accessing to the ArrayList or by overriding the remove() method if you have only access to the adapter (assuming your adapter extends ArrayAdapter).
Also, you may have to override usefull Adapter methods like getCount(), getView()...
Thanks to all.
I found another solution thanks to remove row from another activity
Class A
public class ListActivity extends Activity {
ListView list;
Button exit;
static List<ListItems> items = new ArrayList<ListItems>();
public static int deletePos;
static ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
items = new ArrayList<ListItems>();
for (int i = 0; i < title.length; i++) {
ListItems s = new ListItems(title[i], subtitle[i]);
items.add(s);
}
adapter = new ListAdapter(this, android.R.layout.simple_list_item_2,
items);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
deletePos = position;
adapter.notifyDataSetChanged();
startActivity(intent);
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
Class B
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});
// Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int deletePos = ListActivity.deletePos;
ListActivity.items.remove(deletePos);
ListActivity.adapter.notifyDataSetChanged();
finish();
}
});
}
}

refresh listview when back button is pressed - android

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.

Listview Array Adapter position onClick

I have a listview with an ArrayAdapter. The ListView at a position fills itselfs with the same position in some ArrayList. In each listitem
there are two buttons. When the onClickListener start, it gets
the position of the overrided View getView(position, View etc.), takes some variables out of the ArrayList and sends it to a database. The problem is, the position is not really accurate. Sometimes I get the position of a Listitem above the Listitem I want. Here is the code:
public class MemoAdapter extends ArrayAdapter<String> {
private final Activity context;
ArrayList<String> commentarray;
ArrayList<String> fromarray;
ArrayList<String> datearray;
ArrayList<String> ids;
ArrayList<String> feedback;
Dialog dialog;
EditText feedbacktxt;
String token;
String website;
public MemoAdapter(Activity context, ArrayList<String> commentArray,
ArrayList<String> fromArray, ArrayList<String> dateArray,
ArrayList<String> ids, ArrayList<String> feedback, String token,
String website) {
super(context, R.layout.memo_listitem, commentArray);
this.context = context;
this.commentarray = commentArray;
this.fromarray = fromArray;
this.datearray = dateArray;
this.ids = ids;
this.feedback = feedback;
this.token = token;
this.website = website;
}
#Override
public long getItemId(int position) {
return 0;
}
// static to save the reference to the outer class and to avoid access to
// any members of the containing class
static class ViewHolder {
public TextView textView;
public TextView textView2;
public TextView textView3;
public TextView textView4;
// public ImageView reply;
// public ImageView accept;
public Button reply;
public Button accept;
public RelativeLayout r;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.memo_listitem, null);
holder = new ViewHolder();
holder.textView = (TextView) rowView
.findViewById(R.id.memodescription);
holder.textView2 = (TextView) rowView.findViewById(R.id.memofrom);
holder.textView3 = (TextView) rowView.findViewById(R.id.memodate);
holder.textView4 = (TextView) rowView
.findViewById(R.id.memofeedback);
holder.reply = (Button) rowView.findViewById(R.id.buttonFeedback);
holder.accept = (Button) rowView.findViewById(R.id.buttonAccepteer);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.textView.setText(commentarray.get(position));
holder.textView2.setText(datearray.get(position));
holder.textView3.setText(fromarray.get(position));
holder.textView4.setText(feedback.get(position));
if (holder.textView4.getText().toString().equals("")
|| holder.textView4.getText().toString().equals(" ")) {
holder.textView4.setText(" - ");
}
// ONCLICKLISTENER FOR REPLYIMAGE
holder.reply.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog = new Dialog(NostradamusActivity2.parentcontext);
dialog.setContentView(R.layout.memo_dialog);
dialog.setTitle("Feedback");
feedbacktxt = (EditText) dialog.findViewById(R.id.memoeddittxt);
Button cancel = (Button) dialog
.findViewById(R.id.memobtncancel);
// CANCEL BUTTON ONCLICKLISTENER REPLYIMAGE
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
Button okay = (Button) dialog.findViewById(R.id.memobtnokay);
// OKAY BUTTON ONCLICKLISTENER REPLYIMAGE
okay.setOnClickListener(new OnClickListener() {
private String errormessage;
private AlertDialog alertDialog;
public void onClick(View v) {
Database2 db = new Database2(
"https://"
+ website
+ "/index2.php?option=com_webservices&controller=json&method=core.memos.memo_feedback&token=",
"token", token, "id", ids.get(position),
"memo_feedback", feedbacktxt.getText()
.toString());
}
// //ACCEPTEER MEMO BUTTON ONCLICKLISTENER
holder.accept.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(
NostradamusActivity2.parentcontext);
builder.setMessage("Heeft u de opdracht uitgevoerd?")
.setCancelable(false)
.setPositiveButton("Ja",
new DialogInterface.OnClickListener() {
private AlertDialog alertDialog;
public void onClick(DialogInterface dialog,
int id) {
Database2 dbaccept = new Database2(
"http://intern.koeckers.nl/index2.php?option=com_webservices&controller=json&method=core.memos.memo_state&token=",
"token", token, "id", ids
.get(position),
"memo_completed", "1");
dialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Nee",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return rowView;
}
}
You are getting the item by ids.get(position).
You are using the arrayList, instead use the getTag() method.
rowView.getTag() will give you the ViewHolder from which, you can get the correct ids and Feedback Text.
Database2 dbaccept = new Database2(
"http://intern.koeckers.nl/index2.php? option=com_webservices&controller=json&method=core.memos.memo_state&token=",
"token", token, "id", ids.get(position),
"memo_completed", "1");

Categories

Resources