android Use own Image in ListView - android

I have 10 graphic needs to display in my ListView
and I create a class like this
public class LayoutAdapterObj {
public String addString;
public ImageView leftImage;
public String backgroundImageName;
public LayoutAdapterObj(String addString,ImageView leftImageName,String backgroundImageName){
this.addString = addString;
this.leftImage = leftImageName;
this.backgroundImageName = backgroundImageName;
}
and when I create a LayoutAdaptor object
I do this
aArray.add(new LayoutAdapterObj("1",new ImageView(null, null, R.drawable.frame1),"R.drawable.layout"));
aArray.add(new LayoutAdapterObj("2",new ImageView(null, null, R.drawable.frame2),"R.drawable.layout"));
LayoutListAdapter m_adapter;
m_adapter = new LayoutListAdapter(this, R.layout.topbarlayout, aArray);
after that.... in my adapter class, i do this
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.layout1, null);
}
LayoutAdapterObj o = items.get(position);
if (o != null) {
TextView addText = (TextView) v.findViewById(R.id.addtext);
ImageView leftImage=(ImageView)v.findViewById(R.id.layoutframe);
if(!o.backgroundImageName.equals(""))
{
}
if(addText!=null)
{
addText.setText(o.addString);
}
the wrong message is like this
java.lang.IllegalStateException: Could not execute method of the activity
if(leftImage != null)
{
leftImage= o.leftImage;
}

see this...example...`
class UserListAdapter extends ArrayAdapter<String>
{
#Override
public int getCount() {
// TODO Auto-generated method stub
int temp;
if(SharedVariables.is_traffic_search_ON_flag){
temp=search_cases_trafficTicketsList.size();
}else{
temp=search_cases_criminalTicketsList.size();
}
return temp;
}
Activity context;
public UserListAdapter(Activity context) {
super(context, 0);
Log.d("hh","sgbdfjfdgfk");
this.context = context;
}
class ViewHolder {
RelativeLayout rl2;
ImageView genderimage;
TextView ticketcounttt;
TextView name;
TextView city;
TextView added_date;
}
#SuppressWarnings("unused")
public View getView(final int position, View convertView, ViewGroup parent){//here we inflating the layout "R.layout.cars_row"
ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
if(SharedVariables.is_traffic_search_ON_flag)rowView = inflater.inflate(R.layout.traffic_row, null, true);
else rowView = inflater.inflate(R.layout.criminal_row, null, true);
holder = new ViewHolder();
holder.rl2=(RelativeLayout) rowView.findViewById(R.id.rl2);
try{
holder.genderimage=(ImageView) rowView.findViewById(R.id.genderimage);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
holder.ticketcounttt=(TextView) rowView.findViewById(R.id.ticketcounttt);
holder.name=(TextView) rowView.findViewById(R.id.textView1);
holder.city=(TextView) rowView.findViewById(R.id.textView2);
holder.added_date=(TextView) rowView.findViewById(R.id.textView333);
//Traffic cases...
if(SharedVariables.is_traffic_search_ON_flag)
{
if(search_cases_trafficTicketsList.get(position).CaseID!=0)holder.rl2.setBackgroundResource(R.drawable.green_color1); //Pink color...
else holder.rl2.setBackgroundResource(R.drawable.pink_color); //Green color...
if(search_cases_trafficTicketsList.get(position).Sex.equals("M"))holder.genderimage.setBackgroundResource(R.drawable.man);
else holder.genderimage.setBackgroundResource(R.drawable.woman);
holder.ticketcounttt.setTypeface(SharedVariables.font);
holder.name.setTypeface(SharedVariables.font);
holder.city.setTypeface(SharedVariables.font);
holder.added_date.setTypeface(SharedVariables.font);
holder.name.setText(search_cases_trafficTicketsList.get(position).FirstName+" "+search_cases_trafficTicketsList.get(position).LastName);
holder.city.setText(search_cases_trafficTicketsList.get(position).City+" City"+"("+search_cases_trafficTicketsList.get(position).ZIP+")");
try{
String s[]=search_cases_trafficTicketsList.get(position).ViolationDate.split("/");
String month=SharedVariables.convertFromNumberToMonth(Integer.parseInt(s[0]));
String day=s[1];
String year=s[2].substring(0,4);
holder.added_date.setText("Added: "+Integer.parseInt(day)+" "+month+" "+year);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
try{
holder.ticketcounttt.setText(""+search_cases_trafficTicketsList.get(position).Violations.split(",").length);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
//Criminal casess...
else{
if(search_cases_criminalTicketsList.get(position).CaseID!=0)holder.rl2.setBackgroundResource(R.drawable.green_color1); //Pink color...
else holder.rl2.setBackgroundResource(R.drawable.pink_color); //Green color...
holder.ticketcounttt.setTypeface(SharedVariables.font);
holder.name.setTypeface(SharedVariables.font);
holder.city.setTypeface(SharedVariables.font);
holder.added_date.setTypeface(SharedVariables.font);
holder.name.setText(search_cases_criminalTicketsList.get(position).FirstName+" "+search_cases_criminalTicketsList.get(position).LastName);
holder.city.setText(search_cases_criminalTicketsList.get(position).City+" City");
try{
String s[]=search_cases_criminalTicketsList.get(position).ViolationDate.split("/");
String month=SharedVariables.convertFromNumberToMonth(Integer.parseInt(s[0]));
String day=s[1];
String year=s[2].substring(0,4);
holder.added_date.setText("Added: "+Integer.parseInt(day)+" "+month+" "+year);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
try{
holder.ticketcounttt.setText(""+search_cases_criminalTicketsList.get(position).Violations.split(",").length);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
rowView.setTag(holder);
}
else
{
holder = (ViewHolder) rowView.getTag();
}
return rowView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}`
call your adapter like this
UserListAdapter a=new UserListAdapter();
yurlistview.setAdapter(a);

Related

Result asyntask execute cant load fast and value change after scroll listview

I have adapter and inside adapter there are asyntask. Show layout badge cant load fast and when i scroll value change randomly.
My adapter
private class MyAdapter extends ArrayAdapter<MyClass> {
ConvertView holder = null;
public MyAdapter(Context context, int resource, int textViewResourceId, List<MyClass> objects) {
super(context, resource, textViewResourceId, objects);
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return myclassList.size();
}
public MyClass getItem(int position) {
return myclassList.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final TextView txtTestKode, txtTestName, txtTestStatus;
final RelativeLayout layoutBadge;
final MyClass data = getItem(position);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_test_transaction, null, false);
holder = new ConvertView(convertView);
convertView.setTag(holder);
} else {
holder = (ConvertView) convertView.getTag();
}
txtTestKode = holder.getTxtTestKode();
txtTestName = holder.getTxtTestName();
txtTestStatus = holder.getTxtTestStatus();
new AsyncTask<String, Void, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String url = "my_url";
WebRequestPost req = new WebRequestPost(url);
req.execute();
BufferedReader reader = new BufferedReader(new InputStreamReader(req.getResultStream()));
String result = reader.readLine();
reader.close();
req.closeStream();
return result;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (SQLiteConstraintException e) {
e.printStackTrace();
} catch (SQLiteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
if (results != null) {
if (Integer.parseInt(results) > 0) {
holder.getLayoutBadge().setVisibility(View.VISIBLE);
}
}
}
}.execute();
return convertView;
}
}
and:
public static class ConvertView {
private View row;
private RelativeLayout layoutBadge;
public ConvertView(View row) {
this.row = row;
}
public RelativeLayout getLayoutBadge() {
if (layoutBadge == null) {
layoutBadge = (RelativeLayout) row.findViewById(R.id.layoutBadge);
}
return layoutBadge;
}
}
Thanks
you should not do these kinds of task in adapter. what is happening is the data is being fetched asynchronous and may be available in any time later (changing data randolmly). adapter continues to loading other rows data and dont wait for each rows task to be finished becuase you are doing it asynchronous.
the best practice is to provide data before creating the adapter and send the data as a list to adapter as a constructor argument.

