Android custom listview View with timer - android

I have a problem with the list. My list consists of two rows. The first is simply information about the object. When I click on the first item is presented a second row. It has a timer, everything works as expected, but the re-acquired by the time starts ticking faster. I understand that it is necessary to clean the list or am I just doing something wrong. Help me please.
This is my code:
public class MainActivity extends Activity {
ArrayList<Childrens> arrayList = new ArrayList<Childrens>();
ChilndrensAdapter adapter;
ListView listView;
private static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
final Childrens ls = new Childrens();
arrayList = ls.getListView();
adapter = new ChilndrensAdapter(getApplicationContext(), arrayList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (arrayList.get(position).status == false) {
Log.d("True", " True");
adapter.setSelecterIndex(position);
adapter.toggleSelected(new Integer(position));
adapter.startUpdateTimer(position);
adapter.notifyDataSetChanged();
} else if (arrayList.get(position).status == true) {
Log.d("False", " False");
adapter.setSelecterIndex(position);
adapter.toggleSelected(new Integer(position));
adapter.stopUpdateTimer(position);
adapter.notifyDataSetChanged();
}
}
});
}
public static Context getContext() {
return context;
}
}
Adapter:
public class ChilndrensAdapter extends BaseAdapter {
ArrayList<Childrens> arrayList;
Context context;
private LayoutInflater cInflater;
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
private ArrayList<ViewHolder> lstHolders;
private static final int END = 0;
private static final int START = 1;
Timer tmr = new Timer();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
//Log.d("Runnable","Runnable");
synchronized (lstHolders) {
long currentTime = 0L;
//long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining(currentTime);
}
}
}
};
public ChilndrensAdapter(Context context, ArrayList<Childrens> arrayList) {
this.context = context;
this.arrayList = arrayList;
this.cInflater = LayoutInflater.from(context.getApplicationContext());
lstHolders = new ArrayList<>();
// startUpdateTimer();
}
public void startUpdateTimer(final int positon) {
arrayList.get(positon).status = true;
tmr.schedule(new TimerTask() {
#Override
public void run() {
//Log.d("tmr","tmr");
mHandler.post(updateRemainingTimeRunnable);
// arrayList.get(positon).time = arrayList.get(positon).time + 1;
}
}, 1000, 1000);
for (int i = 0; i < lstHolders.size(); i++) {
//Log.d("Holders: ","H: "+ i+" " + lstHolders.get(i) +" Size: " + lstHolders.size() + " Time: "+arrayList.get(positon).time);
}
}
public void stopUpdateTimer(int position) {
arrayList.get(position).time = 0;
arrayList.get(position).status = false;
// Log.d("Timer Run:", "Time is:" + lstHolders.size());
}
#Override
public int getCount() {
if (arrayList == null) {
return 0;
}
return arrayList.size();
}
public void setSelecterIndex(int ind) {
notifyDataSetChanged();
}
public void toggleSelected(Integer position) {
if (selectedIds.contains(position)) {
selectedIds.remove(position);
} else {
selectedIds.add(position);
}
}
#Override
public int getItemViewType(int position) {
if (selectedIds.contains(position)) {
return 1;
} else
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public Childrens getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Childrens item = (Childrens) getItem(position);
int type = getItemViewType(position);
if (convertView == null) {
switch (type) {
case END:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_normal, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.info = (TextView) convertView.findViewById(R.id.name_control);
convertView.setTag(holder);
break;
case START:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_start, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name_start);
holder.button = (ImageView) convertView.findViewById(R.id.dialog_button);
holder.holderTimer = (TextView) convertView.findViewById(R.id.answerTime);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
break;
}
} else {
holder = (ViewHolder) convertView.getTag();
}
switch (type) {
case END:
holder.name.setText(item.name);
holder.info.setText("Time");
break;
case START:
holder.setData(getItem(position));
holder.name.setText(item.name);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.getContext());
dialog.setTitle("Position " + position);
dialog.setContentView(R.layout.dialog);
dialog.show();
}
});
break;
}
return convertView;
}
public class ViewHolder {
private TextView name;
private TextView info;
public TextView holderTimer;
public ImageView button;
Childrens mChildrens;
public void setData(Childrens item) {
mChildrens = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
int sec = (mChildrens.time) % 60;
int min = (mChildrens.time / 60) % 60;
holderTimer.setText(String.format("%02d", min) + ":" + String.format("%02d", sec));
// holderTimer.setText("Time: " + min +":"+ sec);
}
}
}
Object:
public class Childrens {
public String name;
public int id;
public long answerTime = 0;
public boolean status;
public int time;
final static Childrens CHILDRENS_STATE = new Childrens();
Childrens(String n, int id, long answerTime) {
this.name = n;
this.id = id;
this.answerTime = answerTime;
}
Childrens() {
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public static Childrens getInstance() {
return CHILDRENS_STATE;
}
public ArrayList<Childrens> getListView() {
ArrayList<Childrens> arrayList = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
Childrens c = new Childrens();
c.status = false;
c.name = "Child: " + i;
c.time = 0;
arrayList.add(c);
//arrayList.add(new Childrens("Tata"+ i, i, answerTime));
}
return arrayList;
}
}

