How to implement admob ads in settings activity without xml - android

I want to place admob ad in my settings activity, since I am not using any xml for the settings activity I want to place the ad in the listview.
My settings activity looks as follows:
public class SettingsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider {
private ListView listView;
private ListAdapter listAdapter;
private BackupImageView avatarImage;
private TextView nameTextView;
private TextView onlineTextView;
private ImageView writeButton;
private AnimatorSetProxy writeButtonAnimation;
private AvatarUpdater avatarUpdater = new AvatarUpdater();
private View extraHeightView;
private View shadowView;
private int extraHeight;
private int overscrollRow;
private int emptyRow;
private int numberSectionRow;
private int numberRow;
private int usernameRow;
private int settingsSectionRow;
private int settingsSectionRow2;
private int enableAnimationsRow;
private int notificationRow;
private int backgroundRow;
private int languageRow;
private int privacyRow;
private int mediaDownloadSection;
private int mediaDownloadSection2;
private int mobileDownloadRow;
private int wifiDownloadRow;
private int roamingDownloadRow;
private int saveToGalleryRow;
private int messagesSectionRow;
private int messagesSectionRow2;
private int customTabsRow;
private int directShareRow;
private int textSizeRow;
private int stickersRow;
private int cacheRow;
private int raiseToSpeakRow;
private int sendByEnterRow;
//private int useSystemEmojiRow;
private int supportSectionRow;
private int supportSectionRow2;
// private int askQuestionRow;
//private int telegramFaqRow;
private int adsRow;
private int privacyPolicyRow;
private int sendLogsRow;
private int clearLogsRow;
private int switchBackendButtonRow;
private int versionRow;
private int contactsSectionRow;
private int contactsReimportRow;
private int contactsSortRow;
private int autoplayGifsRow;
private int rowCount;
private final static int edit_name = 1;
private final static int logout = 2;
private static class LinkMovementMethodMy extends LinkMovementMethod {
#Override
public boolean onTouchEvent(#NonNull TextView widget, #NonNull Spannable buffer, #NonNull MotionEvent event) {
try {
return super.onTouchEvent(widget, buffer, event);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return false;
}
}
#Override
public boolean onFragmentCreate() {
super.onFragmentCreate();
avatarUpdater.parentFragment = this;
avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() {
#Override
public void didUploadedPhoto(TLRPC.InputFile file, TLRPC.PhotoSize small, TLRPC.PhotoSize big) {
TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto();
req.caption = "";
req.crop = new TLRPC.TL_inputPhotoCropAuto();
req.file = file;
req.geo_point = new TLRPC.TL_inputGeoPointEmpty();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
#Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
if (user == null) {
return;
}
MessagesController.getInstance().putUser(user, false);
} else {
UserConfig.setCurrentUser(user);
}
TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response;
ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes;
TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);
TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);
user.photo = new TLRPC.TL_userProfilePhoto();
user.photo.photo_id = photo.photo.id;
if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
if (bigSize != null) {
user.photo.photo_big = bigSize.location;
} else if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
MessagesStorage.getInstance().clearUserPhotos(user.id);
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);
AndroidUtilities.runOnUIThread(new Runnable() {
#Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
UserConfig.saveConfig(true);
}
});
}
}
});
}
};
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
rowCount = 0;
overscrollRow = rowCount++;
emptyRow = rowCount++;
numberSectionRow = rowCount++;
numberRow = rowCount++;
usernameRow = rowCount++;
settingsSectionRow = rowCount++;
settingsSectionRow2 = rowCount++;
notificationRow = rowCount++;
privacyRow = rowCount++;
backgroundRow = rowCount++;
languageRow = rowCount++;
adsRow = rowCount++;
enableAnimationsRow = rowCount++;
mediaDownloadSection = rowCount++;
mediaDownloadSection2 = rowCount++;
mobileDownloadRow = rowCount++;
wifiDownloadRow = rowCount++;
roamingDownloadRow = rowCount++;
if (Build.VERSION.SDK_INT >= 11) {
autoplayGifsRow = rowCount++;
}
saveToGalleryRow = rowCount++;
messagesSectionRow = rowCount++;
messagesSectionRow2 = rowCount++;
customTabsRow = rowCount++;
if (Build.VERSION.SDK_INT >= 23) {
directShareRow = rowCount++;
}
textSizeRow = rowCount++;
stickersRow = rowCount++;
cacheRow = rowCount++;
raiseToSpeakRow = rowCount++;
sendByEnterRow = rowCount++;
// useSystemEmojiRow = rowCount++;
supportSectionRow = rowCount++;
supportSectionRow2 = rowCount++;
// askQuestionRow = rowCount++;
//telegramFaqRow = rowCount++;
privacyPolicyRow = rowCount++;
if (BuildVars.DEBUG_VERSION) {
sendLogsRow = rowCount++;
clearLogsRow = rowCount++;
switchBackendButtonRow = rowCount++;
}
versionRow = rowCount++;
//contactsSectionRow = rowCount++;
//contactsReimportRow = rowCount++;
//contactsSortRow = rowCount++;
MessagesController.getInstance().loadFullUser(UserConfig.getCurrentUser(), classGuid, true);
return true;
}
#Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
if (avatarImage != null) {
avatarImage.setImageDrawable(null);
}
MessagesController.getInstance().cancelLoadFullUser(UserConfig.getClientUserId());
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces);
avatarUpdater.clear();
}
#Override
public View createView(Context context) {
actionBar.setBackgroundColor(AvatarDrawable.getProfileBackColorForId(5));
actionBar.setItemsBackground(AvatarDrawable.getButtonColorForId(5));
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAddToContainer(false);
extraHeight = 88;
if (AndroidUtilities.isTablet()) {
actionBar.setOccupyStatusBar(false);
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
#Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == edit_name) {
presentFragment(new ChangeNameActivity());
} else if (id == logout) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MessagesController.getInstance().performLogout(true);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
}
}
});
ActionBarMenu menu = actionBar.createMenu();
ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName), 0);
item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut), 0);
listAdapter = new ListAdapter(context);
fragmentView = new FrameLayout(context) {
#Override
protected boolean drawChild(#NonNull Canvas canvas, #NonNull View child, long drawingTime) {
if (child == listView) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (parentLayout != null) {
int actionBarHeight = 0;
int childCount = getChildCount();
for (int a = 0; a < childCount; a++) {
View view = getChildAt(a);
if (view == child) {
continue;
}
if (view instanceof ActionBar && view.getVisibility() == VISIBLE) {
if (((ActionBar) view).getCastShadows()) {
actionBarHeight = view.getMeasuredHeight();
}
break;
}
}
parentLayout.drawHeaderShadow(canvas, actionBarHeight);
}
return result;
} else {
return super.drawChild(canvas, child, drawingTime);
}
}
};
FrameLayout frameLayout = (FrameLayout) fragmentView;
listView = new ListView(context);
listView.setDivider(null);
listView.setDividerHeight(0);
listView.setVerticalScrollBarEnabled(false);
AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5));
frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == textSizeRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize));
final NumberPicker numberPicker = new NumberPicker(getParentActivity());
numberPicker.setMinValue(12);
numberPicker.setMaxValue(30);
numberPicker.setValue(MessagesController.getInstance().fontSize);
builder.setView(numberPicker);
builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("fons_size", numberPicker.getValue());
MessagesController.getInstance().fontSize = numberPicker.getValue();
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
showDialog(builder.create());
} else if (i == enableAnimationsRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("view_animations", !animations);
editor.commit();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!animations);
}
} else if (i == notificationRow) {
presentFragment(new NotificationsSettingsActivity());
} else if (i == backgroundRow) {
presentFragment(new WallpapersActivity());
}
else if (i == adsRow) {
}
Hence I want to place the code under i== adsRow else if condition at the last.
How can I do the same?

