I'm using it for grid view, the count of object displayed is correct and it's returning in log is correct but for example 6 object display and the rest repeat them
1,2,3,4,5,6, 1,2,3,4,5,6,.....
my code
public class CustomAdapter extends ArrayAdapter<ItemObject> {
private static float textViewWidth;
public CustomAdapter(ArrayList<ItemObject> array, float textViewWidth) {
super(G.context, R.layout.sample_album_item, array);
CustomAdapter.textViewWidth = textViewWidth;
}
private static class ViewHolder {
ImageView imgScreenShot;
TextView txtAlbumName;
TextView txtAlbumAuthor;
public ViewHolder(View view) {
imgScreenShot = (ImageView) view.findViewById(R.id.screen_shot);
txtAlbumName = (TextView) view.findViewById(R.id.album_name);
txtAlbumAuthor = (TextView) view.findViewById(R.id.album_author);
}
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
ItemObject item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.sample_album_item, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
private static float widthSizeViaParent(TextView text, String newText) {
float textWidth = text.getPaint().measureText(newText);
return textViewWidth - (textWidth * G.displayMetrics.density);
}
}
if getView method without this (convertView == null) condition, everything is correct but scrolling is slowly
My guess is that this block of code makes it run slow:
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
Two loops runs for every single item. You probably want to have that logic in the models instead. So when rendering the items, albumName and albumAuthor is already set.
Related
I have a problem in Android, and Ive tried a couple of solutions, but nothing work.
When I scroll the list I get the exception:
java.lang.ClassCastException: com.example.restaurante.SmartMercadoriasAdapter$FirstViewHolder cannot be cast to com.example.restaurante.SmartMercadoriasAdapter$SecondViewHolder
This my code:
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
if (tipo.equals("1"))
return 0;
else
return 1;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
MyListSmartMercadoria mercadoria = null;
if(mercadorias.size() > 1){
mercadoria = mercadorias.get(position);
}else{
mercadoria = mercadorias.get(0);
}
tipo = "";
tipo = mercadoria.getTipo();
int viewType = getItemViewType(position);
switch (viewType) {
case 0: {
FirstViewHolder firstViewHolder = null;
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.merc_lista_smart_adp, parent, false);
firstViewHolder = new FirstViewHolder(view);
view.setTag(firstViewHolder);
}
else {
firstViewHolder = (FirstViewHolder)view.getTag();
}
firstViewHolder.mTipo.setText(tipo);
String codigo = mercadoria.getCod();
if(codigo.matches("[0-9]+")){
int codI = Integer.parseInt(mercadoria.getCod());
codigo = "[";
codigo += String.format("%06d", codI);
codigo += "]";
}else{
codigo = "[";
codigo += codigo;
int cont = 6 - codigo.length();
for(int i = 0; i < cont; i++){
codigo = codigo + " ";
}
codigo += "]";
}
firstViewHolder.mCodigo.setText(codigo);
firstViewHolder.mDescricao.setText(mercadoria.getNome());
firstViewHolder.mPreco.setText(mercadoria.getPreco());
break;
}
case 1: {
SecondViewHolder holder = null;
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.merc_sub_lista_smart_adp, parent, false);
holder = new SecondViewHolder(view);
view.setTag(holder);
}
else holder = (SecondViewHolder)view.getTag();
holder.mTipo.setText(tipo);
String codigo = mercadoria.getCod();
if(codigo.matches("[0-9]+")){
int codI = Integer.parseInt(mercadoria.getCod());
codigo = "[";
codigo += String.format("%06d", codI);
codigo += "]";
}else{
codigo = "[";
codigo += codigo;
int cont = 6 - codigo.length();
for(int i = 0; i < cont; i++){
codigo = codigo + " ";
}
codigo += "]";
}
holder.mCodigo.setText(codigo);
holder.mDescricao.setText(mercadoria.getNome());
holder.mQuant.setText(mercadoria.getPreco());
break;
}
}
return view;
}
protected class SecondViewHolder {
TextView mTipo;
TextView mCodigo;
TextView mDescricao;
EditText mQuant;
public SecondViewHolder(View view) {
mCodigo = (TextView) view.findViewById(R.id.text_view_cod_merc);
mTipo = (TextView) view.findViewById(R.id.text_view_tipo_merc);
mDescricao = (TextView) view.findViewById(R.id.text_view_nome_merc);
mQuant = (EditText) view.findViewById(R.id.text_view_preco_merc);
}
}
protected class FirstViewHolder {
TextView mTipo;
TextView mCodigo;
TextView mDescricao;
TextView mPreco;
public FirstViewHolder(View view) {
mCodigo = (TextView) view.findViewById(R.id.text_view_cod_merc);
mTipo = (TextView) view.findViewById(R.id.text_view_tipo_merc);
mDescricao = (TextView) view.findViewById(R.id.text_view_nome_merc);
mPreco = (TextView) view.findViewById(R.id.text_view_preco_merc);
}
}
EDIT1: The exception occurs in this stretch:
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.merc_sub_lista_smart_adp, parent, false);
holder = new SecondViewHolder(view);
view.setTag(holder);
}
else holder = (SecondViewHolder)view.getTag();
Specifically in view.getTag()
Don't store fields while views are recycled
Try this
#Override
public int getItemViewType(int position) {
String tipo = mercadorias.get(position).getTipo();
if (tipo.equals("1"))
return 0;
else
return 1;
}
Also, this doesn't make sense
if(mercadorias.size() > 1){
mercadoria = mercadorias.get(position);
}else{
mercadoria = mercadorias.get(0);
}
If the Arraylist is empty, this will throw an exception, but if the size is equal to one, then the position should already be the first element
I am getting incorrect id for child item click.
Fragment Class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View itemView = inflater.inflate(R.layout.fragment_checklist_groups_description, container, false);
fragmentManager = getActivity().getSupportFragmentManager();
mLinearListView = (LinearLayout) itemView.findViewById(R.id.linear_ListView);
//=========================================================================
for (int i = 0; i < 2; i++) {
V_ChecklistParentItemModel v_checklistParentItemModel = new V_ChecklistParentItemModel();
v_checklistParentItemModel.setParentGroupID("" + (i + 1));
v_checklistParentItemModel.setParentGroupName("Group Name " + i);
if (i == 0) {
v_checklistParentItemModel.setHasSubGroup(false);
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int j = 0; j < 3; j++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (j + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (j + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistParentItemModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
} else {
v_checklistParentItemModel.setHasSubGroup(true);
ArrayList<V_ChecklistSubGroupModel> tempV_checklistSubGroupModelArrayList = new ArrayList<>();
for (int j = 0; j < 2; j++) {
V_ChecklistSubGroupModel v_checklistSubGroupModel = new V_ChecklistSubGroupModel();
v_checklistSubGroupModel.setSubGroupID("" + (j + 1));
if (j == 0) {
v_checklistSubGroupModel.setSubGroupName("Sub Group Name 2a");
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int k = 0; k < 2; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistSubGroupModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
} else {
v_checklistSubGroupModel.setSubGroupName("Sub Group Name 2b");
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int k = 0; k < 3; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistSubGroupModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
}
tempV_checklistSubGroupModelArrayList.add(v_checklistSubGroupModel);
}
v_checklistParentItemModel.setV_checklistSubGroupModelArrayList(tempV_checklistSubGroupModelArrayList);
}
v_checklistParentItemModelArrayList.add(v_checklistParentItemModel);
}
//=========================================================================
//Adds data into first row
for (int i = 0; i < v_checklistParentItemModelArrayList.size(); i++) {
Log.v("I : ", " " + i);
LayoutInflater listInflater = null;
listInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = listInflater.inflate(R.layout.custom_cardview_checklist_groups_description_main_parent_item, null);
final TextView mProductName = (TextView) mLinearView.findViewById(R.id.textViewName);
final RelativeLayout mImageArrowFirst = (RelativeLayout) mLinearView.findViewById(R.id.rlFirstArrow);
final LinearLayout mLinearScrollSecond = (LinearLayout) mLinearView.findViewById(R.id.linear_scroll);
//checkes if menu is already opened or not
if (isFirstViewClick == false) {
mLinearScrollSecond.setVisibility(View.GONE);
mImageArrowFirst.setBackgroundResource(R.drawable.next_disable_icon);
} else {
mLinearScrollSecond.setVisibility(View.VISIBLE);
mImageArrowFirst.setBackgroundResource(R.drawable.arw_down);
}
//Handles onclick effect on list item
mImageArrowFirst.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isFirstViewClick == false) {
isFirstViewClick = true;
mImageArrowFirst.setBackgroundResource(R.drawable.arw_down);
mLinearScrollSecond.setVisibility(View.VISIBLE);
} else {
isFirstViewClick = false;
mImageArrowFirst.setBackgroundResource(R.drawable.next_disable_icon);
mLinearScrollSecond.setVisibility(View.GONE);
}
return false;
}
});
final String name = v_checklistParentItemModelArrayList.get(i).getParentGroupName();
mProductName.setText(name);
if (v_checklistParentItemModelArrayList.get(i).isHasSubGroup()) {
//Adds data into second row
for (int j = 0; j < v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().size(); j++) {
Log.v("J : ", " " + j);
LayoutInflater inflater2 = null;
inflater2 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView2 = inflater2.inflate(R.layout.custom_cardview_checklist_groups_description_child_parent_item, null);
TextView mSubItemName = (TextView) mLinearView2.findViewById(R.id.textViewTitle);
final RelativeLayout mLinearSecondArrow = (RelativeLayout) mLinearView2.findViewById(R.id.linearSecond);
final RelativeLayout mImageArrowSecond = (RelativeLayout) mLinearView2.findViewById(R.id.rlSecondArrow);
final LinearLayout mLinearScrollThird = (LinearLayout) mLinearView2.findViewById(R.id.linear_scroll_third);
final LinearLayout linearLayoutMain = (LinearLayout) mLinearView2.findViewById(R.id.llMain);
if (i == 0) {
mLinearSecondArrow.setBackgroundColor(getResources().getColor(R.color.main_parent));
mImageArrowSecond.setVisibility(View.GONE);
linearLayoutMain.setPadding(20, 0, 0, 0);
} else {
mLinearSecondArrow.setBackgroundColor(getResources().getColor(R.color.child_parent));
mImageArrowSecond.setVisibility(View.VISIBLE);
if (i == 1) {
linearLayoutMain.setPadding(20, 8, 0, 0);
} else {
linearLayoutMain.setPadding(15, 8, 0, 0);
}
}
//checkes if menu is already opened or not
if (isSecondViewClick == false) {
mLinearScrollThird.setVisibility(View.GONE);
mImageArrowSecond.setBackgroundResource(R.drawable.next_disable_icon);
} else {
mLinearScrollThird.setVisibility(View.VISIBLE);
mImageArrowSecond.setBackgroundResource(R.drawable.arw_down);
}
//Handles onclick effect on list item
if (i == 0) {
final int finalI1 = i;
final int finalJ1 = j;
mLinearSecondArrow.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI1).getParentGroupName());
bundle.putInt("itemCount", 3);
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
pageNumber = 0;
bundle.putInt("pageNumber", pageNumber);
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.sd_project_list_screen_name));
return false;
}
});
} else {
mImageArrowSecond.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isSecondViewClick == false) {
isSecondViewClick = true;
mImageArrowSecond.setBackgroundResource(R.drawable.arw_down);
mLinearScrollThird.setVisibility(View.VISIBLE);
} else {
isSecondViewClick = false;
mImageArrowSecond.setBackgroundResource(R.drawable.next_disable_icon);
mLinearScrollThird.setVisibility(View.GONE);
}
return false;
}
});
}
final String catName = v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getSubGroupName();
mSubItemName.setText(catName);
//Adds items in subcategories
for (int k = 0; k < v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getV_checklistChildItemModelArrayList().size(); k++) {
Log.v("K : ", " " + k);
LayoutInflater inflater3 = null;
inflater3 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView3 = inflater3.inflate(R.layout.custom_cardview_checklist_groups_description_child_item, null);
TextView mItemName = (TextView) mLinearView3.findViewById(R.id.textViewItemName);
final String itemName = v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getV_checklistChildItemModelArrayList().get(k).getChildItemQuestionName();
mItemName.setText(itemName);
mLinearScrollThird.addView(mLinearView3);
final int finalI = i;
final int finalJ = j;
final int finalK = k;
mLinearScrollThird.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI).getParentGroupName());
bundle.putInt("itemCount", v_checklistParentItemModelArrayList.get(finalI).getV_checklistSubGroupModelArrayList().get(finalJ).getV_checklistChildItemModelArrayList().size());
// bundle.putSerializable("questionData", group2bQuestionList);
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
pageNumber = finalI + finalJ + finalK + 1;
bundle.putInt("pageNumber", pageNumber);
Log.v("====ugugugu==", "===ijhbjhbjh===");
Toast.makeText(getActivity(), "Page No. " + v_checklistParentItemModelArrayList.get(finalI).getV_checklistSubGroupModelArrayList().get(finalJ).getV_checklistChildItemModelArrayList().get(finalK).getChildQuestionID(), Toast.LENGTH_LONG).show();
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.check_list_groups_question_screen_name));
return false;
}
});
}
mLinearScrollSecond.addView(mLinearView2);
}
mLinearListView.addView(mLinearView);
} else {
//Adds items in subcategories
for (int k = 0; k < v_checklistParentItemModelArrayList.get(i).getV_checklistChildItemModelArrayList().size(); k++) {
Log.v("K : ", " " + k);
LayoutInflater inflater3 = null;
inflater3 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView3 = inflater3.inflate(R.layout.custom_cardview_checklist_groups_description_child_item, null);
final LinearLayout mLinearScrollThird = (LinearLayout) mLinearView3.findViewById(R.id.linear_scroll_third);
TextView mItemName = (TextView) mLinearView3.findViewById(R.id.textViewItemName);
final String itemName = v_checklistParentItemModelArrayList.get(i).getV_checklistChildItemModelArrayList().get(k).getChildItemQuestionName();
mItemName.setText(itemName);
final int finalI = i;
final int finalK = k;
mLinearScrollThird.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI).getParentGroupName());
bundle.putInt("itemCount", v_checklistParentItemModelArrayList.get(finalI).getV_checklistChildItemModelArrayList().size());
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
bundle.putInt("pageNumber", 1);
Toast.makeText(getActivity(), "Page No. " + v_checklistParentItemModelArrayList.get(finalI).getV_checklistChildItemModelArrayList().get(finalK).getChildQuestionID(), Toast.LENGTH_LONG).show();
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.check_list_groups_question_screen_name));
return false;
}
});
mLinearScrollSecond.addView(mLinearView3);
}
mLinearListView.addView(mLinearView);
}
}
//==============================================================================
return itemView;
}
I have assigned Child Question ID using setChildQuestionID(). For Group Name 0, I get 0, 1, 2 on each child click. However, for Group Name 1, I get 4 for Sub Group Name 2a & 7 for Sub Group Name 2b for each of there child item click. Ideally, it should return whatever I set for them.
Do you mean that you want to get 0, 1, 2 for child clicks in group name 1? As far as I can tell, you're going to have to re-set the value of index to 0 to get that. At least, assuming you've defined index = 0 somewhere outside your outermost for-loop (I can't see where in your code you've set the value of index). Right now in Group 0, you have:
for (int k = 0; k < 2; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
If index was 0 to start with, the value of index is now greater than 0. You don't set it back to 0, so when you get to the next cycle through your top-level for loop, the value of index is already > 0. If you want to start over at index = 0 in Group 1, you'll have to set the value of index back to 0.
In other words, you are returning exactly what you set for the questionIDs, but I think you're setting a number that you didn't want to set.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder helper = null;
Log.i("StaggeredGridView--Adapter:", "position:" + position);
if(convertView ==null){
helper = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user_details_adapter, null);
helper.tv_content = (EmojiconTextView) convertView.findViewById(R.id.txt_content);
helper.tv_time = (TextView) convertView.findViewById(R.id.txt_time);
helper.tv_zannum = (TextView) convertView.findViewById(R.id.tv_zan_num);
helper.tv_plnum = (TextView) convertView.findViewById(R.id.tv_pl_num);
helper.iv_show = (DynamicHeightImageView) convertView.findViewById(R.id.img_content);// 展示的图片
helper.img_zan = (ImageView) convertView.findViewById(R.id.img_normal);// 已经赞过的改颜色。
helper.rel_photo = (RelativeLayout) convertView.findViewById(R.id.rel_photo);
convertView.setTag(helper);
} else {
helper = (ViewHolder) convertView.getTag();
}
double positionHeight = getPositionRatio(position);
Log.d(TAG, "getView position:" + position + " h:" + positionHeight);
helper.iv_show.setHeightRatio(positionHeight);
String imgeurl = "";
List<Map<String, String>> listget = mUserInfors.get(position).getmAttach();
if (listget != null && listget.size() > 0) {
for (int i = 0; i < listget.size(); i++) {
Map<String, String> map = listget.get(i);
if (map != null) {
if (map.get("attach_middle") != null) {
imgeurl = map.get("attach_middle");
if (!TextUtils.isEmpty(imgeurl)) {
break;
}
}
}
}
}
List<Map<String, String>> diggerlist = mUserInfors.get(position).getDigger_list();
if (diggerlist.size() > 0) {
helper.tv_zannum.setText(diggerlist.size() + "");
boolean state = getCheckstate(diggerlist);
if (state) {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.zan));
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
if (!TextUtils.isEmpty(imgeurl)) {
ImageLoader.getInstance().displayImage(imgeurl, helper.iv_show, mDisplayOption);
} else {
helper.iv_show.setImageDrawable(mContext.getResources().getDrawable(R.drawable.empty_activity_icon));
}
String content = mUserInfors.get(position).getContent();
String time = mUserInfors.get(position).getCtime();
helper.tv_time.setText(time.substring(5));
helper.tv_zannum.setText(mUserInfors.get(position).getDigg_count());
helper.tv_plnum.setText(mUserInfors.get(position).getComment_count());
helper.tv_content.setText(content);
if (mUserInfors.get(position).getType().equals("post")) {
helper.rel_photo.setVisibility(View.GONE);
helper.tv_content.setVisibility(View.VISIBLE);
} else {
if (TextUtils.isEmpty(content)) {
helper.tv_content.setVisibility(View.GONE);
} else {
helper.tv_content.setVisibility(View.VISIBLE);
}
helper.rel_photo.setVisibility(View.VISIBLE);
}
return convertView;
}
Above is the code of getview, I was in the use of staggeredgridview Etsy ,when I scroll the screen,this problem is occurs, a time when the position is out of confusion, as if the location of the position did not be remembered.
The following is a screenshot of position getview:
This issue comes only if you are not controlling getCount() and getItem() methods. Make sure that you are returning your list size as in getCount() like this :
#Override
public int getCount() {
return list.size();
}
and getItem() as :
#Override
public SetterGetterClassName getItem(int position) {
return list.get(position);
}
This is my complete code :
enter code here
public class UserDetailsAdapter2 extends BaseAdapter {
//private HashMap<Integer, View> viewMap;
private DisplayImageOptions mDisplayOption = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true)
.showStubImage(R.drawable.empty_activity_icon).showImageForEmptyUri(R.drawable.empty)
.showImageOnFail(R.drawable.empty_activity_icon).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(400)).considerExifParams(true)
.build();
private Context mContext;
private List<CellQzones> mUserInfors;
private UserInfor mUser;
private String TAG = "UserDetailsAdapter2";
private final Random mRandom;
private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
//private ImageLoader2 mImageLoader2;
public UserDetailsAdapter2(Context context, List<CellQzones> mDatas, UserInfor user) {
mContext = context;
mUserInfors = mDatas;
mUser = user;
mRandom = new Random();
//viewMap=new HashMap<Integer, View>();
}
#Override
public int getCount() {
return mUserInfors.size();
}
#Override
public Object getItem(int position) {
return mUserInfors.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder helper = null;
Log.i("StaggeredGridView--Adapter:", "position:" + position);
// if(!viewMap.containsKey(position) || viewMap.get(position) == null){
if(convertView ==null){
helper = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user_details_adapter, null);
helper.tv_content = (EmojiconTextView) convertView.findViewById(R.id.txt_content);
helper.tv_time = (TextView) convertView.findViewById(R.id.txt_time);
helper.tv_zannum = (TextView) convertView.findViewById(R.id.tv_zan_num);
helper.tv_plnum = (TextView) convertView.findViewById(R.id.tv_pl_num);
helper.iv_show = (DynamicHeightImageView) convertView.findViewById(R.id.img_content);// 展示的图片
helper.img_zan = (ImageView) convertView.findViewById(R.id.img_normal);// 已经赞过的改颜色。
helper.rel_photo = (RelativeLayout) convertView.findViewById(R.id.rel_photo);
convertView.setTag(helper);
} else {
//convertView = viewMap.get(position);
helper = (ViewHolder) convertView.getTag();
}
double positionHeight = getPositionRatio(position);
Log.d(TAG, "getView position:" + position + " h:" + positionHeight);
helper.iv_show.setHeightRatio(positionHeight);
String imgeurl = "";
List<Map<String, String>> listget = mUserInfors.get(position).getmAttach();
if (listget != null && listget.size() > 0) {
for (int i = 0; i < listget.size(); i++) {
Map<String, String> map = listget.get(i);
if (map != null) {
if (map.get("attach_middle") != null) {
imgeurl = map.get("attach_middle");
if (!TextUtils.isEmpty(imgeurl)) {
break;
}
}
}
}
}
List<Map<String, String>> diggerlist = mUserInfors.get(position).getDigger_list();
if (diggerlist.size() > 0) {
helper.tv_zannum.setText(diggerlist.size() + "");
boolean state = getCheckstate(diggerlist);
if (state) {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.zan));
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
if (!TextUtils.isEmpty(imgeurl)) {
//mImageLoader2.loadImage(imgeurl,helper.iv_show, true);
ImageLoader.getInstance().displayImage(imgeurl, helper.iv_show, mDisplayOption);
} else {
helper.iv_show.setImageDrawable(mContext.getResources().getDrawable(R.drawable.empty_activity_icon));
}
String content = mUserInfors.get(position).getContent();
String time = mUserInfors.get(position).getCtime();
helper.tv_time.setText(time.substring(5));
helper.tv_zannum.setText(mUserInfors.get(position).getDigg_count());
helper.tv_plnum.setText(mUserInfors.get(position).getComment_count());
helper.tv_content.setText(content);
if (mUserInfors.get(position).getType().equals("post")) {
helper.rel_photo.setVisibility(View.GONE);
helper.tv_content.setVisibility(View.VISIBLE);
} else {
if (TextUtils.isEmpty(content)) {
helper.tv_content.setVisibility(View.GONE);
} else {
helper.tv_content.setVisibility(View.VISIBLE);
}
helper.rel_photo.setVisibility(View.VISIBLE);
}
return convertView;
}
public class ViewHolder {
EmojiconTextView tv_content;
TextView tv_time;
TextView tv_zannum;
TextView tv_plnum;
DynamicHeightImageView iv_show;
ImageView img_zan;
RelativeLayout rel_photo;
}
private double getPositionRatio(final int position) {
double ratio = sPositionHeightRatios.get(position, 0.0);
// if not yet done generate and stash the columns height
// in our real world scenario this will be determined by
// some match based on the known height and width of the image
// and maybe a helpful way to get the column height!
if (ratio == 0) {
ratio = getRandomHeightRatio();
sPositionHeightRatios.append(position, ratio);
Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
}
return ratio;
}
private double getRandomHeightRatio() {
return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5
// the width
}
/** 得到checkbox的赞的状态 **/
private boolean getCheckstate(List<Map<String, String>> diggerlist) {
for (int i = 0; i < diggerlist.size(); i++) {
Map<String, String> mp = diggerlist.get(i);
String uid = mUser.getUid();
String mUid = mp.get("uid");
// 如果有就设置true。
if (uid.equals(mUid)) {
return true;
}
}
return false;
}
}
For eg:- if i load first 5 items in a list then on scrolling down load next five items
and as it is a endlessadapter this procedure must repeat endlessly
this is how i tried -->foliowing is my demoadapter code:-
public class MyDemoAdapter extends EndlessAdapter {
private static int cutting_int =5;
public static int batch_repeat = 0;
public int check_batch = 0;
private Context mcontxt;
private RotateAnimation rotate = null;
ArrayList<DownloadOffersClass> tempList = new ArrayList<DownloadOffersClass>();
private static int mLastOffset = 0;
private ArrayList<DownloadOffersClass> list = new ArrayList<DownloadOffersClass>();
private int LIST_SIZE;
public MyDemoAdapter(Context context, int textViewResourceId,
ArrayList<DownloadOffersClass> list, int lIST_SIZE) {
super(new DownloadedOffersAdapter(context,
R.layout.offer_listview_item, list));
this.mcontxt = context;
this.list = list;
this.LIST_SIZE = lIST_SIZE;
rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
#Override
protected View getPendingView(ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mcontxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.row, null);
View child = row.findViewById(android.R.id.text1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return (row);
}
#Override
protected boolean cacheInBackground() {
SystemClock.sleep(2000);
if (check_batch != batch_repeat) {
tempList.clear();
int lastOffset = getLastOffset();
if (lastOffset < LIST_SIZE) {
int limit = lastOffset + cutting_int;
for (int i = (lastOffset + 1); (i <= limit && i < LIST_SIZE); i++) {
tempList.add(list.get(i));
}
setLastOffset(limit);
if (limit < 50) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
#Override
protected void appendCachedData() {
if (getWrappedAdapter().getCount() < 50) {
#SuppressWarnings("unchecked")
DownloadedOffersAdapter a = (DownloadedOffersAdapter) getWrappedAdapter();
check_batch = check_batch + 1;
Log.v("Check", " " + check_batch);
for (int i = cutting_int; i < cutting_int + cutting_int; i++) {
a.add(list.get(i));
}
}
}
public static void setLastOffset(int i) {
mLastOffset = i;
}
private int getLastOffset() {
return mLastOffset;
}
}
Modify your cacheInBackground()
if (check_batch != batch_repeat) {
tempList.clear();
int lastOffset = getLastOffset();
if (lastOffset < LIST_SIZE) {
int limit = lastOffset + cutting_int;
for (int i = (lastOffset + 1); (i <= limit && i < LIST_SIZE); i++) {
tempList.add(list.get(i));
}
setLastOffset(limit);
if (limit <= 50) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
if (!firstTry) {// use this boolean to do it only once
tempList.clear();
int notDivisible = LIST_SIZE % cutting_int;
if (!(notDivisible == 0)) {
firstTry = true;
return true;
} else {
return false;
}
}
return false;
}
And replace your appendCachedData() method with this:
protected void appendCachedData() {
DownloadedOffersAdapter a = (DownloadedOffersAdapter) getWrappedAdapter();
if (check_batch != batch_repeat) {
if (getWrappedAdapter().getCount() <= 50) {
check_batch = check_batch + 1;
Log.v("Check", "append chk_batch " + check_batch);
for (int i = cutting_int; i < cutting_int + cutting_int; i++) {
a.add(list.get(i));
}
}
} else {// Append extra entries to list i.e less than cutting_int
int notDivisible = LIST_SIZE % cutting_int;
for (int i = (LIST_SIZE - notDivisible); i < LIST_SIZE - 1; i++) {
a.add(list.get(i));
}
return;
}
}
You will create the object for ImageLoader on your listadapter.
ImageLoader lazyload = new ImageLoader(context);
public ImageLoader(Context context) {
FileCache fileCache = new FileCache(context);
ExecutorService executorService = Executors.newFixedThreadPool(5);
}
Then set images to your adapter getView() like this.
ImageView image = (ImageView) view.findViewById(R.id.yourImage);
lazyload.displayImage(image);
load your Images
public void displayImage(String url, ImageView imageView) {
if (bitmap != null)
imageView.setImageBitmap(bitmap);
For eg:- if i load first 5 items in a list then on scrolling down load next five items
You are responsible for populating the adapter with enough items to warrant scrolling, and 5 is unlikely to be enough.
You are responsible for determining how many additional items to load when you are told to go load additional data.
and as it is a endlessadapter this procedure must repeat endlessly
Or until you tell the EndlessAdapter that there is no more data, such as by returning false from cacheInBackground(). The idea here is that when you do the Web service call to get the next set of data, you should also determine whether you have reached the end of the available data.
I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}