Sorry there was mistake in adapter
public class ChilndrensAdapter extends BaseAdapter {
ArrayList<Childrens> arrayList;
Context context;
private LayoutInflater cInflater;
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
private ArrayList<ViewHolder> lstHolders;
private static final int END = 0;
private static final int START = 1;
Timer tmr = new Timer();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
public ChilndrensAdapter(Context context, ArrayList<Childrens> arrayList){
this.context = context;
this.arrayList = arrayList;
this.cInflater = LayoutInflater.from(context.getApplicationContext());
lstHolders = new ArrayList<>();
}
public void startUpdateTimer(final int positon) {
arrayList.get(positon).status = true;
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
arrayList.get(positon).time = arrayList.get(positon).time + 1;
}
}, 1000, 1000);
}
public void stopUpdateTimer(int position) {
arrayList.get(position).time = 0;
arrayList.get(position).status = false;
}
#Override
public int getCount() {
if(arrayList == null){
return 0;
}
return arrayList.size();
}
public void setSelecterIndex(int ind){
notifyDataSetChanged();
}
public void toggleSelected(Integer position){
if (selectedIds.contains(position)){
selectedIds.remove(position);
}else {
selectedIds.add(position);
}
}
#Override
public int getItemViewType(int position) {
if (selectedIds.contains(position)){
return 1;
}else
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public Childrens getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Childrens item = (Childrens) getItem(position);
int type = getItemViewType(position);
if(convertView == null){
switch (type){
case END:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_normal, parent,false);
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.info = (TextView)convertView.findViewById(R.id.name_control);
convertView.setTag(holder);
break;
case START:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_start, parent, false);
holder.name = (TextView)convertView.findViewById(R.id.name_start);
holder.button = (ImageView)convertView.findViewById(R.id.dialog_button);
holder.holderTimer = (TextView)convertView.findViewById(R.id.answerTime);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
break;
}
}else {
holder = (ViewHolder) convertView.getTag();
}
switch (type){
case END:
holder.name.setText(item.name);
holder.info.setText("Time");
break;
case START:
holder.setData(getItem(position));
holder.name.setText(item.name);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.getContext());
dialog.setTitle("Position " + position);
dialog.setContentView(R.layout.dialog);
dialog.show();
}
});
break;
}
return convertView;
}
public class ViewHolder{
private TextView name;
private TextView info;
public TextView holderTimer;
public ImageView button;
Childrens mChildrens;
public void setData(Childrens item) {
mChildrens = item;
updateTimeRemaining();
}
public void updateTimeRemaining(long currentTime) {
int sec = (mChildrens.time)%60;
int min = (mChildrens.time/60)%60;
holderTimer.setText(String.format("%02d", min) + ":" + String.format("%02d", sec));
}
}
}