You will be creating a banner AdView object programmatically, and stitch it to your ListView:
// Create a banner ad. The ad size and ad unit ID must be set before calling loadAd.
AdView mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId("myAdUnitId");
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
// Add the AdView to the view hierarchy.
layout.addView(mAdView);
// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());

Related

How to set some item unclickable in GridView

For example, I need to judge the contents of the item in the Item can be clicked.
enter image description here
As shown in the picture, I need to get the gray Item cannot be clicked.
Here is my adapter
public class RoomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context mContext;
private List<Room> mDatas;
public RoomAdapter(Context context, List<Room> mDatas) {
mInflater = LayoutInflater.from(context);
this.mContext = context;
this.mDatas = mDatas;
}
#Override
public int getCount() {
return mDatas.size();
}
#Override
public Object getItem(int position) {
return mDatas.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Room room = mDatas.get(position);
ViewHolder viewHolder = null;
View view;
if (convertView == null) {
viewHolder = new ViewHolder();
view = mInflater.inflate(R.layout.roomstate_item, null);
viewHolder.tv_roomstate = (TextView) view.findViewById(R.id.tv_roomstate);
viewHolder.tv_roomnumber = (TextView) view.findViewById(R.id.tv_roomnumber);
viewHolder.tv_roomtype = (TextView) view.findViewById(R.id.tv_roomtype);
viewHolder.tv_roomprice = (TextView) view.findViewById(R.id.tv_roomprice);
view.setTag(viewHolder);
}else{
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
// String nu = room.getRoom_number();
viewHolder.tv_roomstate.setText(room.getRoom_status());
viewHolder.tv_roomnumber.setText(room.getRoom_number());
viewHolder.tv_roomtype.setText(room.getRoomType().getRoom_type_name());
viewHolder.tv_roomprice.setText(room.getRoomType().getRoom_type_price());
if (room.getRoom_status().equals("0") &&room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single);
view.setClickable(false);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single_b);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("1")) {
view.setBackgroundResource(R.drawable.double_b);
} else if(room.getRoom_status().equals("0") && room.getRoomType().getRoom_type_name().equals("1")){
view.setClickable(false);
view.setBackgroundResource(R.drawable.doubleg);
}
return view;
}
private class ViewHolder {
TextView tv_roomnumber;
TextView tv_roomstate;
TextView tv_roomtype;
TextView tv_roomprice;
}
}
Here is my Activity
public class RoomList extends Activity {
private ImageView iv_back;
private TextView tv_hotelname;
private GridView griv_hotel;
private RoomAdapter adapter;
private String hotelname;
private String url
= "http://jm/user/room/selectRoomByHotelName?hotel_name=";
private List<Room> mRoom;
private RoomType mRoomType;
private boolean isfinish = false;//判断请求是否完成
private String hotel_address;
private String hotel_id;
private Bundle mBundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_room_list);
init();
sendRequestWithOkHttp();
boolean is = true;
while (is) {
if (isfinish) {
adapter = new RoomAdapter(this, mRoom);
griv_hotel.setAdapter(adapter);
griv_hotel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv_roomnumber = (TextView) view.findViewById(R.id.tv_roomnumber);
TextView tv_roomstate = (TextView) view.findViewById(R.id.tv_roomstate);
TextView tv_roomprice = (TextView) view.findViewById(R.id.tv_roomprice);
TextView tv_roomtype = (TextView) view.findViewById(R.id.tv_roomtype);
String roomnumber = tv_roomnumber.getText().toString();
String roomstate = tv_roomstate.getText().toString();
String roomtype = tv_roomtype.getText().toString();
String roomprice = tv_roomprice.getText().toString();
Log.e("房间类型",roomtype);
// if (roomstate.equals("0") && roomtype.equals("0")) {
// view.setClickable(false);
// } else if (roomstate.equals("1") && roomtype.equals("0")) {
// view.setClickable(true);
// } else if (roomstate.equals("1") && roomtype.equals("1")) {
// view.setClickable(true);
// } else {
// view.setClickable(false);
// }
mBundle.putString("roomnumber", roomnumber);
mBundle.putString("roomstate", roomstate);
mBundle.putString("roomtype", roomtype);
mBundle.putString("roomprice", roomprice);
mBundle.putString("hoteladdress", hotel_address);
mBundle.putString("hotelid", hotel_id);
Intent intent = new Intent(RoomList.this, BookRoomDetail.class);
intent.putExtras(mBundle);
startActivity(intent);
}
});
is = false;
}
}
}
private void init() {
initView();
initEvents();
}
private void initEvents() {
iv_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void initView() {
iv_back = (ImageView) findViewById(R.id.iv_back);
tv_hotelname = (TextView) findViewById(R.id.tv_hotelname);
mBundle = getIntent().getExtras();
hotelname = mBundle.getString("hotelname");
tv_hotelname.setText(hotelname);
griv_hotel = (GridView) findViewById(R.id.griv_hotel);
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
#Override
public void run() {
MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
try {
OkHttpClient client = new OkHttpClient();
String postBody = hotelname;
Request request = new Request.Builder()
.url(url + hotelname)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
try {
parseJSON(responseData);
isfinish = true;
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSON(String responseData) throws JSONException {
JSONArray JSONArray = new JSONArray(responseData);
mRoom = new ArrayList<Room>();
for (int i = 0; i < JSONArray.length(); i++) {
try {
JSONObject JSON = JSONArray.getJSONObject(i);
String room_number = JSON.getString("room_number");
String room_status = JSON.getString("room_status");
JSONObject jsonObject = JSON.getJSONObject("roomType");
String room_type_name = jsonObject.getString("room_type_name");
String room_type_price = jsonObject.getString("room_type_price");
JSONObject jsonObj = JSON.getJSONObject("hotel");
hotel_id = String.valueOf(jsonObj.getInt("hotel_id"));
hotel_address = jsonObj.getString("hotel_location");
mRoomType = new RoomType(null, room_type_name, room_type_price, null, null);
mRoom.add(new Room(null, room_number, room_status, null, null, mRoomType));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I set view.setClickable (false)in my Adapter, but it does not work.
item.setEnabled(false);
when u need to make it clickable call
item.setEnabled(true);
Here item is your edittext or button or anything else
Try this:
if (room.getRoom_status().equals("0") &&room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single);
view.setEnabled(false);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single_b);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("1")) {
view.setBackgroundResource(R.drawable.double_b);
} else if(room.getRoom_status().equals("0") && room.getRoomType().getRoom_type_name().equals("1")){
view.setEnabled(false);
view.setBackgroundResource(R.drawable.doubleg);
}
else
view.setEnabled(true);
The right way is to write a Boolean value, and let it based on a Boolean value to determine whether to jump.
private boolean checkedIntent = false;
if (roomstate.equals("0") && roomtype.equals("0")) {
checkedIntent = false;
} else if (roomstate.equals("1") && roomtype.equals("0")) {
checkedIntent = true;
} else if (roomstate.equals("1") && roomtype.equals("1")) {
checkedIntent = true;
} else if (roomstate.equals("0") && roomtype.equals("1")) {
checkedIntent = false;
}
if (checkedIntent == true) {
Intent intent = new Intent(RoomList.this, BookRoomDetail.class);
intent.putExtras(mBundle);
startActivity(intent);
}

Android - Creating Listview using Custom Adapter Programmatically

I'm in learning about add view programmatically. But, I'm in confusing now.
I have data, there are idpatient, idheader. Patient can have more than one ID header. When I input idpatient, it will add listview (with custom adapter) programmatically. The number of listview is same with the number of ID header.
I want to set in each listview with data patient group by ID header..
So far, I add search view when loop adding listview, but when I input one ID header to seacrh view, all of listview will view the same data according to ID header in search view..
I'm sorry for the long explanation. Can anybody help me to solve this problem?
Thanks in advance
This is My Adapter :
/**
* Created by RKI on 11/9/2016.
*/
public class AdapterHistory extends BaseAdapter implements Filterable, View.OnClickListener {
private Activity activity;
LayoutInflater inflater;
HistoryHeaderActivity main;
public int count = 0;
Context context;
public ModelHistory product;
ArrayList<ModelHistory> mStringFilterList;
ModelHistory tempValues = null;
ValueFilter valueFilter;
public Cart cart;
public AdapterHistory(HistoryHeaderActivity main, ArrayList<ModelHistory> arraylist) {
this.main = main;
this.main.historyModel = arraylist;
mStringFilterList = arraylist;
}
#Override
public int getCount() {
return main.historyModel.size();
}
#Override
public Object getItem(int position) {
return main.historyModel.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
int pos = position;
final Cart carts = CartHelper.getCart();
View vi = convertView;
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_history, null);
holder.h_id = (TextView) vi.findViewById(R.id.id_header_);
holder.h_type = (TextView) vi.findViewById(R.id.servicetype_);
holder.h_qty = (TextView) vi.findViewById(R.id.qty_);
holder.h_ps_id = (TextView) vi.findViewById(R.id.patient_id);
holder.h_ps_name = (TextView) vi.findViewById(R.id.patient_);
holder.h_dokid = (TextView) vi.findViewById(R.id.doctor_id_);
holder.h_dokname = (TextView) vi.findViewById(R.id.doctor_);
holder.h_item = (TextView) vi.findViewById(R.id.item_);
holder.h_date = (TextView) vi.findViewById(R.id.date_);
holder.checkToCart = (CheckBox) vi.findViewById(R.id.checkBox);
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
tempValues.setSelected(isChecked);
}
});
vi.setTag(holder);
vi.setTag(R.id.checkBox, holder.checkToCart);
} else {
holder = (ViewHolderItem) vi.getTag();
}
if (main.historyModel.size() <= 0) {
holder.h_date.setText("No Data");
} else {
/*** Get each Model object from Arraylist ****/
tempValues = null;
tempValues = (ModelHistory) main.historyModel.get(position);
holder.h_id.setText(tempValues.getH_id());
holder.h_type.setText(tempValues.getH_service());
holder.h_qty.setText(tempValues.getH_qty());
holder.h_ps_name.setText(tempValues.getH_p_name());
holder.h_ps_id.setText(tempValues.getH_p_id());
holder.h_dokid.setText(tempValues.getH_d_id());
holder.h_dokname.setText(tempValues.getH_d_name());
holder.h_item.setText(tempValues.getH_item());
holder.h_date.setText(tempValues.getH_date());
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
main.historyModel.get(position).setSelected(buttonView.isChecked());
}
});
holder.checkToCart.setChecked(main.historyModel.get(position).isSelected());
for (pos = 1; pos <= 1; pos++) {
main.u_pname = tempValues.getH_p_name();
main.u_pid = tempValues.getH_p_id();
main.u_service = tempValues.getH_service();
main.up_iddetail = tempValues.getH_id();
}
}
return vi;
}
#Override
public void onClick(View v) {
}
public static class ViewHolderItem {
TextView h_id, h_type, h_ps_id, h_ps_name, h_dokid, h_dokname, h_item, h_qty, h_date;
CheckBox checkToCart;
}
private List<TransactionsItem> getCartItems(Cart cart) {
List<TransactionsItem> cartItems = new ArrayList<>();
Map<Saleable, Integer> itemMap = cart.getItemWithQuantity();
for (Map.Entry<Saleable, Integer> entry : itemMap.entrySet()) {
TransactionsItem cartItem = new TransactionsItem();
cartItem.setProduct((ModelInventory) entry.getKey());
cartItem.setQuantity(entry.getValue());
cartItems.add(cartItem);
}
return cartItems;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<ModelHistory> filterList = new ArrayList<ModelHistory>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getH_id().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ModelHistory country = new ModelHistory(
mStringFilterList.get(i).getH_id(),
mStringFilterList.get(i).getH_p_id(),
mStringFilterList.get(i).getH_date(),
mStringFilterList.get(i).getH_p_name(),
mStringFilterList.get(i).getH_d_id(),
mStringFilterList.get(i).getH_d_name(),
mStringFilterList.get(i).getH_item(),
mStringFilterList.get(i).getH_qty(),
mStringFilterList.get(i).getH_service());
filterList.add(country);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
main.historyModel = (ArrayList<ModelHistory>) results.values;
notifyDataSetChanged();
}
}
}
This is My Activity :
import com.mobileproject.rki.mobile_his_receipt.view.adapter.AdapterHistory;
import org.w3c.dom.*;
import java.io.Serializable;
import java.util.*;
public class HistoryHeaderActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
static final String URL = "http://.../GetDataInv";
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_REG_ID = "Sales_Aptk_ID", KEY_DATE = "Sales_Aptk_Date",
KEY_PATIENT_ID = "Sales_Aptk_Patient_ID", KEY_SERVICE_ID = "Sales_Aptk_Type",
KEY_PATIENT_NAME = "Sales_Aptk_Patient_Name",
KEY_DOCTOR_ID = "Sales_Aptk_Doctor_ID", KEY_DOCTOR_NAME = "Sales_Aptk_Doctor_Name",
KEY_ITEM_ID = "Sales_Aptk_Detail_Item_ID", KEY_DETAIL_UNIT = "Sales_Aptk_Detail_Unit",
KEY_ITEM_QTY = "Sales_Aptk_Detail_Qty";
static final String KEY_ID_HEADER = "Sales_Aptk_ID";
static final String KEY_TABLE_INV = "Table"; // parent node
static final String KEY_ITEM_ID_INV = "Item_ID", KEY_ITEM_NAME = "Item_Name",
KEY_MAX_STOCK = "Item_Max_Stock";
public static final int DIALOG_DOWNLOAD_DATA_PROGRESS = 0, DIALOG_NO_DATA = 1,
DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS = 2;
Element e;
final Context context = this;
public List<ModelInventory> invModels;
private ProgressDialog mProgressDialog;
public static String id, up_iddetail, up_user, u_pid, u_pname, u_service, xml;
public ArrayList<ModelInventory> invModel = new ArrayList<ModelInventory>();
public ArrayList<ModelHistory> historyModel = new ArrayList<ModelHistory>();
public ArrayList<ModelIDHeader> headerModel = new ArrayList<ModelIDHeader>();
public Cart cart;
private Menu menu;
AdapterHistory hstAdpt, idhstAdpt;
private ProgressDialog progressDialog;
public ModelInventory productInv;
int mPosition, invPosition;
EditText p_id;
ListView listHistory;
XMLParser parser;
LinearLayout lm;
LinearLayout.LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_header);
lm = (LinearLayout) findViewById(R.id.linearMain);
params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
p_id = (EditText) findViewById(R.id.patientID);
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mPosition = position;
invPosition = position;
}
});
SharedPreferences login2 = getSharedPreferences("USERLOGIN", 0);
String doktername = login2.getString("userlogin", "0");
up_user = doktername;
p_id.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
onGetHistory();
}
});
}
/**
* Check Form Input
*
* #return
*/
private boolean isFormValid() {
String aTemp = p_id.getText().toString();
if (aTemp.isEmpty()) {
Toast.makeText(this, "Please Input Patient ID..", Toast.LENGTH_SHORT).show();
return false;
} else {
id = aTemp.toString();
}
return true;
}
protected void dismissDialogWait() {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
public void onGetHistory() {
listHistory.setAdapter(null);
if (isFormValid()) {
GetDataHistoryTask syncTask = new GetDataHistoryTask();
syncTask.execute(new IntroductingMethod());
GetDataHeaderTask syncTaskHeader = new GetDataHeaderTask();
syncTaskHeader.execute(new IntroductingMethod());
}
}
private class GetDataHistoryTask extends AsyncTask<IntroductingMethod, String, String> {
#Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryData(id);
}
#Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelHistory add = new ModelHistory();
add.setH_id(parser.getValue(e, KEY_REG_ID));
add.setH_p_name(parser.getValue(e, KEY_PATIENT_NAME));
add.setH_p_id(parser.getValue(e, KEY_PATIENT_ID));
add.setH_service(parser.getValue(e, KEY_SERVICE_ID));
add.setH_date(parser.getValue(e, KEY_DATE));
add.setH_detail_unit(parser.getValue(e, KEY_DETAIL_UNIT));
add.setH_d_id(parser.getValue(e, KEY_DOCTOR_ID));
add.setH_d_name(parser.getValue(e, KEY_DOCTOR_NAME));
add.setH_item(parser.getValue(e, KEY_ITEM_ID));
add.setH_qty(parser.getValue(e, KEY_ITEM_QTY));
historyModel.add(add);
}
ShowAllContentHistory();
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
private class GetDataHeaderTask extends AsyncTask<IntroductingMethod, String, String> {
#Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryHeaderData(id);
}
#Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelIDHeader add = new ModelIDHeader();
add.setIdSalesHeader(parser.getValue(e, KEY_ID_HEADER));
headerModel.add(add);
}
if(result.contains("<Sales_Aptk_Patient_ID>"+id+"</Sales_Aptk_Patient_ID>")){
Log.d("NilaiID ", id);
AddNewList();
}
else{
Log.d("Kenapayahh", id);
}
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
public void AskUpdate(View v) {
if (hstAdpt.getCount() == 0) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Tidak ada rekaman pasien.", Toast.LENGTH_LONG).show();
} else {
SharedPreferences id_header = getSharedPreferences("IDSALESAPTK", 0);
SharedPreferences.Editor editorID = id_header.edit();
editorID.putString("idsalesaptk", up_iddetail);
editorID.commit();
SharedPreferences sendPref2 = getSharedPreferences("DATAPATIENTNAME", 0);
SharedPreferences.Editor editor2 = sendPref2.edit();
editor2.putString("datapatientname", u_pname);
editor2.commit();
editor2.clear();
SharedPreferences sendPref3 = getSharedPreferences("DATAPATIENTID", 0);
SharedPreferences.Editor editor3 = sendPref3.edit();
editor3.putString("datapatientid", u_pid);
editor3.commit();
editor3.clear();
SharedPreferences regID = getSharedPreferences("DATAREGID", 0);
String reg_ID = regID.getString("dataregid", "0");
SharedPreferences sendPref4 = getSharedPreferences("DATAREGID", 0);
SharedPreferences.Editor editor4 = sendPref4.edit();
editor4.putString("dataregid", reg_ID);
editor4.commit();
editor4.clear();
SharedPreferences sendPref1 = getSharedPreferences("DATASERVICE", 0);
SharedPreferences.Editor editor1 = sendPref1.edit();
editor1.putString("dataservice", u_service);
editor1.commit();
editor1.clear();
new LoadingDataAsync().execute();
}
}
public class LoadingDataAsync extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
updateDetail();
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
}
public void updateDetail() {
ArrayList<ModelHistory> candidateModelArrayList = new ArrayList<ModelHistory>();
for (ModelHistory model : historyModel) {
if (model.isSelected()) {
candidateModelArrayList.add(model);
}
}
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_TABLE_INV);
for (int i = 0; i < nl.getLength(); i++) {
e = (Element) nl.item(i);
ModelInventory add = new ModelInventory();
add.setItem_ID(parser.getValue(e, KEY_ITEM_ID_INV));
add.setItem_Name(parser.getValue(e, KEY_ITEM_NAME));
add.setItem_Max_Stock(parser.getValue(e, KEY_MAX_STOCK));
invModel.add(add);
}
invModels = new ArrayList<ModelInventory>();
invModels = invModel;
ArrayAdapter<ModelInventory> adptInv = new ArrayAdapter<ModelInventory>(context, android.R.layout.simple_spinner_dropdown_item, invModels);
ArrayAdapter<ModelHistory> adptChkItem = new ArrayAdapter<ModelHistory>(context, android.R.layout.simple_spinner_dropdown_item, candidateModelArrayList);
if (adptInv.isEmpty()) {
Toast.makeText(HistoryHeaderActivity.this, "Empty Patient", Toast.LENGTH_SHORT).show();
}
cart = CartHelper.getCart();
for (mPosition = 0; mPosition < adptChkItem.getCount(); mPosition++) {
ModelHistory historyItem = (ModelHistory) adptChkItem.getItem(mPosition);
for (int j = mPosition; j < adptInv.getCount(); j++) {
ModelInventory inventoryItem = (ModelInventory) adptInv.getItem(j);
if (candidateModelArrayList.get(mPosition).getH_item().equals(inventoryItem.getItem_ID())) {
if (cart.getProducts().toString().contains(inventoryItem.getItem_Name())) {
} else {
productInv = (ModelInventory) (Serializable) adptInv.getItem(j);
int qty = Integer.parseInt(historyItem.getH_qty());
cart.add(productInv, qty);
}
} else {
}
}
}
Intent i = new Intent(getBaseContext(), CartActivity.class);
i.putExtra("PersonID", "try");
startActivity(i);
}
#Override
protected Dialog onCreateDialog(int id) {
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
hstAdpt.getFilter().filter(newText);
idhstAdpt.getFilter().filter(newText);
return false;
}
public void AddNewList(){
ArrayAdapter<ModelIDHeader> adptIDHeader = new ArrayAdapter<ModelIDHeader>(context, android.R.layout.simple_spinner_dropdown_item, headerModel);
for(int count =0; count< adptIDHeader.getCount(); count++){
idhstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
ModelIDHeader idHeader = (ModelIDHeader) adptIDHeader.getItem(count);
Button btn = new Button(this);
btn.setId(count);
btn.setText(idHeader.getIdSalesHeader());
lm.addView(btn);
SearchView search = new SearchView(this);
search.setQuery(idHeader.getIdSalesHeader(), false);
search.setOnQueryTextListener(this);
lm.addView(search);
ListView tv = new ListView(this);
tv.setId(count);
tv.setLayoutParams(params);
tv.setDividerHeight(2);
tv.setAdapter(idhstAdpt);
lm.addView(tv);
}
}
public void ShowAllContentHistory() {
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_history_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ClearPrefs();
logout();
Intent intent = new Intent(HistoryHeaderActivity.this, LoginActivity.class);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
}
if (id == R.id.action_home) {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
}
public void ClearPrefs() {
}
public void logout() {
SharedPreferences preferences5 = getSharedPreferences("IDLOGIN", Context.MODE_PRIVATE);
SharedPreferences.Editor editor5 = preferences5.edit();
editor5.clear();
editor5.commit();
}
}