dynamic listview adding “Load more items” at the end of scroll

I have a listview fetching data from sql database by Json.
I want to turn it into dynamic listview that at the end of scroll, a "load more items" appears in the footer of the list while loading more items and adding them to the adapter (for example 10 items each time). I have problem in implementing this feature. Please help me with it.Thankx.
Activity Class:
public class MoreVideos extends ListActivity {
int i =1;
private int dateCode = 1;
private ListArrayAdapter listAdapter = null;
private ProgressDialog pDialog = null;
private String id;
#SuppressWarnings("unused")
ArrayList<videoDto> aryLists =null;
String getDate;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.more_video);
id=getIntent().getStringExtra("id");
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setMessage("Loading....");
pDialog.setCancelable(true);
loadCategoriesAsync();
};
// TODO Auto-generated method stub
protected void loadCategoriesAsync() {
loadCategoriesTaskHandler task = new loadCategoriesTaskHandler();
if (Build.VERSION.SDK_INT >= 11)
{
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else
{
task.execute();
}
}
class loadCategoriesTaskHandler extends AsyncTask<videoDto, Void, String>
{
#Override
protected String doInBackground(videoDto... params)
{
String results= "";
try
{
videoDto videodto=new videoDto();
// healthDto.getInfom(strEail.trim(),strPassword,getApplicationContext());
aryLists = new ArrayList<videoDto>();
aryLists= videodto.getvideo(id);
}
catch (Exception e)
{
e.printStackTrace();
}
return results;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(aryLists!=null){
listAdapter = new ListArrayAdapter(getApplicationContext(), MoreVideos.this,
aryLists);
setListAdapter(listAdapter);
}else{
Toast.makeText(getApplicationContext(), "ArrayList is null ", Toast.LENGTH_SHORT).show();
}
}
}
Adapter Class:
public class ListArrayAdapter extends ArrayAdapter<videoDto> {
private final Context context;
private MoreVideos _parent;
public ListArrayAdapter(Context context, MoreVideos parent,
ArrayList<videoDto> aryLog) {
super(context, R.layout.video_listing, aryLog);
this.context = context;
this._parent = parent;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflate.inflate(R.layout.video_listing,
null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.index = (TextView) rowView
.findViewById(R.id.index);
viewHolder.NameOfVideo = (TextView) rowView
.findViewById(R.id.txt_name_video);
viewHolder.img = (ImageView) rowView
.findViewById(R.id.img_video);
viewHolder.rel= (RelativeLayout) rowView.findViewById(R.id.click);
viewHolder.bookv = (ImageView)rowView.findViewById(R.id.bookv);
//viewHolder.download = (ImageView)rowView.findViewById(R.id.download);
rowView.setTag(viewHolder);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
final videoDto userLog = (this._parent != null) ? this._parent.listAdapter
.getItem(position) : null;
String currentPosition = Integer.toString(position);
if (userLog != null) {
try {
try {
/* if(currentPosition.equals(""))
{
holder.index.setText("-----");
}
else
{
holder.index.setText(Integer.toString(Integer.parseInt(currentPosition) + 1));
}*/
holder.rel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name =userLog.link ;
/*try {
MediaPlayer player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource("http://xty/MRESC/images/test/xy.mp3");
player.prepare();
player.start();
} catch (Exception e) {
// TODO: handle exception
}*/
//Log.v("String ", speaker.vid);
Intent mainIntent = new Intent(getApplicationContext(),VideoViewActivity.class);
mainIntent.putExtra("IMGNAME", name);
//Log.v("name",name);
// startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(name)));
startActivity(mainIntent);
}
});
holder.bookv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// String jobId = (String) v.getTag();
String name =userLog.link ;
videoDto videodto = (videoDto) v.getTag();
Intent intentJobApplicants = new Intent(getApplicationContext(),VideoViewActivity.class);
intentJobApplicants.putExtra("IMGNAME",name);
// intentJobApplicants.putExtra("JobId", jobAp.id);
startActivity(intentJobApplicants);
}
});
if (userLog.VideoText.equals("")) {
holder.NameOfVideo.setText("-----");
} else {
holder.NameOfVideo.setText(userLog.VideoText);
}
i=i+1;
Log.v("i",String.valueOf(i));
} catch (Exception ex) {
// Toast.makeText(context, ex.getMessage(),
// Toast.LENGTH_SHORT).show();
}
if (position % 2 == 0) {
rowView.setBackgroundColor(Color.LTGRAY);
} else {
rowView.setBackgroundColor(Color.WHITE);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
return rowView;
}
}
}
View Holder Class:
public static class ViewHolder {
protected TextView index;
protected ImageView bookv;
protected ImageView img;
protected ImageView download;
protected TextView NameOfVideo;
protected RelativeLayout rel;
}