I solved the problem and I want to share with you the ready code.
When creating a new timer I dobovlyaet it to your array of, and with the second click on an element and find this timer is reset to zero it. Although at this point I'm going to send data to the server to zero. Generally it works, check!
public class ChilndrensAdapter extends BaseAdapter {
ArrayList<Childrens> arrayList;
Context context;
private LayoutInflater cInflater;
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
private ArrayList<ViewHolder> lstHolders;
private static final int END = 0;
private static final int START = 1;
Timer tmr;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
public ChilndrensAdapter(Context context, ArrayList<Childrens> arrayList){
this.context = context;
this.arrayList = arrayList;
this.cInflater = LayoutInflater.from(context.getApplicationContext());
lstHolders = new ArrayList<>();
}
public void startUpdateTimer(final int positon) {
arrayList.get(positon).status = true;
tmr = new Timer();
arrayList.get(positon).timer = tmr;
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
arrayList.get(positon).time = arrayList.get(positon).time + 1;
}
}, 1000, 1000);
}
public void stopUpdateTimer(int position) {
arrayList.get(position).timer.cancel();
arrayList.get(position).timer = null;
arrayList.get(position).time = 0;
arrayList.get(position).status = false;
}
#Override
public int getCount() {
if(arrayList == null){
return 0;
}
return arrayList.size();
}
public void setSelecterIndex(int ind){
notifyDataSetChanged();
}
public void toggleSelected(Integer position){
if (selectedIds.contains(position)){
selectedIds.remove(position);
}else {
selectedIds.add(position);
}
}
#Override
public int getItemViewType(int position) {
if (selectedIds.contains(position)){
return 1;
}else
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public Childrens getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Childrens item = (Childrens) getItem(position);
int type = getItemViewType(position);
if(convertView == null){
switch (type){
case END:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_normal, parent,false);
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.info = (TextView)convertView.findViewById(R.id.name_control);
convertView.setTag(holder);
break;
case START:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_start, parent, false);
holder.name = (TextView)convertView.findViewById(R.id.name_start);
holder.button = (ImageView)convertView.findViewById(R.id.dialog_button);
holder.holderTimer = (TextView)convertView.findViewById(R.id.answerTime);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
break;
}
}else {
holder = (ViewHolder) convertView.getTag();
}
switch (type){
case END:
holder.name.setText(item.name);
holder.info.setText("Time");
break;
case START:
holder.setData(getItem(position));
holder.name.setText(item.name);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.getContext());
dialog.setTitle("Position " + position);
dialog.setContentView(R.layout.dialog);
dialog.show();
}
});
break;
}
return convertView;
}
public class ViewHolder{
private TextView name;
private TextView info;
public TextView holderTimer;
public ImageView button;
Childrens mChildrens;
public void setData(Childrens item) {
mChildrens = item;
updateTimeRemaining();
}
public void updateTimeRemaining() {
int sec = (mChildrens.time)%60;
int min = (mChildrens.time/60)%60;
holderTimer.setText(String.format("%02d", min) + ":" + String.format("%02d", sec));
}
}
}

Related

Specific View holder in recyclerView Adapter cant cast to View Holder