how do I add search capability to my list view?

I am planning to add search to my contacts lists I am working on. I added the searchview textchanged listener, how do I go about this so I can get my search working based on letter of each item in my listview? as in what am i missing?
enum LvType {
HEADER_GROUP,
HEADER_UNGROUPED,
HEADER_twoway_CHAT,
HEADER_MANAGED_CHATROOM,
ITEM_CHATROOM,
ITEM_twoway_CHAT,
ITEM_USER,
}
class ListItemsHolder {
private ArrayList<String> lvJids;
private ArrayList<String> lvNames;
private ArrayList<Presence> lvPresences;
private ArrayList<LvType> lvTypes;
public ListItemsHolder() {
}
public void init() {
lvTypes = new ArrayList<LvType>();
lvJids = new ArrayList<String>();
lvNames = new ArrayList<String>();
lvPresences = new ArrayList<Presence>();
}
public int setInfo(String jid, String name, LvType type, Presence presence) {
lvJids.add(jid);
lvNames.add(name);
lvTypes.add(type);
lvPresences.add(presence);
return lvJids.size();
}
public String getJid (int pos) { return ((lvJids == null) ? null : lvJids.get(pos) ); }
public String getName (int pos) { return ((lvNames == null) ? null : lvNames.get(pos) ); }
public LvType getType (int pos) { return ((lvTypes == null) ? null : lvTypes.get(pos) ); }
public Presence getPresence (int pos) { return ((lvPresences == null) ? null : lvPresences.get(pos)); }
public int getSize() { return (lvJids == null) ? 0 : lvJids.size(); }
}
public class ContactFragment extends RMBaseFragment<MethodsForContactFragment> implements OnItemClickListener, OnItemLongClickListener, ContactInterface,FragmentDrawer.FragmentDrawerListener
, OnClickListener, OnMenuItemClickedListener, Dialog.OnDismissListener,SearchView.OnQueryTextListener,
MainActivity.BackPressListener<android.support.v4.app.Fragment>
{
public final static String TAG_Contact_FRAGMENT = "TAG_Contact_FRAGMENT";
private static final String MY_PRESENCE_DIALOG_FRAGMENT = "MyPresenceDialogFragment";
private RecyclerView m_recycler;
public static ContactFragment newInstance(final FragmentManager manager) {
final ContactFragment fragment = new ContactFragment();
final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD);
fragmentInfo.setFragmentTag(TAG_Contact_FRAGMENT);
fragmentInfo.setActionBarTitle("contact list");
fragmentInfo.setAnimation(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
fragmentInfo.setPopAnimation(R.anim.slide_in_from_left, R.anim.no_animation2);
FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
class ViewHolder {
public TextView text;
public ImageView image;
}
private int numOfConferences = 0;
private int numOfLegacyChats = 0;
private int numOfGroups = 0;
private int numOfUnfiled = 0;
private Vector<BookmarkedConference> mConferences = null;
private Vector<BookmarkedConference> mLegacyChats = null;
private String[] ContactGroupsNames = null;
private TreeMap<String, ContactGroup> treeMapOfContactGroups = null;
//return new TreeMap<String, ContactGroup>(groups).keySet().toArray(new String[0]);
private DrawerLayout mDrawerLayout;
EditText inputSearch;
private int numOfBookmarks = 0;
private Vector mBoomarks = null;
private ListItemsHolder listItemsHolder = new ListItemsHolder();
private static final String twowayChatsHeader = "twoway Chats";
private static final String managedChatroomsHeader = "Managed Chatrooms";
private static final String ungroupedContactsHeader= "Ungrouped Contacts";
private MenuHelper mMenuHelper;
private final ArrayList<String> mMenuItems = new ArrayList<String>();
private ImageView mContextMenuButton;
private ImageView mMyPresenceButton;
private FontTextView mMyPresenceTextView;
private ImageView mContactAccountButton;
private static class MenuItems{
final static String PRESENCE = Application.getAppResources().getString(R.string.rm_news_menu_presence);
final static String LOGOUT = Application.getAppResources().getString(R.string.rm_news_menu_logout);
static final int PRESENCE_POSITION = 0;
static final int LOGOUT_POSITION = 1;
}
private void createMenu() {
mMenuItems.add(MenuItems.PRESENCE);
mMenuItems.add(MenuItems.LOGOUT);
mMenuHelper = new MenuHelper(getActivity(),mMenuItems,this,this);
}
public class MySimpleArrayAdapter extends BaseAdapter {
private final Activity context;
private ItemFilter mFilter;
public MySimpleArrayAdapter(Activity context) {
this.context = context;
prepareDataForListView();
}
private int total;
private void sortDataDefault(wrapper dw) {
if (dw == null)
return;
Contact Contact = dw.getContact();
Hashtable ht;
Vector<ContactEntry> entries;
if (Contact != null && ((ht = Contact.getGroupsEx()) != null) ) {
numOfGroups = Contact.getGroupCount();
treeMapOfContactGroups = new TreeMap<String, ContactGroup>(ht);
ContactGroupsNames = treeMapOfContactGroups.keySet().toArray(new String[0]);
for (int ii = 0; ii < numOfGroups; ii++) {
listItemsHolder.setInfo(ContactGroupsNames[ii], ContactGroupsNames[ii], LvType.HEADER_GROUP, null);
ContactGroup group = Contact.getGroup(ContactGroupsNames[ii]);
entries = group.getEntriesEx();
Collections.sort(entries, comparatorContactEntryAlpha);
Iterator<ContactEntry> it = entries.iterator();
ContactEntry tmpEntry;
while(it.hasNext()) {
tmpEntry = it.next();
listItemsHolder.setInfo(tmpEntry.getUser(), tmpEntry.getName(), LvType.ITEM_USER, Contact.getPresence(tmpEntry.getUser()));
}
}
}
entries = Contact.getUnfiledEntriesEx();
if (entries != null) {
listItemsHolder.setInfo(ungroupedContactsHeader, ungroupedContactsHeader, LvType.HEADER_GROUP, null);
Collections.sort(entries, comparatorContactEntryAlpha);
Iterator<ContactEntry> it = entries.iterator();
ContactEntry tmpEntry;
while(it.hasNext()) {
tmpEntry = it.next();
listItemsHolder.setInfo(tmpEntry.getUser(), tmpEntry.getName(), LvType.ITEM_USER, Contact.getPresence(tmpEntry.getUser()));
}
}
mConferences = dw.getConferences();
if (mConferences != null && mConferences.size() > 0) {
listItemsHolder.setInfo(twowayChatsHeader, twowayChatsHeader, LvType.HEADER_twoway_CHAT, null);
Collections.sort(mConferences, comparatorBookMarksAlpha);
Iterator<BookmarkedConference> it = mConferences.iterator();
BookmarkedConference bk;
while(it.hasNext()) {
bk = it.next();
listItemsHolder.setInfo(bk.getRoomId(), bk.getName(), LvType.ITEM_twoway_CHAT, null);
}
}
mLegacyChats = dw.getLegacyChats(); // mUNitroChatManager.getConferenceBookmarksAsVector(Bookmarks.Type.LEGACY_ROOM);
if (mLegacyChats != null && mLegacyChats.size() > 0) {
listItemsHolder.setInfo(managedChatroomsHeader, managedChatroomsHeader, LvType.HEADER_MANAGED_CHATROOM, null);
Collections.sort(mLegacyChats, comparatorBookMarksAlpha);
Iterator<BookmarkedConference> it = mLegacyChats.iterator();
BookmarkedConference bk;
while(it.hasNext()) {
bk = it.next();
listItemsHolder.setInfo(bk.getRoomId(), bk.getName(), LvType.ITEM_CHATROOM, null);
}
}
}
private void prepareDataForListView() {
numOfConferences = numOfLegacyChats = 0;
mConferences = null;
mLegacyChats = null;
listItemsHolder.init();
try {
sortDataDefault(controller.getContactModel());
}
catch (Exception ex) {
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.my_poc_rowlayout, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) rowView.findViewById(R.id.label);
viewHolder.image = (ImageView) rowView.findViewById(R.id.icon);
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
String jid = listItemsHolder.getJid(position);
String name = listItemsHolder.getName(position);
holder.image.setVisibility(View.VISIBLE);
switch (listItemsHolder.getType(position)) {
case ITEM_USER:
Status status = MessengerUtils.presence2Status(listItemsHolder.getPresence(position));
if (status == Status.AVAILABLE)
holder.image.setImageResource(R.drawable.online);
else if (status == Status.BUSY)
holder.image.setImageResource(R.drawable.busy);
else if (status == Status.AWAY)
holder.image.setImageResource(R.drawable.away);
else
holder.image.setImageResource(R.drawable.offline);
break;
case ITEM_twoway_CHAT:
holder.image.setImageResource(R.drawable.twoway_chat);
break;
case ITEM_CHATROOM:
holder.image.setImageResource(R.drawable.chatroom);
break;
case HEADER_GROUP: // fall thru
case HEADER_twoway_CHAT: // keep falling
case HEADER_MANAGED_CHATROOM:
holder.image.setVisibility(View.GONE);
break;
default:
//TODO Throw some nasty exception
break;
}
if (name != null && name.length() > 1){
holder.text.setText(name);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) holder.text.getLayoutParams();
params.leftMargin = 20;
}else
holder.text.setText(jid);
return rowView;
}
public String firstUpper(String text) {
return (text.substring(0,1).toUpperCase() + text.substring(1).toLowerCase());
}
#Override
public int getCount() {
if (listItemsHolder == null)
return 0;
return listItemsHolder.getSize();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return null; // don't really need it
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Set up search view
inflater.inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.search_messenger);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public void onItemClick(final AdapterView<?> parent, final View arg1, final int position, final long id) {
if (listItemsHolder == null) // paranoia
return;
String jid = listItemsHolder.getJid(position);
String name = listItemsHolder.getName(position);
LvType type = listItemsHolder.getType(position);
if (type == LvType.ITEM_USER) {
controller.openChat(jid, name);
mDrawerLayout.closeDrawer(Gravity.RIGHT);
}
}
private ListView listView_Contact;
private TextView empty_tv;
private MySimpleArrayAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.poc_Contact_fragment, container, false);
mDrawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout_messenger);
m_recycler = (RecyclerView)view.findViewById(R.id.recyclerConversations);
m_recycler.setHasFixedSize(true);
m_recycler.setLayoutManager(new LinearLayoutManager(this.getActivity()));
m_recycler.setAdapter(m_recyclerAdapter);
listView_Contact = (ListView)view.findViewById(R.id.listView_Contact);
empty_tv = (TextView)view.findViewById(R.id.empty_tv);
inputSearch = (EditText) view.findViewById(R.id.search_text_messenger);
mAdapter = new MySimpleArrayAdapter(getActivity());
listView_Contact.setAdapter(mAdapter);
listView_Contact.setTextFilterEnabled(true);
listView_Contact.setOnItemClickListener(this);
listView_Contact.setOnItemLongClickListener(this);
//headerView = (HeaderView) view.findViewById(R.id.news_categories_container);
mContextMenuButton = (ImageView) view.findViewById(R.id.context_menu_button);
mContextMenuButton.setOnClickListener(this);
mMyPresenceButton = (ImageView) view.findViewById(R.id.my_presence_button);
mMyPresenceButton.setOnClickListener(this);
mMyPresenceTextView = (FontTextView) view.findViewById(R.id.my_presence_textview);
mMyPresenceTextView.setOnClickListener(this);
setMyPresenceStatus();
mContactAccountButton = (ImageView) view.findViewById(R.id.Contact_contact_button);
mContactAccountButton.setOnClickListener(this);
createMenu();
return view;
}
public void chatMessageReceived(BaseNitroChat chat) {
String from = chat.getName();
String says = chat.getLastMessage().getBody();
Toast.makeText(getActivity(), "" + from + " says " + says, Toast.LENGTH_SHORT).show();
}
#Override
public void ContactModelUpdated() {
if (mAdapter == null)
return;
mAdapter.prepareDataForListView();
mAdapter.notifyDataSetChanged();
m_recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
mAdapter.getFilter().filter(s);
return false;
}
}