Android - package manager disable/enable

I have a problem with disable application through package manager function disable/enable.
In android terminal is all corect, but in this application not. However " Runtime.getRuntime().exec("su"); " functioning normally and carrying out his activity.
public class AppInfoAdapter extends BaseAdapter {
private Context aContext;
private List<ApplicationInfo> aListAppInfo;
private PackageManager aPackManager;
private CheckBox chAppStat ;
public AppInfoAdapter(Context c, List<ApplicationInfo> list, PackageManager pm) {
aContext = c;
aListAppInfo = list;
aPackManager = pm;
}
#Override
public int getCount() {
return aListAppInfo.size();
}
#Override
public Object getItem(int position) {
return aListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ApplicationInfo entry = aListAppInfo.get(position);
//positon = position;
View v = convertView; // convertView
// recyklovace
if(v == null) {
LayoutInflater inflater = LayoutInflater.from(aContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
}
// nahrat layout
ImageView ivAppIcon = (ImageView)v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView)v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView)v.findViewById(R.id.tvPack);
chAppStat = (CheckBox)v.findViewById(R.id.chBox);
//text = entry.packageName;
chAppStat.setTag(entry.packageName);
chAppStat.setOnCheckedChangeListener(aListener);
// privest na vystup
ivAppIcon.setImageDrawable(entry.loadIcon(aPackManager));
tvAppName.setText(entry.loadLabel(aPackManager));
tvPkgName.setText(entry.packageName);
// navrat view
return v;
}
OnCheckedChangeListener aListener = new CompoundButton.OnCheckedChangeListener () {
public void onCheckedChanged( CompoundButton buttonView, boolean isChecked) {
if(isChecked = true){
try {
Runtime.getRuntime().exec("su");
Runtime.getRuntime().exec("pm disable "+ buttonView.getTag());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
try {
Runtime.getRuntime().exec("pm enable "+ buttonView.getTag());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
}
recapitulation: problem is package manager function disable/enable in the application. BUT in terminal is correct "pm disable some.name.package"
try {
Runtime.getRuntime().exec("su");
Runtime.getRuntime().exec("pm disable "+ buttonView.getTag());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Android ListView the gallery shows in wrong places

When I use listview with adapter which add a gallery in the view and the gallery adapter loads the image loads the image with asynctask the gallery shows in different places.
public View getView(int position, View convertView, ViewGroup parent) {
final int myPosition = position;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
boolean isConverted = false;
switch(typeOfCell.get(position))
{
case 0:
if(convertView == null)
{
rowView = inflater.inflate(R.layout.newstextcelladapter, parent, false);
}
else
{
rowView = convertView;
}
break;
case 1:
if(convertView == null)
{
rowView = inflater.inflate(R.layout.newsimagecelladapter, parent, false);
}
else
{
rowView = convertView;
isConverted = true;
}
Gallery gallery = (Gallery) rowView.findViewById(R.id.newsImageGallery);
try{
gallery.setAdapter(this.adaptersForGallery.get(position));
Log.w("Adapter used", "" + this.adaptersForGallery.get(position));
Log.w("URL used", "" + this.adaptersForGallery.get(position).mImageIds.get(0));
gallery.setHorizontalFadingEdgeEnabled(false);
gallery.setVisibility(View.GONE);
gallery.setVisibility(View.VISIBLE);
}
catch(Exception e)
{
#SuppressWarnings("unused")
int a =1;
Log.w("FATAL","ERROR");
}
rowView.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
View view2 = new View(MainActivity.context);
DetailsImageNews.setView(MainActivity.dataBase.getCommentsForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getAuthorForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getDateForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getTimeForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getDetailedTextForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.dataBase.getTitleForNews(MainActivity.existingForNews.get(myPosition)),
MainActivity.detailImageNews,
adaptersForGallery.get(myPosition)
,view2);
while (MainActivity.currentViewPosition != 1) {
MainActivity.mContainer.showNext();
Log.w("position", "" + MainActivity.currentViewPosition);
if (MainActivity.currentViewPosition > 2) {
MainActivity.currentViewPosition = 0;
}
MainActivity.currentViewPosition += 1;
}
}
});
break;
case 2:
if(convertView == null)
{
rowView = inflater.inflate(R.layout.newsvideocelladapter, parent, false);
}
else
{
rowView = convertView;
}
Uri uri=Uri.parse(videoUrls.get(position));
VideoView video = (VideoView) rowView.findViewById(R.id.newsVideo);
video.setVideoURI(uri);
break;
default:
if(convertView == null)
{
rowView = inflater.inflate(R.layout.newstextcelladapter, parent, false);
}
else
{
rowView = convertView;
}
break;
}
TextView titleView = (TextView) rowView.findViewById(R.id.newsTitleView);
TextView dateView = (TextView) rowView.findViewById(R.id.newsDateView);
TextView timeView = (TextView) rowView.findViewById(R.id.newsTimeView);
TextView commentsView = (TextView) rowView.findViewById(R.id.newsCommentView);
titleView.setText(this.title.get(position));
dateView.setText(this.date.get(position));
timeView.setText(this.time.get(position));
commentsView.setText(Integer.toString(this.comments.get(position)));
return rowView;
}
public View getView(int position, View convertView, ViewGroup parent) {
View i ;
ImageView iv;
ProgressBar mProgressBar;
calledGetView+=1;
Log.i("Image View:URL", ""+mImageIds.get(position));
if(convertView == null)
{
i = MainActivity.factory.inflate(R.layout.imagespinner, null);
}
else
{
i = (ImageView) convertView;
}
mProgressBar =(ProgressBar) i.findViewById(R.id.imageProgress);
iv = (ImageView) i.findViewById(R.id.image);
try {
AsycTask task = new AsycTask();
task.url = new URL(mImageIds.get(position));
task.iv = iv;
task.execute(iv);
iv.setAdjustViewBounds(true);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new RelativeLayout.LayoutParams((int) (MainActivity.screenWidth*0.7), (int) ((MainActivity.screenWidth*0.7)*0.6)));
task.globalPosition = currentPosition;
task.mProgressBar = mProgressBar;
if(task.bm == null)
{
}
}
catch (IOException e) {
Log.i("Asyc task", "FATAL ERROR");
e.printStackTrace();
}
return i;
}
public class AsycTask extends AsyncTask<ImageView, Void, Bitmap> {
public Bitmap bm;
public Bitmap bm2;
public int globalPosition;
public ProgressBar mProgressBar;
public int imagePosition;
public ImageView iv;
public URL url;
public Canvas c;
#Override
protected Bitmap doInBackground(ImageView... arg0) {
iv = arg0[0];
//Log.w("Loading url:",""+ url.getPath());
try {
bm2 = BitmapFactory.decodeStream((InputStream) url.getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OutOfMemoryError e) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 2;
o.inDither = false;
o.inPurgeable = true;
try {
bm2 = BitmapFactory.decodeStream(
(InputStream) url.getContent(), null, o);
} catch (IOException e1) {
e1.printStackTrace();
} catch (OutOfMemoryError e1) {
}
}
return bm2;
}
private void updateView(int index){
View v = MainActivity.newsListView.getChildAt(index -
MainActivity.newsListView.getFirstVisiblePosition());
}
#Override
protected void onPostExecute(Bitmap result) {
mProgressBar.setVisibility(View.GONE);
iv.setVisibility(View.GONE);
iv.setVisibility(View.VISIBLE);
BitmapDrawable dr = ((BitmapDrawable) iv.getDrawable());
if (dr != null) {
Bitmap bmForRecyl = dr.getBitmap();
if (bmForRecyl != null) {
bmForRecyl.recycle();
}
}
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setImageBitmap(result);
Log.i("Set", "setted");
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
mProgressBar.incrementProgressBy(5);
}
}
I know for this problem but I dont know how to resolve it for listview with gallery with asyctask.
I think this is because the gallery is not loaded with the new adapter.How to change the adapter?
You need to override getViewItemType.
getViewTypeCount() - this methods returns information how many types of rows do you have in your list
getItemViewType(int position) - returns information which layout type you should use based on position
Then you inflate layout only if it's null and determine type using getItemViewType.
Example :
private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;
private static final int TYPE_ITEM3 = 2;
#Override
public int getItemViewType(int position)
{
int type;
if (position== 0){ // your condition
type = TYPE_ITEM1; //type 0 for image
} else if(position == 1){
type = TYPE_ITEM2; //type 1 for text
}else {
type = TYPE_ITEM3; //type 2 for videos
}
return type;
}
#Override
public int getViewTypeCount() {
return 3; //three different layouts to be inflated
}
In getView
int type= getItemViewType(arg0);
switch (type) {
case TYPE_ITEM1:
// inflate layout for text
break;
case TYPE_ITEM2:
// inflate layout for image
break;
case TYPE_ITEM3:
// inflate layout for video
break;
....
You can check the tutorial below
http://android.amberfog.com/?p=296

Unchecking Checkboxes in Custom Listview

I want to unchecked my all check boxes inside listview on button click.
This my adapter class. It unchecked all check boxes but for that I have to scroll through listview.
When I scroll through it, it unchecked according to the rows that are visible.
public class ExpenseCalculatorAdapter extends ArrayAdapter<String>{
private Activity context;
private static LayoutInflater inflator = null;
private ArrayList<String> data;
private ArrayList<String> values;
DataBaseUtil dbUtils;
public ExpenseCalculatorAdapter(Activity context, ArrayList<String> data){
super(context,R.layout.expenserow, data);
this.context = context;
this.data = data;
dbUtils=new DataBaseUtil(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
String row=data.get(position);
String date;
String type;
String cost;
final String id;
/* result.add(c.getString(iRowid)+"&"+c.getString(iDate)+"~"+c.getString(iCost)+"#"+c.getString(iType)+"*");*/
id=row.substring(0, row.indexOf("&"));
date=row.substring(row.indexOf("&")+1,row.indexOf("~"));
cost=row.substring(row.indexOf("~")+1,row.indexOf("#"));
type=row.substring(row.indexOf("#")+1,row.indexOf("*"));
if(convertView==null)
{
ViewHolder holder = new ViewHolder();
inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.expenserow, null);
holder.togCheck=(CheckBox)convertView.findViewById(R.id.check);
holder.textDate = (TextView) convertView.findViewById(R.id.txtrowDate);
holder.textType = (TextView) convertView.findViewById(R.id.txtrowType);
holder.textCost = (TextView) convertView.findViewById(R.id.txtrowCost);
holder.togCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setAction("clicked");
if(buttonView.isChecked())
{
try
{
dbUtils.open();
dbUtils.setVisibility(id);
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
dbUtils.close();
}
intent.putExtra("isClicked","yes");
intent.putExtra("ID",""+id);
context.sendBroadcast(intent);
}
else
{
try
{
dbUtils.open();
dbUtils.setInVisibility(id);
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
dbUtils.close();
}
intent.putExtra("isClicked","no");
intent.putExtra("ID",""+id);
context.sendBroadcast(intent);
}
}
});
convertView.setTag(holder);
}
ViewHolder hold = (ViewHolder) convertView.getTag();
//setting Data to List
hold.textDate.setText(date);
hold.textType.setText(type);
hold.textCost.setText(cost);
if(CheckReceiver.checkAll)
{
hold.togCheck.setChecked(true);
}
if(!CheckReceiver.checkAll)
{
hold.togCheck.setChecked(false);
}
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
static class ViewHolder{
public CheckBox togCheck;
public TextView textDate;
public TextView textType;
public TextView textCost;
}
}
As Listview recycles view its not possible to do this with only BroadCastReciver. It was really a bad idea.
I done this using Database and BroadCastReciver.
holder.togCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*Intent intent=new Intent();
intent.setAction("clicked")*/;
if(holder.togCheck.isChecked())
{
//holder.togCheck.setBackgroundResource(R.drawable.check);
try
{
dbUtils.open();
dbUtils.setVisibility(id);
// Toast.makeText(context, "Checked ", Toast.LENGTH_SHORT).show();
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
dbUtils.close();
}
intent.putExtra("isClicked","yes");
intent.putExtra("ID",""+id);
context.sendBroadcast(intent);
}
else
{
// holder.togCheck.setBackgroundResource(R.drawable.uncheck);
try
{
dbUtils.open();
dbUtils.setInVisibility(id);
Toast.makeText(context, "UnChecked ", Toast.LENGTH_SHORT).show();
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
dbUtils.close();
}
intent.putExtra("isClicked","no");
intent.putExtra("ID",""+id);
context.sendBroadcast(intent);
}
}
});
what i done is i set the checked or unchecked state of checkbox according to id in database.
Then by fetching state of that id i done calculation!.

Categories

Resources