I have this weird bug that I cannot seem to diagnose, I have 2 fields one is getting the value from the DB and the other one is not.
My problem is that "friends[position].userPresence" isn't returning any values from DB, but an Identical one called "friends[position].userStatus" is returning values, but when I assign userPresence's column name to userStatus, then userStatus is returning the correct info for the column.
Any help would be highly appreciated!
public class FriendList extends ListActivity {
private static final int ADD_NEW_FRIEND_ID = Menu.FIRST;
private static final int EXIT_APP_ID = Menu.FIRST + 1;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter {
class ViewHolder {
TextView text;
TextView status;
ImageView avatar;
ImageView onlstatus;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private Bitmap mAwayIcon;
private Bitmap mPersonPic;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.online);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.offline);
mAwayIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.away);
mPersonPic = BitmapFactory.decodeResource(context.getResources(),
R.drawable.no_photo_icon_big);
}
public void setFriendList(FriendInfo[] friends) {
this.friends = friends;
}
#Override
public int getCount() {
return friends.length;
}
#Override
public FriendInfo getItem(int position) {
return friends[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid
// unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is
// no need
// to reinflate it. We only inflate a new View when the convertView
// supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.friend_list_screen,
null);
// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.userName);
holder.status = (TextView) convertView
.findViewById(R.id.userStatusMsg);
holder.onlstatus = (ImageView) convertView
.findViewById(R.id.icon_status);
holder.avatar = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(friends[position].userName);
holder.onlstatus
.setImageBitmap(friends[position].userStatus == "Available" ? mOnlineIcon :
friends[position].userStatus == "Busy" ? mOfflineIcon : mAwayIcon);
holder.avatar.setImageBitmap(mPersonPic);
holder.status.setText(friends[position].userPresence);
/*
* holder.icon .setImageBitmap(friends[position].status ==
* STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
*/
return convertView;
}
}
FriendInfo
public class FriendList extends ListActivity {
private static final int ADD_NEW_FRIEND_ID = Menu.FIRST;
private static final int EXIT_APP_ID = Menu.FIRST + 1;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter {
class ViewHolder {
TextView text;
TextView status;
ImageView avatar;
ImageView onlstatus;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private Bitmap mAwayIcon;
private Bitmap mPersonPic;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.online);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.offline);
mAwayIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.away);
mPersonPic = BitmapFactory.decodeResource(context.getResources(),
R.drawable.no_photo_icon_big);
}
public void setFriendList(FriendInfo[] friends) {
this.friends = friends;
}
#Override
public int getCount() {
return friends.length;
}
#Override
public FriendInfo getItem(int position) {
return friends[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid
// unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is
// no need
// to reinflate it. We only inflate a new View when the convertView
// supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.friend_list_screen,
null);
// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.userName);
holder.status = (TextView) convertView
.findViewById(R.id.userStatusMsg);
holder.onlstatus = (ImageView) convertView
.findViewById(R.id.icon_status);
holder.avatar = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(friends[position].userName);
holder.onlstatus
.setImageBitmap(friends[position].userStatus == "Available" ? mOnlineIcon :
friends[position].userStatus == "Busy" ? mOfflineIcon : mAwayIcon);
holder.avatar.setImageBitmap(mPersonPic);
holder.status.setText(friends[position].userPresence);
/*
* holder.icon .setImageBitmap(friends[position].status ==
* STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
*/
return convertView;
}
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast receiver ", "received a message");
Bundle extra = intent.getExtras();
if (extra != null) {
String action = intent.getAction();
if (action.equals(IMService.FRIEND_LIST_UPDATED)) {
// taking friend List from broadcast
// String rawFriendList =
// extra.getString(FriendInfo.FRIEND_LIST);
// FriendList.this.parseFriendInfo(rawFriendList);
FriendList.this.updateData(
FriendController.getFriendsInfo(),
FriendController.getUnapprovedFriendsInfo());
}
}
}
};
public MessageReceiver messageReceiver = new MessageReceiver();
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder) service).getService();
FriendInfo[] friends = FriendController.getFriendsInfo(); // imService.getLastRawFriendList();
if (friends != null) {
FriendList.this.updateData(friends, null); // parseFriendInfo(friendList);
}
// setTitle(imService.getUsername() + "'s friend list");
CommonUtility.setCustomTitlebar(FriendList.this, imService);
ownusername = imService.getUsername();
((LinearLayout)findViewById(R.id.actionbar_layout)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(FriendList.this,UserProfile.class));
}
});
}
#Override
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(FriendList.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.list_screen);
friendAdapter = new FriendListAdapter(this);
}
public void updateData(FriendInfo[] friends, FriendInfo[] unApprovedFriends) {
if (friends != null) {
friendAdapter.setFriendList(friends);
setListAdapter(friendAdapter);
}
if (unApprovedFriends != null) {
NotificationManager NM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (unApprovedFriends.length > 0) {
String tmp = new String();
for (int j = 0; j < unApprovedFriends.length; j++) {
tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher) // TODO Redo
// friend
// notification
.setContentTitle(
getText(R.string.new_friend_request_exist));
/*
* Notification notification = new
* Notification(R.drawable.stat_sample,
* getText(R.string.new_friend_request_exist),
* System.currentTimeMillis());
*/
Intent i = new Intent(this, UnApprovedFriendList.class);
i.putExtra(FriendInfo.FRIEND_LIST, tmp);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, i, 0);
mBuilder.setContentText("You have new friend request(s)");
/*
* notification.setLatestEventInfo(this,
* getText(R.string.new_friend_request_exist),
* "You have new friend request(s)", contentIntent);
*/
mBuilder.setContentIntent(contentIntent);
NM.notify(R.string.new_friend_request_exist, mBuilder.build());
} else {
// if any request exists, then cancel it
NM.cancel(R.string.new_friend_request_exist);
}
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, Messaging.class);
FriendInfo friend = friendAdapter.getItem(position);
i.putExtra(FriendInfo.USERNAME, friend.userName);
i.putExtra(FriendInfo.PORT, friend.port);
i.putExtra(FriendInfo.IP, friend.ip);
startActivity(i);
}
#Override
protected void onPause() {
unregisterReceiver(messageReceiver);
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(FriendList.this, IMService.class), mConnection,
Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
// i.addAction(IMService.TAKE_MESSAGE);
i.addAction(IMService.FRIEND_LIST_UPDATED);
registerReceiver(messageReceiver, i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, ADD_NEW_FRIEND_ID, 0, R.string.add_new_friend);
menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);
return result;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case ADD_NEW_FRIEND_ID: {
Intent i = new Intent(FriendList.this, AddFriend.class);
startActivity(i);
return true;
}
case EXIT_APP_ID: {
imService.exit();
finish();
return true;
}
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
The XML Handler
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if (localName == "friend") {
FriendInfo friend = new FriendInfo();
friend.userName = attributes.getValue(FriendInfo.USERNAME);
String status = attributes.getValue(FriendInfo.STATUS);
friend.ip = attributes.getValue(FriendInfo.IP);
friend.port = attributes.getValue(FriendInfo.PORT);
friend.userPresence = attributes.getValue(FriendInfo.USER_PRESENCE);
friend.userStatus = attributes.getValue(FriendInfo.USER_STATUS);
friend.userDisplayName = attributes.getValue(FriendInfo.USER_DISPNAME);
friend.userKey = attributes.getValue(FriendInfo.USER_KEY);
friend.expire = attributes.getValue("expire");
if (status != null && status.equals("online")) {
friend.status = STATUS.ONLINE;
mOnlineFriends.add(friend);
} else if (status.equals("unApproved")) {
friend.status = STATUS.UNAPPROVED;
mUnapprovedFriends.add(friend);
} else {
friend.status = STATUS.OFFLINE;
mFriends.add(friend);
}
} else if (localName == "user") {
this.userKey = attributes.getValue(FriendInfo.USER_KEY);
} else if (localName == "message") {
MessageInfo message = new MessageInfo();
message.userid = attributes.getValue(MessageInfo.USERID);
message.sendt = attributes.getValue(MessageInfo.SENDT);
message.messagetext = attributes.getValue(MessageInfo.MESSAGETEXT);
Log.i("MessageLOG", message.userid + message.sendt
+ message.messagetext);
mUnreadMessages.add(message);
}
super.startElement(uri, localName, name, attributes);
}
FriendInfo Class
public class FriendInfo {
public static final String FRIEND_LIST = "friendList";
public static final String USERNAME = "username";
public static final String IP = "IP";
public static final String PORT = "port";
public static final String USER_KEY = "userKey";
public static final String USER_DISPNAME = "displayname";
public static final String MESSAGE = "message"; // this should not be in
// here
public static final String STATUS = "status";
public static final String USER_STATUS = "status_msg";
public static final String USER_PRESENCE = "status_msg2";
public STATUS status;
public String userStatus;
public String userPresence;
public String userDisplayName;
public String userName;
public String ip;
public String port;
public String userKey;
public String expire;
};
I don't see what the solution is. However, I would suggest you flood your program with System.out.println() statements to see what values are throughout your program. Alternately (and better) is to use your IDE's debugger and set breakpoints to examine values.
Related
I have an abstract class "ListItem" with two subclasses - "Header"(Data) and "Event". Depending on the situation, the array should be displayed either as "Header" - "Events of this data", or just events.
The created object of the "Event" class is passed to the main fragment from a separate activity. If I only need to display events, I just write it to an array and update the adapter data, it works. If, after creating a class object, I need to display it and existing events in the form "Header" - "Events", then the adapter for some reason is not updated and the new event is not displayed. If you close the application and reopen it, the event appears in its normal form with a header.
Here's my RV Adapter
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final String TAG = "myLogs";
private ArrayList<ListItem> list;
final SparseBooleanArray selectedItems = new SparseBooleanArray();
private int currentSelectedPos;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM", myDateFormatSymbols);
public EventAdapter(ArrayList<ListItem> items){
list = items;
}
public ArrayList<ListItem> getItems(){
return list;
}
private EventAdapterListener itemClickListener;
public interface EventAdapterListener {
void onItemClick(int position);
void onItemLongClick(int position);
}
public void setListener(EventAdapterListener listener){
itemClickListener = listener;
}
private OnItemCheckedListener OnItemChecked;
public interface OnItemCheckedListener {
void onItemChecked(int position, boolean isImportant);
}
public void setOnItemCheckedListener (OnItemCheckedListener listener){
OnItemChecked = listener;
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public TextView TVtitle;
public TextView TVcomment;
public CheckBox CBimportance;
public TextView TVdate;
//public EventViewHolder(#NonNull View itemView, final EventAdapterListener listener) {
public EventViewHolder(#NonNull View itemView) {
super(itemView);
}
}
public void removeAllObjectsOf(Class<? extends ListItem> cls) {
Iterator itr = list.iterator();
while (itr.hasNext()) {
if (itr.next().getClass().equals(cls)) {
itr.remove();
}
}
notifyDataSetChanged();
}
Comparator<ListItem> dateComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).Date.compareTo(((Event)t1).Date);
}
};
Comparator<ListItem> importanceComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).IsImportant.compareTo(((Event)t1).IsImportant);
}
};
Comparator<ListItem> nameComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).Name.compareTo(((Event)t1).Name);
}
};
Comparator<ListItem> completenessComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).IsComplete.compareTo(((Event)t1).IsComplete);
}
};
public void sortBy(Comparator<ListItem> comparator, ArrayList<ListItem> list) {
removeAllObjectsOf(Header.class);
Collections.sort(list, comparator);
}
public void groupByDate()
{
ArrayList<ListItem> result = new ArrayList<>();
removeAllObjectsOf(Header.class);
sortBy(dateComparator, list);
ArrayList<Long> dates = new ArrayList<>();
for (ListItem event: list)
{
if (!(dates.contains(((Event)event).getDate())))
{
dates.add(((Event)event).getDate());
ArrayList<ListItem> ei = getItemsbyDate(list, ((Event)event).getDate());
Header header = new Header();
header.setHeader(String.valueOf(((Event)event).getDate()));
result.add(header);
result.addAll(ei);
}
}
list = result;
notifyDataSetChanged();
}
public ArrayList<ListItem> getItemsbyDate(ArrayList<ListItem> items, Long date){
ArrayList<ListItem> result = new ArrayList<>();
for (ListItem ci : items){
if (((Event)ci).getDate().equals(date)){
result.add(ci);
}
}
return result;
}
public void removeItem(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,list.size());
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return list.get(position) instanceof Header;
}
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
#Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
if (viewType == TYPE_HEADER){
View v = inflater.inflate(R.layout.group_layout, parent, false);
return new VHHeader(v);
} else {
View v = inflater.inflate(R.layout.list_item_cardview, parent, false);
return new VHItem(v);
}
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, final int position)
{
if (holder instanceof VHHeader){
Header currentItem = (Header) list.get(position);
VHHeader VHheader = (VHHeader) holder;
VHheader.txtTitle.setText(simpleDateFormat.format(Long.parseLong(currentItem.getHeader())));
} else if (holder instanceof VHItem) {
final Event event = (Event) list.get(position);
VHItem VHitem = (VHItem) holder;
VHitem.txtName.setText(event.getName());
VHitem.txtDate.setText(simpleDateFormat.format(event.getDate()));
VHitem.TVcomment.setText(event.getComment());
VHitem.CBimportance.setOnCheckedChangeListener(null);
VHitem.CBimportance.setChecked(event.getImportant());
VHitem.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
event.IsImportant = b;
OnItemChecked.onItemChecked(position, b);
}
});
VHitem.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectedItems.size() > 0 && itemClickListener != null){
itemClickListener.onItemClick(position);
}
}
});
VHitem.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (itemClickListener != null){
itemClickListener.onItemLongClick(position);
}
return true;
}
});
if (currentSelectedPos == position) currentSelectedPos = -1;
}
}
#Override
public int getItemCount() {
return (list == null) ? 0 : list.size();
}
void deleteEvents(){
List<ListItem> selectedEvents = new ArrayList<>();
for (ListItem item : list){
if (item instanceof Event){
if (((Event) item).getSelected()){
selectedEvents.add(item);
}
}
}
list.removeAll(selectedEvents);
//notifyDataSetChanged();
currentSelectedPos = -1;
deleteEmptyHeaders();
}
public int getCountofHeaderItems(Header header)
{
int k = 0;
for (ListItem item: list)
{
if (item instanceof Event){
if (((Event) item).Date.equals(Long.parseLong(header.getHeader()))){
k++;
}
}
}
return k;
}
void deleteEmptyHeaders(){
List<Header> headers = new ArrayList<>();
for (ListItem event : list){
if (event instanceof Header){
if (getCountofHeaderItems((Header)event) == 0){
headers.add((Header)event);
}
}
}
list.removeAll(headers);
}
void toggleSelection(int position) {
if (getItemViewType(position) == TYPE_ITEM){
currentSelectedPos = position;
if (selectedItems.get(position)) {
selectedItems.delete(position);
((Event)list.get(position)).setSelected(false);
} else {
selectedItems.put(position, true);
((Event)list.get(position)).setSelected(true);
}
notifyItemChanged(position);
}
}
class VHHeader extends EventAdapter.EventViewHolder {
TextView txtTitle;
public VHHeader(View itemView) {
super(itemView);
this.txtTitle = (TextView) itemView.findViewById(R.id.tvTitleGroup);
}
}
class VHItem extends EventAdapter.EventViewHolder {
TextView txtName;
TextView txtDate;
TextView TVcomment;
CheckBox CBimportance;
public VHItem(View itemView) {
super(itemView);
this.txtName = (TextView) itemView.findViewById(R.id.tvTitle);
this.txtDate = (TextView) itemView.findViewById(R.id.tvDate);
this.TVcomment = (TextView) itemView.findViewById(R.id.tvComment);
this.CBimportance = (CheckBox) itemView.findViewById(R.id.cbIconImportant);
}
}
}
Here's my MainFragment:
private final static String ONLY_EVENTS = "ONLY_EVENTS";
private final static String GROUP_EVENTS_BY_DATE = "GROUP_EVENTS_BY_DATE";
ArrayList<ListItem> events;
private String ShowMode = ONLY_EVENTS;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first_new, container, false);
events = read(this.getActivity(), PROCESSED_EVENTS);
if (events == null)
events = new ArrayList<ListItem>();
rvEvent = view.findViewById(R.id.recyclerview);
rvEvent.setHasFixedSize(true);
lmEvent = new LinearLayoutManager(this.getContext());
adapterEvent = new EventAdapter(events);
rvEvent.setLayoutManager(lmEvent);
rvEvent.setAdapter(adapterEvent);
ShowEvents(ShowMode);
initSwipe();
return view;
}
public void ShowEvents(String mode){
switch (mode){
case ONLY_EVENTS:
adapterEvent.removeAllObjectsOf(Header.class);
break;
case GROUP_EVENTS_BY_DATE:
adapterEvent.groupByDate();
break;
}
}
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
Event nd = (Event) data.getSerializableExtra("class");
events.add(nd);
write(this.getActivity(), events, PROCESSED_EVENTS);
if (ShowMode.equals(GROUP_EVENTS_BY_DATE))
adapterEvent.groupByDate();
adapterEvent.notifyDataSetChanged();
}
}
public static void write(Context context, ArrayList<ListItem> events, String Key) {
Gson gson = new Gson();
String jsonString = gson.toJson(events);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Key, jsonString);
editor.apply();
}
public static ArrayList<ListItem> read(Context context, String Key) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String jsonString = pref.getString(Key, "");
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Event>>() {
}.getType();
ArrayList<ListItem> list = gson.fromJson(jsonString, type);
return list;
}
This is how the Event is sent from the activity:
Intent intent = new Intent(NewEvent.this, FirstFragment.class);
//intent.putExtra("name", (String) etName.getText().toString());
objectEvent = new Event(etName.getText().toString(), date, etComment.getText().toString(), etType.getText().toString(), etNotif.getText().toString(), swIsComplete.isChecked(), false);
intent.putExtra("class", objectEvent);
setResult(RESULT_OK, intent);
finish();
UPD. In OnActivityResult after executing the line adapterEvent.groupByDate(); nothing changes. Changes take place in the array list in the adapter, but for some reason they do not go into the array that is used in the fragment. In the ShowEvents procedure, the same line of code works, and after it the array is changed.
Am looking to create a fragment conaining listview by retriveing data from firebase database.This listview gets cards having buttons and seekbar. All I want is to have a global variable listen to these buttons. I tried creating onClicklistener in the fragment itself but wasn't successful.Then I created onClicklistener for these buttons on the Adapter itself which was working. Now when I use the buttonclick to create a Toast, the Toast string is coming up as I expect. But the problem is that I want this Toasted string to store somewhere like global variable so that I could use it in another fragment as well. So I used:
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication)getContext()).setCartitem("XYZ");
inside my adapter class's on Click Listener itself but the application crashes showing error log "First cannot be cast to com.fastfrooot.fastfrooot.MyApplication". First being my Activity containing Fragment and MyApplication is the class extending application.
MyApplication.java
package com.fastfrooot.fastfrooot;
import android.app.Application;
import android.widget.Button;
public class MyApplication extends Application {
private boolean[] cartsitem = {
false,
false,
false,
false,
false,
false
};
private String orderitem;
private String pkname;
private boolean oncomp = false;
private Button[] cartbuttons = new Button[20];
private String cartitem = "Alpha";
public boolean[] getcartsitem() {
return cartsitem;
}
public void setcartsitem(boolean[] cartsitem) {
this.cartsitem = cartsitem;
}
public String getorderitem() {
return orderitem;
}
public void setorderitem(String orderitem) {
this.orderitem = orderitem;
}
public String getpkname() {
return pkname;
}
public void setpkname(String pkname) {
this.pkname = pkname;
}
public boolean getoncomp() {
return oncomp;
}
public void setoncomp(boolean oncomp) {
this.oncomp = oncomp;
}
public Button[] getcartbuttons() {
return cartbuttons;
}
public void setCartbuttons(Button[] cartbuttons) {
this.cartbuttons = cartbuttons;
}
public String getCartitem() {
return cartitem;
}
public void setCartitem(String cartitem) {
this.cartitem = cartitem;
}
}
public class CustomListAdapterfir extends ArrayAdapter < Cardfir > {
private static final String TAG = "CustomListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private int procount;
String Cartkeitem;
private static class ViewHolder {
TextView title;
ImageView image;
TextView Status;
Button cartbutton;
SeekBar seekbar;
}
public CustomListAdapterfir(Context context, int resource, List < Cardfir > objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
//sets up the image loader library
setupImageLoader();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the persons information
final String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();
final String Status = getItem(position).getStatus();
Button cartbutton = getItem(position).getCartbutton();
final SeekBar seekBar = getItem(position).getSeekbar();
try {
//create the view result for showing the animation
final View result;
//ViewHolder object
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.Status = (TextView) convertView.findViewById(R.id.cardstat);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBarf);
holder.cartbutton = (Button) convertView.findViewById(R.id.Addbutton);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
holder.title.setText(title);
holder.Status.setText(Status);
holder.cartbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int seekerpos = holder.seekbar.getProgress() + 1;
Cartkeitem = title + " " + String.valueOf(seekerpos);
Toast.makeText(mContext, Cartkeitem, Toast.LENGTH_SHORT).show();
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication) getContext()).setCartitem("XYZ");
}
});
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//create the imageloader object
ImageLoader imageLoader = ImageLoader.getInstance();
int defaultImage = mContext.getResources().getIdentifier("#drawable/logo", null, mContext.getPackageName());
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();
imageLoader.displayImage(imgUrl, holder.image, options);
return convertView;
} catch (IllegalArgumentException e) {
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage());
return convertView;
}
}
private void setupImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
}
}
public class Tab1fragment extends Fragment implements View.OnClickListener {
private static final String TAG = "TAG1 fragment";
private ListView mListView;
DatabaseReference Complete = FirebaseDatabase.getInstance().getReference();
DatabaseReference Products = Complete.child("Products");
ValueEventListener productlistener;
final ArrayList < Cardfir > list = new ArrayList < Cardfir > ();
String productname;
String producttype;
final ArrayList < Button > Cartbuttons = new ArrayList < Button > ();
final ArrayList < SeekBar > Seekbars = new ArrayList < SeekBar > ();
int productnumber = -1;
Button[] Cartsbut = new Button[20];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listview);
productlistener = Products.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot delphi: dataSnapshot.getChildren()) {
productnumber = productnumber + 1;
productname = delphi.child("Name").getValue().toString();
producttype = delphi.child("Type").getValue().toString();
list.add(new Cardfir("drawable://" + R.drawable.trans, productname, producttype));
}
CustomListAdapterfir adapter = new CustomListAdapterfir(getActivity(), R.layout.card_layout_liveorder, list);
mListView.setAdapter(adapter);
Products.removeEventListener(productlistener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_SHORT).show();
}
}
[EDIT] I'm new to android development, so please bear with me. I have two java classes named Join Game, extends to AppCompatActivity and HintList,extends to ArrayAdapter<>. This is connected to a database. So maybe its one of the factors?
For the layout of join game, I have a listview
and for the layout of hintlist I have three textview.
The code goes this way
JoinGame
public class JoinGame extends AppCompatActivity {
ListView list;
String[] itemdescription = {};
String[] itemhints = {};
String[] itemlocasyon = {};
ProgressDialog progress;
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joingame);
Button schan = (Button)findViewById(R.id.tarascan);
schan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(JoinGame.this,ScanActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
progress = new ProgressDialog(this);
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
RequestFactory.joingameitems(JoinGame.this, RequestFactory.user_id, new RequestCallback<JSONArray>() {
#Override
public void onSuccess(final JSONArray response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
} catch (JSONException e) {
e.printStackTrace();
}
} ////////// below this is the adapter
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
}
});
}
#Override
public void onFailed(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(JoinGame.this, message, Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
HintList
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, null, true);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
}
I actually retrieved the data (here)
E/DB: [{"description":"chinese garter","location":"near Tricycle station","hint":"garter plus chinese"},{"description":"isang pinoy game","location":"near ....","hint":"may salitang baka"},{"description":"\"tinik\"","location":"below...","hint":"may salitang tinik"},{"description":"aka Tinubigan","location":"at the back...","hint":"katunog ng pintero"},{"description":"\"knock down the can\"","location":"near...","hint":"gumagamit ng lata"}]
but it doesnt display on my listview
I dont know anymore what I should do.
I actually tried making this (I added view)
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)view.findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
but it will only returns an error of java.lang.NullPointerException: Attempt to invoke virtual method
Change this:
View rowView = inflater.inflate(R.layout.hints_list, null, true);
to:
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
Modify your getView() method to:
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
try adding getCount
#Override
public int getCount() {
return itemHints.length;
}
Try to change your code to this
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
private LayoutInflater inflater=null;
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return itemHints.length;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
view=inflater.inflate(R.layout.hints_list, null, true);
holder = new ViewHolder(view);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
holder.itemDesc2.setText(itemDesc[position]);
holder.itemHint.setText(itemHints[position]);
holder.itemLocation2.setText(itemLocation[position]);
return view;
}
static class ViewHolder{
TextView itemDesc2,itemHint,itemLocation2;
ViewHolder(View view) {
itemDesc2 = (TextView)view.findViewById(R.id.itemdescription);
itemHint = (TextView)view.findViewById(R.id.itemhint);
itemLocation2 = (TextView)view.findViewById(R.id.itemlocation);
}
}
}
My suggestions is create a bean class (DetailsBean), used for setter and getter method, and also the ArrayList (details1).
List<DetailsBean> details1 = new ArrayList<>(); // declare this as global
Then add the bean to below code
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
// here the bean
DetailsBean dbean = new DetailsBean(itemDescription, itemhints, itemlocasyon);
details1.add(dbean); // add all the data to details1 ArrayList
HintList hladapt = new HintList(getActivity(), details1);
(ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
} catch (JSONException e) {
e.printStackTrace();
}
}
Your DetailsBean should looked like this
public class DetailsBean {
private String itemDescription="";
private String itemhints="";
private String itemlocasyon ="";
public DetailsBean(String description, String hints, String itemlocasyon) {
this.itemDescription=description;
.....
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDesription;
}
public String getItemDescription() {
return itemDescription;
}
....
}
Then your HintList
public class HintList extends BaseAdapter{
Activity context;
List<DetailsBean> details;
private LayoutInflater mInflater;
public CustomBaseAdapter(Activity context,List<DetailsBean> details) {
this.context = context;
this.details = details;
}
........
}
Add these Override methods in your adapter
#Override
public int getCount() {
return itemHints.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
My code is working fine when it comes to clicking items. But the problem arises when I try to open activities after filtering listview. It always opens activity 1.
Here is my source code.
navigate.java
public class navigate extends Activity {
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] names;
int[] flag;
ArrayList<Object> arraylist = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
// Generate sample data
rank = new String[] { "1", "2", "3", "4", "5","6","7","8","9","10","11"};
names = new String[] { "Animal Bite", "Asthma Attack", "Choking","CPR","Black eye",
"Drowning", "Fracture","Heart Attack","Insect Bite","Poisoning","Spinal Injury",};
flag = new int[] { R.drawable.animal,
R.drawable.asthma, R.drawable.choke, R.drawable.cpricon,
R.drawable.blckeye,R.drawable.drown,R.drawable.fracture,R.drawable.hrtattck,R.drawable.insect,R.drawable.poison,R.drawable.spinal };
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < rank.length; i++)
{
Object wp = new Object(rank[i], names[i], flag[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> listView, View view,
final int position, long id) {
switch ((int) adapter.getItemId(position)) {
case 0:
Intent newActivity = new Intent(navigate.this, animalbite.class);
startActivity(newActivity);
break;
case 1:Intent newActivity1 = new Intent(navigate.this, asthmaattack.class);
startActivity(newActivity1);
break;
case 2:Intent newActivity2 = new Intent(navigate.this, animalbite.class);
startActivity(newActivity2);
break;}
}
});
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Object> objectList = null;
private ArrayList<Object> arraylist;
public ListViewAdapter(Context context,
List<Object> objectList) {
mContext = context;
this.objectList = objectList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Object>();
this.arraylist.addAll(objectList);
}
public class ViewHolder {
TextView name;
ImageView flag;
}
#Override
public int getCount() {
return objectList.size();
}
#Override
public Object getItem(int position) {
return objectList.get(position);
}
public String getCountry(int position){return objectList.get(position).getCountry();}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
//holder.rank = (TextView) view.findViewById(R.id.rank);
holder.name = (TextView) view.findViewById(R.id.name);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(objectList.get(position).getRank());
holder.name.setText(objectList.get(position).getCountry());
;
// Set the results into ImageView
holder.flag.setImageResource(objectList.get(position)
.getFlag());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
// Pass all data rank
// Start SingleItemView Class
switch (position) {
case 0:
Intent intent = new Intent(mContext, animalbite.class);
mContext.startActivity(intent);break;
case 1:
Intent i2 = new Intent(mContext, asthmaattack.class);
mContext.startActivity(i2);break;
case 2:
Intent i3 = new Intent(mContext, choking.class);
mContext.startActivity(i3);break;
case 3:
Intent i4 = new Intent(mContext, cpr.class);
mContext.startActivity(i4);break;
case 4:
Intent i5 = new Intent(mContext, lackeye.class);
mContext.startActivity(i5);break;
case 5:
Intent i6 = new Intent(mContext, drowning.class);
mContext.startActivity(i6);break;
case 6:
Intent i7 = new Intent(mContext, Fracture.class);
mContext.startActivity(i7);break;
case 7:
Intent i8 = new Intent(mContext, heartattack.class);
mContext.startActivity(i8);break;
case 8:
Intent i9 = new Intent(mContext, insectbite.class);
mContext.startActivity(i9);break;
case 9:
Intent i10 = new Intent(mContext, poisoning.class);
mContext.startActivity(i10);break;
case 10:
Intent i11 = new Intent(mContext, spinalinjury.class);
mContext.startActivity(i11);break;
}}});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
objectList.clear();
if (charText.length() == 0) {
objectList.addAll(arraylist);
} else {
for (Object wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
objectList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Object.java
public class Object {
private String rank;
private String country;
private int flag;
public Object(String rank, String country,
int flag) {
this.rank = rank;
this.country = country;
this.flag = flag;
}
public String getCountry() {
return this.country;
}
public int getFlag() {
return this.flag;
}
}
How can I open different activities while clicking on listview items after I filter them.
This is the sample code I used. Although it doesn't provide the functionality to open original activities through intent ,just some forged up activity,so I'm trying to change that.
http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/
I think your adapter has problem, this below sample code of my application is extended from Filterable and work fine
public class AdapterContacts extends BaseAdapter implements Filterable {
private LayoutInflater inflater;
private Context context;
private List<ContactLists> categoryArrayList;
private final ArrayList<ContactLists> originalList = new ArrayList<ContactLists>();
private NameFilter filter;
public AdapterContacts(ArrayList<ContactLists> array) {
categoryArrayList = array;
}
public AdapterContacts(Context context, List<ContactLists> array) {
this.context = context;
inflater = LayoutInflater.from(this.context);
categoryArrayList = array;
originalList.addAll(array);
}
#Override
public int getCount() {
return categoryArrayList.size();
}
#Override
public ContactLists getItem(int position) {
return categoryArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_contacts_list_item, null);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
ContactLists item = getItem(position);
mViewHolder.fillItems(this, item, position);
return convertView;
}
private static class UI extends HelperUI {
public TextView tv_person_nickname_mobile_number;
public TextView btn_invite_message;
public ImageView img_contact_image;
public ImageView imgv_user_rank;
public TextView tv_contact_name;
public LinearLayout ll_root;
public UI(View view) {
parseUi(view);
}
}
private class ViewHolder {
private UI UI;
public ViewHolder(View view) {
UI = new UI(view);
}
public void fillItems(final AdapterContacts adapter, final ContactLists item, final int position) {
UI.tv_contact_name.setText(item.getContact_name());
if (item.getStatus() == 1) {
UI.btn_invite_message.setVisibility(View.GONE);
UI.imgv_user_rank.setVisibility(View.VISIBLE);
if (item.getRank() != null || !TextUtils.isEmpty(item.getRank())) {
//Picasso.with(G.context).load(item.getRank()).into(UI.imgv_user_rank);
}
UI.tv_person_nickname_mobile_number.setText(item.getNick_name());
//UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_button_actions));
if (item.getContact_image() == null || TextUtils.isEmpty(item.getContact_image())) {
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
} else {
// show user avatar from web
//Picasso.with(G.context).load(item.getContact_image()).into(UI.img_contact_image);
UI.img_contact_image.setImageBitmap(BitmapFactory.decodeFile(G.DIR_IMAGE + "/" + item.getContact_image()));
}
} else {
// UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_invite_actions));
UI.btn_invite_message.setVisibility(View.VISIBLE);
UI.imgv_user_rank.setVisibility(View.GONE);
UI.btn_invite_message.setText(UC.getString(R.string.invite_person));
UI.btn_invite_message.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.shape_invite_button_default));
UI.tv_person_nickname_mobile_number.setText(item.getMobile_number());
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
}
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new NameFilter();
}
return filter;
}
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
}
Im creating a custom ListPreference on the back of this example.
I've implemented it and it works. But I can only add a max of 5 item to the ListPreference. If I add 7 items they appears in the list but when I click it it does nothing, just closes the ListPref dialog and return to the pref screen
public class IconPickerPreference extends ListPreference {
private class CustomListPreferenceAdapter extends ArrayAdapter<IconItem> {
private Context context;
private List<IconItem> icons;
private int resource;
public CustomListPreferenceAdapter(Context context, int resource, List<IconItem> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.icons = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(resource, parent, false);
holder = new ViewHolder();
holder.iconName = (TextView) convertView
.findViewById(R.id.iconName);
holder.iconImage = (ImageView) convertView
.findViewById(R.id.iconImage);
holder.radioButton = (RadioButton) convertView
.findViewById(R.id.iconRadio);
holder.position = position;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.iconName.setText(icons.get(position).name);
int identifier = context.getResources().getIdentifier(
icons.get(position).file, "drawable",
context.getPackageName());
holder.iconImage.setImageResource(identifier);
holder.radioButton.setChecked(icons.get(position).isChecked);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewHolder holder = (ViewHolder) v.getTag();
for (int i = 0; i < icons.size(); i++) {
if (i == holder.position)
icons.get(i).isChecked = true;
else
icons.get(i).isChecked = false;
}
getDialog().dismiss();
}
});
return convertView;
}
}
private static class IconItem {
private String file;
private boolean isChecked;
private String name;
public IconItem(CharSequence name, CharSequence file, boolean isChecked) {
this(name.toString(), file.toString(), isChecked);
}
public IconItem(String name, String file, boolean isChecked) {
this.name = name;
this.file = file;
this.isChecked = isChecked;
}
}
private static class ViewHolder {
protected ImageView iconImage;
protected TextView iconName;
protected int position;
protected RadioButton radioButton;
}
private Context context;
private ImageView icon;
private CharSequence[] iconFile;
private CharSequence[] iconName;
private List<IconItem> icons;
private SharedPreferences preferences;
private Resources resources;
private String selectedIconFile, defaultIconFile;
private TextView summary;
public IconPickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
resources = context.getResources();
preferences = PreferenceManager.getDefaultSharedPreferences(context);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.attrs_icon, 0, 0);
try {
defaultIconFile = a.getString(R.styleable.attrs_icon_iconFile);
} finally {
a.recycle();
}
}
private String getEntry(String value) {
String[] entries = resources.getStringArray(R.array.iconName);
String[] values = resources.getStringArray(R.array.iconFile);
int index = Arrays.asList(values).indexOf(value);
return entries[index];
}
#Override
protected void onBindView(View view) {
super.onBindView(view);
selectedIconFile = preferences.getString(
resources.getString(R.string.custom_icon_key), defaultIconFile);
icon = (ImageView) view.findViewById(R.id.iconSelected);
updateIcon();
summary = (TextView) view.findViewById(R.id.summary);
summary.setText(getEntry(selectedIconFile));
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (icons != null) {
for (int i = 0; i < icons.size(); i++) {
IconItem item = icons.get(i);
if (item.isChecked) {
Editor editor = preferences.edit();
editor.putString(
resources.getString(R.string.custom_icon_key),
item.file);
editor.apply();
selectedIconFile = item.file;
updateIcon();
summary.setText(item.name);
break;
}
}
}
}
#Override
protected void onPrepareDialogBuilder(Builder builder) {
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton(null, null);
iconName = getEntries();
iconFile = getEntryValues();
if (iconName == null || iconFile == null
|| iconName.length != iconFile.length) {
throw new IllegalStateException(
"ListPreference requires an entries array "
+ "and an entryValues array which are both the same length");
}
String selectedIcon = preferences.getString(
resources.getString(R.string.custom_icon_key),
resources.getString(R.string.icon_default));
icons = new ArrayList<IconItem>();
for (int i = 0; i < iconName.length; i++) {
boolean isSelected = selectedIcon.equals(iconFile[i]) ? true
: false;
IconItem item = new IconItem(iconName[i], iconFile[i], isSelected);
icons.add(item);
}
CustomListPreferenceAdapter customListPreferenceAdapter = new CustomListPreferenceAdapter(
context, R.layout.item_picker, icons);
builder.setAdapter(customListPreferenceAdapter, null);
}
private void updateIcon() {
int identifier = resources.getIdentifier(selectedIconFile, "drawable",
context.getPackageName());
icon.setImageResource(identifier);
icon.setTag(selectedIconFile);
}
String values
<string-array name="iconName">
<item>CHESTNUT</item>
<item>POMEGRANATE</item>
<item>OLD BRICK</item>
<item>FLAMINGO</item>
<item>SNUFF</item>
<item>RAZZMATAZZ</item>
<item>NEW YORK PINK</item>
</string-array>
<string-array name="iconFile">
<item>ic_chestnut</item>
<item>ic_pomegranate</item>
<item>ic_old_brick</item>
<item>ic_flamingo</item>
<item>ic_snuff</item>
<item>ic_razzmatazz</item>
<item>ic_new_york_pink</item>
</string-array>
7 ic_ pngs for the items above in drawable...
Logs not showing any index error...
Stumped :P
Any help appreciated
Thanks in advance
I think that the problem could be caused because you are saving the position in your ViewHolder, why do you do that?
Mark final the position field, and use it directly in your OnClickListener.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
...
#Override
public void onClick(View v) {
ViewHolder holder = (ViewHolder) v.getTag();
for (int i = 0; i < icons.size(); i++) {
if (i == position)
icons.get(i).isChecked = true;
else
icons.get(i).isChecked = false;
}
getDialog().dismiss();
}