setOnScrollListener of ListView interrupts setOnItemClickListener

It took me two(!) days to figure out my problem.
I have ListView with both onItemClickListener and onScrollListner. If I implement the onScrollListner then no ItemClick actions are fired.
I saw this problem here: setOnScrollListener with setOnItemClickListener and here:Android: cannot set both: setOnItemClickListener setOnScrollListener? with no real solution.
I have also noticed (in the emulator) that when one of the rows (in the ListView) is selected then ItemClick does fire (I assume that it works in not touch mode).
Very frustrating, can anyone think of a solution?
Some code:
Custom ListView
public class CustomHomeListView extends ListView implements android.widget.AdapterView.OnItemClickListener, OnScrollListener, IReceiver {
public static final String TAG = CustomHomeListView.class.getSimpleName();
private static Context mContext;
List<DiscussionModel> mDiscussionsArray = new ArrayList<DiscussionModel>();
private DiscussionsCustomAdapter mAdapter;
private boolean mIsLoading;
private int mCurrentMinDiscussionRowIndex;
private View mFooterView;
private int mFirstVisiblePosition;
private int mSelectedItemPosition;
private int mDividerHeight;
private int mSavedPositionInsideListView;
public MyResultReceiver mReceiver;
public void onCreate() {
// for computing scroll position to an item after data fetch
mDividerHeight = getDividerHeight();
mSavedPositionInsideListView = 0;
// prepare ResultReceiver for informing that puller service is done
mReceiver = new MyResultReceiver(new Handler());
mReceiver.setReceiver(this);
mCurrentMinDiscussionRowIndex = -1; // default value for retrieving most
// recent
// posts from web
mAdapter = new DiscussionsCustomAdapter(mContext);
CrowdietApplication cda = (CrowdietApplication) mContext.getApplicationContext();
mAdapter.setCurrentUserUid(cda.getUserId());
setAdapter(mAdapter);
setOnScrollListener(this);
setOnItemClickListener(this);
mFooterView = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.home_list_view_footer, null);
//setCustomHomeListViewOnScrollListener();
pullDiscussions();
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DiscussionModel discussion = mDiscussionsArray.get(position);
Intent intent = new Intent(mContext, DiscussionActivity.class);
intent.putExtra(CONSTS_DISCUSSIONS.DISCUSSION_ID_FROM_CALLING_ACTIVITY, discussion.getDiscussionId());
mContext.startActivity(intent);
}
public void refresh() {
mCurrentMinDiscussionRowIndex = -1;
pullDiscussions();
}
private void pullDiscussions() {
mIsLoading = true;
// preparing puller service
Intent intent = new Intent(mContext, PullDiscussionsListIntentService.class);
intent.putExtra(CONSTS_APP_SIGNALS.MIN_DISCUSSION_ROW_INDEX_TO_FETCH, mCurrentMinDiscussionRowIndex);
intent.putExtra(CONSTS_APP_SIGNALS.RECEIVER_TAG, mReceiver);
mContext.startService(intent);
}
private void refreshListFromDatabase() {
DbDiscussions dbDiscussions = new DbDiscussions(mContext);
Cursor discussionsCursor;
discussionsCursor = dbDiscussions.getDiscussions();
if (discussionsCursor != null && discussionsCursor.getCount() > 0) {
prepareDiscussionsArray(discussionsCursor);
mCurrentMinDiscussionRowIndex = dbDiscussions.getMinDiscussionRowIndex();
mAdapter.setData(mDiscussionsArray);
mAdapter.notifyDataSetChanged();
mIsLoading = false;
}
discussionsCursor.close();
dbDiscussions.destroy();
}
private void prepareDiscussionsArray(Cursor discussionsCursor) {
mDiscussionsArray.clear();
int noOfReturnedDiscussions = discussionsCursor.getCount();
discussionsCursor.moveToFirst();
for (int i = 0; i < noOfReturnedDiscussions; i++) {
DiscussionModel discussion = new DiscussionModel();
discussion.setDiscussionId(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_DISCUSSION_ID)));
discussion.setDiscussionTitle(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_DISCUSSION_TITLE)));
discussion.setUsername(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_USERNAME)));
mDiscussionsArray.add(discussion);
discussionsCursor.moveToNext();
}
}
private int calcItemPosition() {
int posInListView = 0;
for (int i = 0; i < mSelectedItemPosition - mFirstVisiblePosition - 1; i++) {
View child = getChildAt(i);
if (child == null) {
break;
}
posInListView += child.getHeight() + mDividerHeight;
}
// Log.d(TAG, "measured height :" + posInListView);
return posInListView;
}
public CustomHomeListView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
private void prepareForMySetSelection() {
if (mSelectedItemPosition > -1) {
mSavedPositionInsideListView = calcItemPosition();
}
}
private void mySetSelection() {
if (mSelectedItemPosition > -1) {
setSelectionFromTop(mSelectedItemPosition, mSavedPositionInsideListView);
} else {
setSelection(mFirstVisiblePosition);
}
}
public void onReceiveResult(int resultCode, Bundle resultData) {
prepareForMySetSelection(); // should be before
// RefreshListFromDatabase() so that
// actual position inside adapter is
// saved
refreshListFromDatabase();
setAdapter(mAdapter);
mySetSelection();
// }
removeFooterView(mFooterView);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mFirstVisiblePosition = getFirstVisiblePosition();
mSelectedItemPosition = getSelectedItemPosition();
if (mAdapter != null && mAdapter.getCount() > 0) {
int l = visibleItemCount + firstVisibleItem;
if (l >= totalItemCount && !mIsLoading) {
addFooterView(mFooterView);
pullDiscussions();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
}

ListView - ListView don't update

I'm trying to do Autogrowin/Endless ListView but I have a problem with ArrayAdapter = update after downloading the data.
public class ListShowActivity extends ListActivity {
private ShowsAdapter m_adapter;
private ArrayList<ShowsList> showList = new ArrayList<ShowsList>();
// Adapter
private class ShowsAdapter extends ArrayAdapter<ShowsList>
{
private ArrayList<ShowsList> items = new ArrayList<ShowsList>();
public ShowsAdapter(Context context, int textViewResourceId, ArrayList<ShowsList> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
public void appendList(ArrayList<ShowsList> results)
{
if((results != null) && (results.size() != 0))
{
m_adapter.add(results.get(0));
m_adapter.notifyDataSetChanged();
Log.i("test", "appendList: "+results.get(0).originalTitle);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
TextView tt = null;
TextView bt = null;
ImageView iv = null;
if (v == null){
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_show_item, null);
tt = (TextView) v.findViewById(R.id.showOriginalTitle);
bt = (TextView) v.findViewById(R.id.showTitle);
iv = (ImageView) v.findViewById(R.id.showPoster);
}
ShowsList item = this.items.get(position);
if (item != null) {
if(tt != null){
tt.setText(item.originalTitle);
}
if(bt != null){
bt.setText(item.title);
}
if(iv != null)
{
new DownloadImage().downloadImage(item.poster, iv);
}
}
return v;
}
}
// Implement new OnScrollListener
public class onScrollLoad implements OnScrollListener {
private int lastOffset = 10;
private int limit = 10;
private int mPrevTotalItemCount = 0;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (((firstVisibleItem + visibleItemCount) >= totalItemCount) && totalItemCount != mPrevTotalItemCount) {
lastOffset = totalItemCount;
mPrevTotalItemCount = lastOffset;
limit += 1;
ArrayList<ShowsList> results = new Api().getShows(lastOffset, limit);
m_adapter.appendList(results);
//new PagingRequest(m_adapter).execute(lastOffset, limit);
Toast.makeText(getApplicationContext(), lastOffset+" / "+limit, Toast.LENGTH_SHORT).show();
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
Log.i("test", "onScrollStateChange()");
}
}
// Implement AsyncTask for download items?
/*
private static class PagingRequest extends AsyncTask<Integer, Void, ArrayList<ShowsList>> {
private ShowsAdapter mAdapter;
public PagingRequest(ShowsAdapter adapter) {
this.mAdapter = adapter;
}
protected ArrayList<ShowsList> doInBackground(Integer... params) {
return new Api().getShows(params[0], params[1]);
}
protected void onPostExecute(ArrayList<ShowsList> result) {
this.mAdapter.appendList(result);
}
}
*/
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_shows);
TextView tv = (TextView) findViewById(R.id.headerbarText);
tv.setText("List Shows");
// Get Items
Api a = new Api();
// First 10 items
showList = a.getShows(0, 0);
if(showList.isEmpty() == false)
{
//showList = new Api().getShows(0,0);
m_adapter = new ShowsAdapter(this, R.layout.list_show_item, showList);
setListAdapter(m_adapter);
ListView lv = getListView();
lv.setOnScrollListener(new onScrollLoad());
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent = new Intent(ListShowActivity.this, ShowActivity.class);
//intent.putExtra("showID", getShowsList.get(position).ID);
startActivity(intent);
}
});
}else{
Toast.makeText(getApplicationContext(), "NoData", Toast.LENGTH_SHORT).show();
}
}
}
I pasted code without working Asynctask.
In "theory"^^ everything works (appendList Log return correct value), but i as say i have problem with update ShowsAdapter (Download new image + and insert content to ListView)

Categories

Resources