I use below code but its has an error:-
EventAdapter$MainViewHolder cannot be cast to EventAdapter$ProfileViewHolder
But each viewHolder extended from MainViewHolder,
where is problem in this code?
thanks guys, I am newcomer in stack overflow!
public class NavDrawerAdapter extends RecyclerView.Adapter<NavDrawerAdapter.MainViewHolder> {
List<MainOption> mainOptionlist;
Context context;
private static final int TYPE_PROFILE = 1;
private static final int TYPE_OPTION_MENU = 2;
public NavDrawerAdapter(Context context){
this.mainOptionlist = MainOption.getDrawableDataList();
this.context = context;
}
#Override
public int getItemViewType(int position) {
return (position == 0? TYPE_PROFILE : TYPE_OPTION_MENU);
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){}
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
if(holder.getItemViewType() == TYPE_PROFILE){
ProfileViewHolder mholder = (ProfileViewHolder) holder;
}
else {
MyViewHolder mHolder = (MyViewHolder) holder;
MainOption mo = mainOptionlist.get(position);
mHolder.tv_title.setText(mo.title);
}
}
#Override
public int getItemCount() {
return mainOptionlist.size();
}
public class MyViewHolder extends MainViewHolder{
public MyViewHolder(View v){
super(v);
}
}
public class ProfileViewHolder extends MainViewHolder{
public ProfileViewHolder(View v){
super(v);
}
}
public class MainViewHolder extends RecyclerView.ViewHolder {
public MainViewHolder(View v) {
super(v);
}
}
public class ChaptersAdapter extends BaseAdapter {
private static final int TYPE_CHAPTER = 0;
private static final int TYPE_PART = 1;
private Context mContext;
private ArrayList<Chapter> mChapters;
private LayoutInflater mInflater;
private ItemClickListener mItemClickListener;
private TreeSet<Integer> mSectionNumber = new TreeSet<Integer>();
private boolean mIsPaid;
public ChaptersAdapter(Context context, ArrayList<Chapter> chapters, ItemClickListener itemClickListener, boolean isPaid) {
mContext = context;
mChapters = chapters;
mItemClickListener = itemClickListener;
mInflater = LayoutInflater.from(context);
mIsPaid = isPaid;
saveSectionNum();
}
#Override
public int getCount() {
int n = 0;
for (int i = 0; i < mChapters.size(); i++) {
n += mChapters.get(i).mParts.size();
}
n += mChapters.size();
if (n < 0)
return 0;
return n;
}
private void saveSectionNum() {
int n = 0;
for (int i = 0; i < mChapters.size(); i++) {
mSectionNumber.add(n);
n += mChapters.get(i).mParts.size();
n++;
}
}
private ChapterPart getChapterPart(int position) {
int n = 0;
int chapterNum = 0;
int partNum = -1;
while ( n < position ) {
n++;
n += mChapters.get(chapterNum).mParts.size();
chapterNum++;
}
if ( n > position ) {
chapterNum--;
n = n - mChapters.get(chapterNum).mParts.size();
partNum = position - n;
} else if ( n == position) {
partNum = -1;
}
return new ChapterPart(chapterNum, partNum);
}
#Override
public int getItemViewType(int position) {
return mSectionNumber.contains(position) ? TYPE_CHAPTER : TYPE_PART;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public Object getItem(int position) {
ChapterPart chapterPart = getChapterPart(position);
if (-1 == chapterPart.mPartNum) {
return mChapters.get(chapterPart.mChapterNum);
}
return mChapters.get(chapterPart.mChapterNum).mParts.get(chapterPart.mPartNum);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int rowType = getItemViewType(position);
if (convertView == null) {
switch (rowType) {
case TYPE_CHAPTER:
convertView = mInflater.inflate(R.layout.listitem_chapter, null);
ChapterTag tag1 = new ChapterTag(convertView);
convertView.setTag(tag1);
break;
case TYPE_PART:
convertView = mInflater.inflate(R.layout.listitem_part, null);
PartTag tag2 = new PartTag(convertView);
convertView.setTag(tag2);
break;
}
}
switch (rowType) {
case TYPE_CHAPTER:
ChapterTag tag1 = (ChapterTag)(convertView.getTag());
Chapter chapter = (Chapter)getItem(position);
tag1.setData(position, chapter);
break;
case TYPE_PART:
PartTag tag2 = (PartTag)(convertView.getTag());
Part part = (Part)getItem(position);
tag2.setData(position, part);
break;
}
return convertView;
}
class ChapterTag {
View view;
TextView txtChapter;
Chapter chapter;
public ChapterTag(final View view) {
this.view = view;
txtChapter = (TextView) view.findViewById(R.id.txt_chapter);
}
public void setData(int position, Chapter chapter) {
this.chapter = chapter;
txtChapter.setText(chapter.mName);
}
}
class PartTag {
View view;
TextView txtPart;
FancyButton btnVideo;
FancyButton btnAudio;
Part part;
public PartTag(final View view) {
this.view = view;
txtPart = (TextView) view.findViewById(R.id.txt_part);
btnVideo = (FancyButton) view.findViewById(R.id.btn_video);
UiUtil.applyButtonEffect(btnVideo, new Runnable() {
#Override
public void run() {
mItemClickListener.onVideoClick(part.mVideoURL);
}
});
btnAudio = (FancyButton) view.findViewById(R.id.btn_audio);
UiUtil.applyButtonEffect(btnAudio, new Runnable() {
#Override
public void run() {
mItemClickListener.onAudioClick(part.mAudioURL);
}
});
}
public void setData(int position, Part part) {
this.part = part;
txtPart.setText(part.mName);
if (part.mVideoURL.equals("")) {
btnVideo.setEnabled(false);
}
if (part.mAudioURL.equals("")) {
btnAudio.setEnabled(false);
}
ChapterPart chapterpart = getChapterPart(position);
if (position > 3 + chapterpart.mChapterNum && mIsPaid == false) {
btnVideo.setEnabled(false);
btnAudio.setEnabled(false);
}
}
}
class ChapterPart {
int mChapterNum;
int mPartNum;
ChapterPart(int chapterNum, int partNum) {
mChapterNum = chapterNum;
mPartNum = partNum;
}
}
}

How to get shared preference value from baseadaptor to activity

Selecting multiple items from custom list view and passing to another
list view. When I close the application, these selected items are getting clean.
I have used shared preference ,I could not able to get the data>
MainActivity
MainActivity.java
public class MainActivity extends Activity {
private Button bt_inst_app;
GridView gridView, gv_shortcut;
List<AppList> installedApps;
List<AppList> res = new ArrayList<AppList>();
private String appName, appPackageName;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
gv_shortcut = (GridView) findViewById(R.id.gv_shortcut);
bt_inst_app = (Button) findViewById(R.id.bt_inst_app);
bt_inst_app.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder quick_links_alert = new AlertDialog.Builder(MainActivity.this);
quick_links_alert.setTitle("Edit Quick Links");
LinearLayout quick_links_layout = new LinearLayout(MainActivity.this);
quick_links_layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams quick_links_layoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
quick_links_layoutparams.setMargins(20, 0, 30, 0);
gridView = new GridView(MainActivity.this);
installedApps = getInstalledApps();
final GridViewAdapter gridViewAdapter = new GridViewAdapter(MainActivity.this, installedApps);
gridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
gridView.setAdapter(gridViewAdapter);
gridView.setNumColumns(5);
quick_links_alert.setView(gridView);
quick_links_alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final List<AppList> mArrayProducts = gridViewAdapter.getCheckedItems();
final QuickLinksGridViewAdaptor selected_apps = new QuickLinksGridViewAdaptor(MainActivity.this, mArrayProducts);
gv_shortcut.setAdapter(selected_apps);
gv_shortcut.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = mArrayProducts.get(position).getPackageName();
Intent PackageManagerIntent = getPackageManager().getLaunchIntentForPackage(s);//Here some time getting NULL
startActivity(PackageManagerIntent);
}
});
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
quick_links_alert.show();
}
private List<AppList> getInstalledApps() {
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
//if ((isSystemPackage(p) == false)) {
if (((p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) {
appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
appPackageName = p.applicationInfo.packageName;
res.add(new AppList(icon, appName, appPackageName));
}
}
return res;
}
});
}
}
GridViewAdapter.java
public class GridViewAdapter<T> extends BaseAdapter {
Context mContext;
//private final int length = 9;*/
private LayoutInflater layoutInflater;
List<AppList> listStorage;
MainActivity homeactivity;
private int selectedIndex;
private int selectedColor = Color.parseColor("#1b1b1b");
SparseBooleanArray mSparseBooleanArray;
SharedPreferences settings;
public GridViewAdapter(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
listStorage = customizedListView;
mSparseBooleanArray = new SparseBooleanArray();
}
public void setSelectedIndex(int ind) {
selectedIndex = ind;
notifyDataSetChanged();
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> mTempArry = new ArrayList<T>();
for (int i = 0; i < listStorage.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add((T) listStorage.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return listStorage.size();
}
public Object getItem(int position) {
return listStorage.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.add_apps_grid_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.item_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.item_type);
listViewHolder.tvPkgName = (TextView) convertView.findViewById(R.id.tvPack);
listViewHolder.select_app = (CheckBox) convertView.findViewById(R.id.select_app);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
listViewHolder.tvPkgName.setText(listStorage.get(position).getPackageName());
listViewHolder.select_app.setTag(position);
listViewHolder.select_app.setChecked(mSparseBooleanArray.get(position));
final AppList item = listStorage.get(position);
listViewHolder.textInListView.setText(item.getName());
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
boolean Checked = settings.getBoolean(item.getName(), false);
listViewHolder.select_app.setChecked(Checked);
listViewHolder.select_app.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(mContext, "pkg name==" + listStorage.get(position).getPackageName(), Toast.LENGTH_LONG).show();
if (listViewHolder.select_app.isChecked() == true) {
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
// Toast.makeText(mContext, "You deselected " + Context.MODE_PRIVATE, Toast.LENGTH_SHORT).show();
mSparseBooleanArray.put((Integer) buttonView.getTag(), settings.edit().putBoolean(item.getName(), true).commit());
// Toast.makeText(mContext, "You selected " + item.getName(), Toast.LENGTH_SHORT).show();
} else {
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
mSparseBooleanArray.put((Integer) buttonView.getTag(), settings.edit().putBoolean(item.getName(), false).commit());
// Toast.makeText(mContext, "You deselected " + item.getName(), Toast.LENGTH_SHORT).show();
}
// Toast.makeText(mContext, "Shared prefernce---->" + mContext.toString(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
};
static class ViewHolder {
TextView textInListView, tvPkgName;
ImageView imageInListView;
CheckBox select_app;
}
}
AppList.java
public class AppList implements Parcelable {
private String name;
private String packageName;
Drawable icon;
private boolean selected;
public AppList(Drawable icon, String name, String packageName) {
this.name = name;
this.icon = icon;
this.packageName = packageName;
}
protected AppList(Parcel in) {
name = in.readString();
packageName = in.readString();
selected = in.readByte() != 0;
}
public static final Creator<AppList> CREATOR = new Creator<AppList>() {
#Override
public AppList createFromParcel(Parcel in) {
return new AppList(in);
}
#Override
public AppList[] newArray(int size) {
return new AppList[size];
}
};
public String getName() {
return name;
}
public String getPackageName() {
return packageName;
}
public Drawable getIcon() {
return icon;
}
public String toString() {
return name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(packageName);
parcel.writeByte((byte) (selected ? 1 : 0));
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
QuickLinksGridViewAdaptor.java
public class QuickLinksGridViewAdaptor<T> extends BaseAdapter {
private Context context;
//private final int length = 9;*/
private LayoutInflater layoutInflater;
List<AppList> listStorage;
MainActivity homeactivity;
private int selectedIndex;
SparseBooleanArray mSparseBooleanArray;
int num = 1;
public QuickLinksGridViewAdaptor(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
mSparseBooleanArray = new SparseBooleanArray();
}
public void setSelectedIndex(int ind) {
selectedIndex = ind;
notifyDataSetChanged();
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> mTempArry = new ArrayList<T>();
for (int i = 0; i < listStorage.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add((T) listStorage.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
//return 8;
if(num*8 >= listStorage.size()){
return listStorage.size();
}else{
return num*8;
}
}
public Object getItem(int position) {
return listStorage.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.add_apps_grid_item1, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.item_name1);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.item_type1);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
return convertView;
}
static class ViewHolder {
TextView textInListView;
ImageView imageInListView;
}
}
You can either use savedInstanceState method to save and retrieve data in an Activity or You can save the boolean check value every time you change the value of your selection(either selected or non selected state) into SharedPreferences using key as name/id of the value to be selected, and value as true or false.
You can easily check the shared preferences then, to check whether this value is present in shared preferences or not. And use Boolean value to show the selection.
Hope you get this answer.

StickyListHeadersListView MultiChoiceMode issue

I am using the StickyListHeadersListView android library from github for my application. It was working fine. After I implement MultiChoiceMode listener for copying and deleting elements, there is a problem in highlighting of elements.
Whenever I select an element and scroll up and down, some Section Headers are highlighted automatically like shown in the image below
How to avoid this behaviour. Is there any steps I'm missing? Need some hand in resolving the issue.
My Adapter which extends the StickyListHeadersAdapter is given below
public class MessageStickyAdapter extends BaseAdapter implements StickyListHeadersAdapter, SectionIndexer {
private final Context mContext;
private List<Msg> messages;
private int[] mSectionIndices;
private String[] mSectionDates;
private LayoutInflater mInflater;
public MessageStickyAdapter(Context context,List<Msg> listMessages) {
mContext = context;
mInflater = LayoutInflater.from(context);
messages = listMessages;
mSectionIndices = getSectionIndices();
mSectionDates = getSectionDates();
}
private int[] getSectionIndices() {
ArrayList<Integer> sectionIndices = new ArrayList<>();
String lastDate = messages.get(0)._msg_date;
sectionIndices.add(0);
for (int i = 1; i < messages.size(); i++) {
if (!messages.get(i)._msg_date.equalsIgnoreCase(lastDate)) {
Log.d("LastDate,Newdate",lastDate + ',' +messages.get(i)._msg_date);
lastDate = messages.get(i)._msg_date;
sectionIndices.add(i);
}
}
int[] sections = new int[sectionIndices.size()];
for (int i = 0; i < sectionIndices.size(); i++) {
sections[i] = sectionIndices.get(i);
}
Log.d("Sections",String.valueOf(sections.length));
return sections;
}
private String[] getSectionDates() {
String[] dates = new String[mSectionIndices.length];
for (int i = 0; i < mSectionIndices.length; i++) {
dates[i] = messages.get(i)._msg_date;
Log.d("Dates",dates[i]);
}
return dates;
}
#Override
public int getCount() {
return messages.size();
}
#Override
public Object getItem(int position) {
return messages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.right, parent, false);
holder.text = (TextView) convertView.findViewById(R.id.msgr);
holder.time = (TextView) convertView.findViewById(R.id.tim);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.text.setText(URLDecoder.decode( messages.get(position)._msg_content, "UTF-8"));
holder.text.setTag(messages.get(position).getMsgID());
holder.time.setText(messages.get(position)._msg_time);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return convertView;
}
#Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
if (convertView == null) {
holder = new HeaderViewHolder();
convertView = mInflater.inflate(R.layout.date_separator, parent, false);
holder.text = (TextView) convertView.findViewById(R.id.textSeparator);
convertView.setTag(holder);
} else {
holder = (HeaderViewHolder) convertView.getTag();
}
String headerText = messages.get(position)._msg_date;
holder.text.setText(headerText);
return convertView;
}
/**
* Remember that these have to be static, postion=1 should always return
* the same Id that is.
*/
#Override
public long getHeaderId(int position) {
// return the first character of the country as ID because this is what
// headers are based upon
return getSectionForPosition(position);
}
#Override
public int getPositionForSection(int section) {
if (mSectionIndices.length == 0) {
return 0;
}
if (section >= mSectionIndices.length) {
section = mSectionIndices.length - 1;
} else if (section < 0) {
section = 0;
}
return mSectionIndices[section];
}
#Override
public int getSectionForPosition(int position) {
for (int i = 0; i < mSectionIndices.length; i++) {
if (position < mSectionIndices[i]) {
return i - 1;
}
}
return mSectionIndices.length - 1;
}
#Override
public Object[] getSections() {
return mSectionDates;
}
public void clear() {
messages.clear();
mSectionIndices = new int[0];
mSectionDates = new String[0];
notifyDataSetChanged();
}
public void restore(List<Msg> newMessages)
{
messages.clear();
mSectionIndices = new int[0];
mSectionDates = new String[0];
messages = newMessages;
mSectionIndices = getSectionIndices();
mSectionDates = getSectionDates();
notifyDataSetChanged();
}
public void add(Msg newMessage)
{
messages.add(0,newMessage);
mSectionIndices = getSectionIndices();
mSectionDates = getSectionDates();
}
class HeaderViewHolder {
TextView text;
}
class ViewHolder {
TextView text;
TextView time;
}
}

Using ListActivity in Fragment

The below code is running the custom listview implemented in a seperate project.
public class MainActivity extends ListActivity implements OnTouchListener{
private MyCustomAdapter mAdapter;
Activity temp = this;
String []s = new String[500];
ArrayList<GS> q = new ArrayList<GS>();
ListView lv;
int count=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
if (!db.checkDatabase())
{
db.createDatabase(getApplicationContext());
}
db.openDatabase();
q = db.getData();
mAdapter = new MyCustomAdapter();
mAdapter.addSeparatorItem(new ContentWrapper(q.get(0).getA_name(),null));
mAdapter.addItem(new ContentWrapper(q.get(0).getAS_name(), q.get(0).getDesc_art()));
for (int i = 1; i < 460; i++) {
if (!(q.get(i).getA_name().trim().equals(q.get(i-1).getA_name().trim()))) {
mAdapter.addSeparatorItem(new ContentWrapper(q.get(i).getA_name(), null));
}
mAdapter.addItem(new ContentWrapper(q.get(i).getAS_name(), q.get(i).getDesc_art()));
}
setListAdapter(mAdapter);
}
//Adapter Class
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<ContentWrapper> mData = new ArrayList<ContentWrapper>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(ContentWrapper value) {
mData.add(value);
notifyDataSetChanged();
}
public void addSeparatorItem(ContentWrapper value) {
mData.add(value);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public ContentWrapper getItem(int position) {
return mData.get(position);
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount() {
return mData.size();
}
public long getItemId(int position) {
Log.v("getItemId Position", ""+position);
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.activity_main1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.activity_main2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
count++;
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
} holder.textView.setText(mData.get(position).getItem());
if (type == TYPE_ITEM) {
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder x = new AlertDialog.Builder(temp);
Log.v("position",""+position);
x.setIcon(R.drawable.ic_launcher)
// .setTitle(q.get(position-count).getAS_name())
.setTitle(mData.get(position).getItem())
// .setMessage(q.get(position-count).getDesc_art())
.setMessage(mData.get(position).getItemDescription())
.setCancelable(true)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg,
int arg1) {
}
});
AlertDialog a = x.create();
a.show();
}
});
} else {
holder.textView.setOnClickListener(null);
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
Now I want it to be running the same in my App with Fragment.
I just know that using fragment = new ContentsFragment(); initiates it in fragment.
should it be extending ListFragment with a default constructor & an onCreateView(...) which I have inflated the another activities
I am new to fragments & i don't know what things should be changed in the code.
Please help !
EDIT:
I am showing my implemented code of what i have tried & i am getting 4 errors which are have specified in the code:
public class ContentsFragment extends Fragment implements OnTouchListener{
private MyCustomAdapter mAdapter;
Activity temp = this;// error: Type mismatch: cannot convert from ContentsFragment to Activity
String []s = new String[500];
ArrayList<GS> q = new ArrayList<GS>();
ListView lv;
int count=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());//error :The method getApplicationContext() is undefined for the type ContentsFragment
if (!db.checkDatabase())
{
db.createDatabase(getApplicationContext());//error : The method getApplicationContext() is undefined for the type ContentsFragment
}
db.openDatabase();
q = db.getData();
mAdapter = new MyCustomAdapter();
mAdapter.addSeparatorItem(new ContentWrapper(q.get(0).getA_name(),null));
mAdapter.addItem(new ContentWrapper(q.get(0).getAS_name(), q.get(0).getDesc_art()));
for (int i = 1; i < 460; i++) {
if (!(q.get(i).getA_name().trim().equals(q.get(i-1).getA_name().trim()))) {
mAdapter.addSeparatorItem(new ContentWrapper(q.get(i).getA_name(), null));
}
mAdapter.addItem(new ContentWrapper(q.get(i).getAS_name(), q.get(i).getDesc_art()));
}
setListAdapter(mAdapter); //error : The method getApplicationContext() is undefined for the type ContentsFragment
}
//Adapter Class
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<ContentWrapper> mData = new ArrayList<ContentWrapper>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(ContentWrapper value) {
mData.add(value);
notifyDataSetChanged();
}
public void addSeparatorItem(ContentWrapper value) {
mData.add(value);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public ContentWrapper getItem(int position) {
return mData.get(position);
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount() {
return mData.size();
}
public long getItemId(int position) {
Log.v("getItemId Position", ""+position);
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.activity_main1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.activity_main2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
count++;
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
} holder.textView.setText(mData.get(position).getItem());
if (type == TYPE_ITEM) {
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder x = new AlertDialog.Builder(temp);
Log.v("position",""+position);
x.setIcon(R.drawable.ic_launcher)
// .setTitle(q.get(position-count).getAS_name())
.setTitle(mData.get(position).getItem())
// .setMessage(q.get(position-count).getDesc_art())
.setMessage(mData.get(position).getItemDescription())
.setCancelable(true)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg,
int arg1) {
}
});
AlertDialog a = x.create();
a.show();
}
});
} else {
holder.textView.setOnClickListener(null);
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
setListAdapter is a method of ListFragment. So you need to extend ListFragment to use the same.
Change this
mAdapter = new MyCustomAdapter();
to
mAdapter = new MyCustomAdapter(getActivity());
And Then
public MyCustomAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}

ListFragment error

I have a list in a "listview" to scroll the list using this mess,
grouping and the list has a header with icons.
public class MyCustomAdapter extends BaseAdapter {
private static final String ASSETS_DIR = "images/";
private static final int TYPE_HEAD = -1;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private Context ctx;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context context) {
this.ctx = context;
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public void addHeadItem(){
mData.add("");
mSeparatorsSet.add(0);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
//return equipos.size();
}
#Override
public String getItem(int position) {
return mData.get(position) ;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemViewType(int position) {
if (position==0)
return TYPE_HEAD;
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView
+ " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.list_item, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
holder.textView2 = (TextView) convertView.findViewById(R.id.textView2);
holder.textView3 = (TextView) convertView.findViewById(R.id.textView3);
holder.imageView1 = (ImageView) convertView.findViewById(R.id.imageView1);
String[] datos = mData.get(position).split("-");
holder.textView1.setText(String.format(" %s - %s", datos[0],datos[1]));
holder.textView2.setText(datos[2]);
holder.textView3.setText(datos[3]);
String sel_bandera = datos[4].trim() ;
String imgFilePath = "";
if (sel_bandera.equals("verde")){
imgFilePath = ASSETS_DIR + "circle_green.png" ;
}else if (sel_bandera.equals("amarilla")){
imgFilePath = ASSETS_DIR + "circle_yellow.png";
}else {
imgFilePath = ASSETS_DIR + "circle_red.png";
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(this.ctx.getResources().getAssets().open(imgFilePath));
holder.imageView1.setImageBitmap(bitmap);
//bandera.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.list_group, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textSeparator);
holder.textView1.setText(mData.get(position));
break;
case TYPE_HEAD:
convertView = mInflater.inflate(R.layout.list_head, null);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
public static class ViewHolder {
public TextView textView1;
public TextView textView2;
public TextView textView3;
public ImageView imageView1;
public TextView getTextView1() {
return textView1;
}
public void setTextView1(TextView textView1) {
this.textView1 = textView1;
}
public TextView getTextView2() {
return textView2;
}
public void setTextView2(TextView textView2) {
this.textView2 = textView2;
}
public TextView getTextView3() {
return textView3;
}
public void setTextView3(TextView textView3) {
this.textView3 = textView3;
}
public ImageView getImageView1() {
return imageView1;
}
public void setImageView1(ImageView imageView1) {
this.imageView1 = imageView1;
}
}
}
public class EquiposActivity extends ListFragment implements OnTouchListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mAdapter = new MyCustomAdapter(getActivity());
if (lista.length > 0) {
String[] datos = lista[0].split("-");
cabecera_grupo = datos[4];
}
mAdapter.addHeadItem();
for (int i = 0; i < lista.length; i++) {
String[] datos = lista[i].split("-");
String grupo = datos[4];
if (i == 0) {
mAdapter.addSeparatorItem(grupo.replace("_", " "));
}
if (!grupo.equals(cabecera_grupo)) {
mAdapter.addSeparatorItem(grupo.replace("_", " "));
cabecera_grupo = grupo;
}
mAdapter.addItem(String.format("%s - %s - %s - %s - %s",
datos[0], datos[1], datos[2], datos[3], datos[5]));
}
setListAdapter(mAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
I suggest you to rewrite your getView() method, because I think that you are wrongly using ViewHolder pattern. Read this: http://www.jmanzano.es/blog/?p=166
Or just get rid of ViewHolder and code getView() without it.

Categories

Resources