I have listAdapter of listview and I have set record button in custom adapter. I have put code inside click event of holder.record like
holder.record.setBackgroundResource(R.drawable.record_green);
for set background of that button while user touch.but my problem is when I touch particular list item button this images are apply in another list item
Here are code:
holder.record.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isplaying2 == true) {
} else
{
if (b_Flag_Record_or_not == true) {
} else {
try {
holder.record.setBackgroundResource(R.drawable.record_green);
b_Flag_Record_or_not = true;
b_play_or_not = true;
flag_stop_position = position;
AuthHandler dataHandler = new AuthHandler();
AuthDataset dataset = dataHandler
.getParsednewJobdtl_DataSet();
System.out.println("dataset.getint1();"
+ dataset.getint1());
// Login l = new Login();
String str_useid = RequestTo[position];
recorder = new AudioRecorder("/audiometer/shanesh"
+ RequestId[position] + "-" + str_useid);
start_or_not = true;
recorder.start();
Toast.makeText(context, "Start Recording", Toast.LENGTH_LONG).show();
CountDownTimer countDowntimer = new CountDownTimer(
120000000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try {
Toast.makeText(
context,
"Stop recording Automatically ",
Toast.LENGTH_LONG).show();
recorder.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
countDowntimer.start();
} catch (IOException e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
}catch (Exception e) {
}
}
}
}
});
Update:
public class ListViewAdapter extends BaseAdapter {
public static Activity context;
String title[];
String description[];
String RequestId[];
String Folderpath[];
String RequestTo[];
boolean b_Flag_Record_or_not = false;
boolean b_upload_or_not = false;
boolean start_or_not = false;
boolean start_play = false;
boolean upload_or_not = false;
boolean b_play_or_not = false;
boolean isplaying2 = false;
Thread welcomeThread;
int glob_position;
MediaPlayer mPlayer2;
int flag_stop_position;
AudioRecorder recorder;
AnimationDrawable frameAnimation, frameAnimation_play;
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
Recording login = new Recording();
ViewHolder holder;
MediaPlayer MP_completeRequest = new MediaPlayer();
public ListViewAdapter(Activity context, String[] title,
String[] description, String[] req_id, String[] FolderPath,
String[] Arr_RequestTo) {
super();
this.context = context;
this.title = title;
this.description = description;
this.RequestId = req_id;
this.Folderpath = FolderPath;
this.RequestTo = Arr_RequestTo;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
Button record, stop, play, upload;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = context.getLayoutInflater();
glob_position = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView
.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView
.findViewById(R.id.textView2);
holder.record = (Button) convertView.findViewById(R.id.record);
holder.stop = (Button) convertView.findViewById(R.id.stop);
holder.play = (Button) convertView.findViewById(R.id.play1);
holder.upload = (Button) convertView
.findViewById(R.id.audio_upload);
/* set button image */
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
Typeface face = Typeface.createFromAsset(context.getAssets(),
"fonts/tahoma.ttf");
holder.txtViewTitle.setTypeface(face);
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
Please see Holder is used to reuse views in adapterview, so if a Screen can displays 5 items once, 6th item will reuse item no 1's View, hence holder.
Use ListView.onItemClickListener instead of holder.record.setOnClickListener(), or set background of view into getView method, I am editing your code in getVIew method:
public class ListViewAdapter extends BaseAdapter {
public static Activity context;
String title[];
String description[];
String RequestId[];
String Folderpath[];
String RequestTo[];
boolean b_Flag_Record_or_not = false;
boolean b_upload_or_not = false;
boolean start_or_not = false;
boolean start_play = false;
boolean upload_or_not = false;
boolean b_play_or_not = false;
boolean isplaying2 = false;
Thread welcomeThread;
int glob_position;
MediaPlayer mPlayer2;
int flag_stop_position;
AudioRecorder recorder;
AnimationDrawable frameAnimation, frameAnimation_play;
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
Recording login = new Recording();
ViewHolder holder;
MediaPlayer MP_completeRequest = new MediaPlayer();
public ListViewAdapter(Activity context, String[] title,
String[] description, String[] req_id, String[] FolderPath,
String[] Arr_RequestTo) {
super();
this.context = context;
this.title = title;
this.description = description;
this.RequestId = req_id;
this.Folderpath = FolderPath;
this.RequestTo = Arr_RequestTo;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = context.getLayoutInflater();
glob_position = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView
.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView
.findViewById(R.id.textView2);
/* set button image */
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
Typeface face = Typeface.createFromAsset(context.getAssets(),
"fonts/tahoma.ttf");
holder.txtViewTitle.setTypeface(face);
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
Button record = (Button) convertView.findViewById(R.id.record);
Button stop = (Button) convertView.findViewById(R.id.stop);
Button play = (Button) convertView.findViewById(R.id.play1);
Button upload = (Button) convertView
.findViewById(R.id.audio_upload);
record.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isplaying2 == true) {
} else
{
if (b_Flag_Record_or_not == true) {
} else {
try {
record.setBackgroundResource(R.drawable.record_green);
b_Flag_Record_or_not = true;
b_play_or_not = true;
flag_stop_position = position;
AuthHandler dataHandler = new AuthHandler();
AuthDataset dataset = dataHandler
.getParsednewJobdtl_DataSet();
System.out.println("dataset.getint1();"
+ dataset.getint1());
// Login l = new Login();
String str_useid = RequestTo[position];
recorder = new AudioRecorder("/audiometer/shanesh"
+ RequestId[position] + "-" + str_useid);
start_or_not = true;
recorder.start();
Toast.makeText(context, "Start Recording", Toast.LENGTH_LONG).show();
CountDownTimer countDowntimer = new CountDownTimer(
120000000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try {
Toast.makeText(
context,
"Stop recording Automatically ",
Toast.LENGTH_LONG).show();
recorder.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
countDowntimer.start();
} catch (IOException e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
}catch (Exception e) {
}
}
}
}
});
Related
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;
}
This Is my Adapter problem was scroll listview to change textview value by every position how to solve it ? plus click event to increment one and minus event to decrment and set value in textview (Plus click to quantity + 1 , minus click to quantity - 1).
public class CustomListViewDrycleaning extends BaseAdapter {
ArrayList<ProductModel> myList = new ArrayList<ProductModel>();
LayoutInflater inflater;
Context context;
int loader = R.drawable.loader;
int minteger = 0;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
String rem, b;
private DisplayImageOptions options;
ProductModel currentListData;
String cid, qcount;
public CustomListViewDrycleaning(Context context, ArrayList<ProductModel> list) {
this.myList = list;
this.context = context;
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_launcher) .showImageForEmptyUri(R.drawable.ic_launcher).showImageOnFail(R.drawable.ic_launcher) .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).build();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.customproductlistdrycleaning, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
currentListData = myList.get(position);
mViewHolder.btndropdown.setTag(currentListData.getCategoryId());
mViewHolder.name.setText(currentListData.getName());
mViewHolder.prize.setText("$" + currentListData.getCharge());
mViewHolder.name.setTag(currentListData.getCategoryId());
mViewHolder.plus.setTag(currentListData.getCategoryId());
mViewHolder.minus.setTag(currentListData.getCategoryId());
String img_path = currentListData.getImage();
ImageLoader.getInstance().displayImage(img_path, mViewHolder.imgbucket, options, animateFirstListener);
String servicecheck1 = currentListData.getServiceId1();
String servicecheck2 = currentListData.getServiceId2();
String servicecheck3 = currentListData.getServiceId3();
if (servicecheck1 == null) {
mViewHolder.btndropdown.setVisibility(View.GONE);
} else {
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
}
mViewHolder.btndropdown.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewHolder.lnrbelowdry.setVisibility(View.VISIBLE);
mViewHolder.btndropdown.setVisibility(View.GONE);
mViewHolder.btndropdown1.setVisibility(View.VISIBLE);
}
});
mViewHolder.btndropdown1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewHolder.lnrbelowdry.setVisibility(View.GONE);
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
mViewHolder.btndropdown1.setVisibility(View.GONE);
}
});
if (servicecheck1 == null) {
mViewHolder.btndropdown.setVisibility(View.GONE);
mViewHolder.lnrproduct1.setVisibility(View.GONE);
} else {
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
mViewHolder.lnrproduct1.setVisibility(View.VISIBLE);
mViewHolder.checkBox1.setText(currentListData.getServiceName1());
mViewHolder.txtproductprize1.setText("$" + currentListData.getServiceCharge1());
}
if (servicecheck2 == null) {
mViewHolder.lnrproduct2.setVisibility(View.GONE);
} else {
mViewHolder.lnrproduct2.setVisibility(View.VISIBLE);
mViewHolder.checkBox2.setText(currentListData.getServiceName2());
mViewHolder.txtproductprize2.setText("$" + currentListData.getServiceCharge2());
}
if (servicecheck3 == null) {
mViewHolder.lnrproduct3.setVisibility(View.GONE);
} else {
mViewHolder.lnrproduct3.setVisibility(View.VISIBLE);
mViewHolder.checkBox3.setText(currentListData.getServiceName3());
mViewHolder.txtproductprize3.setText("$" + currentListData.getServiceCharge3());
}
qcount = currentListData.getQuantity();
mViewHolder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Utils.COUNTCARTALIST.add(mViewHolder.name.getTag() + "");
int quantityyp = 0;
for (int m = 0; m < Utils.qtylist.size(); m++) {
String ii = mViewHolder.plus.getTag() + "";
Log.e("", "#ii" + ii);
if (mViewHolder.plus.getTag().equals(Utils.qtylist.get(m).get("categoryId"))) {
Toast.makeText(context, "Match", Toast.LENGTH_SHORT).show();
rem = Utils.qtylist.get(m).get("categoryId");
b = Utils.qtylist.get(m).get("quantity");
quantityyp = Integer.parseInt(b) + 1;
String c = Integer.toString(quantityyp);
mViewHolder.strcount.setText(c);
Utils.qtylist.remove(m);
HashMap<String, String> hashmaplus = new HashMap<String, String>();
hashmaplus.put("categoryId", rem);
hashmaplus.put("quantity", c);
Utils.qtylist.add(hashmaplus);
Log.e("", "#Utils.qtylistadd" + Utils.qtylist);
break;
}
}
}
});
mViewHolder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Utils.COUNTCARTALIST.remove(mViewHolder.name.getTag() + "");
int quantityym = 0;
for (int m = 0; m < Utils.qtylist.size(); m++) {
String ii = mViewHolder.minus.getTag() + "";
Log.e("", "#iiminus" + ii);
if (mViewHolder.minus.getTag().equals(Utils.qtylist.get(m).get("categoryId"))) {
rem = Utils.qtylist.get(m).get("categoryId");
b = Utils.qtylist.get(m).get("quantity");
Log.e("", "#QQQ" + b);
Log.e("", "#rem" + rem);
if (b.equals("0")) {
} else {
quantityym = Integer.parseInt(b) - 1;
String c = Integer.toString(quantityym);
mViewHolder.strcount.setText(c);
Utils.qtylist.remove(m);
HashMap<String, String> hashmapminus = new HashMap<String, String>();
hashmapminus.put("categoryId", rem);
hashmapminus.put("quantity", c);
Utils.qtylist.add(hashmapminus);
break;
}
}
}
}
});
return convertView;
}
private class MyViewHolder {
TextView name, prize, strcount, txtproductprize1, txtproductprize2, txtproductprize3;
Button cart, plus, minus, btndropdown, btndropdown1;
ImageView imgbucket;
LinearLayout lnrbelowdry, lnrproduct1, lnrproduct2, lnrproduct3;
CheckBox checkBox1, checkBox2, checkBox3;
public MyViewHolder(View item) {
name = (TextView) item.findViewById(R.id.txtproductname);
prize = (TextView) item.findViewById(R.id.txtprize);
strcount = (TextView) item.findViewById(R.id.txtcount);
imgbucket = (ImageView) item.findViewById(R.id.imgbucket);
plus = (Button) item.findViewById(R.id.btnplus);
minus = (Button) item.findViewById(R.id.btnminus);
btndropdown = (Button) item.findViewById(R.id.btndropdown);
btndropdown1 = (Button) item.findViewById(R.id.btndropdown1);
lnrbelowdry = (LinearLayout) item.findViewById(R.id.lnrbelowdry);
lnrproduct1 = (LinearLayout) item.findViewById(R.id.lnrproduct1);
lnrproduct2 = (LinearLayout) item.findViewById(R.id.lnrproduct2);
lnrproduct3 = (LinearLayout) item.findViewById(R.id.lnrproduct3);
checkBox1 = (CheckBox) item.findViewById(R.id.checkBox1);
checkBox2 = (CheckBox) item.findViewById(R.id.checkBox2);
checkBox3 = (CheckBox) item.findViewById(R.id.checkBox3);
txtproductprize1 = (TextView) item.findViewById(R.id.txtproductprize1);
txtproductprize2 = (TextView) item.findViewById(R.id.txtproductprize2);
txtproductprize3 = (TextView) item.findViewById(R.id.txtproductprize3);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
You are returning a same ID for each row. try this:
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
Hi i have created a listview,In that i inflated four layout, my data set is images, text,audio and Video. so i inflating the layouts accordingly.Once the data is coming from Api,and images is being cached,and audio video and text is being stored in folder and sqlite respectively. But when i open second time the listview showing the data randomly or sometime unordered. even sometime not showing whole data. here is my adapter's code.
public class ListViewAdapter extends BaseAdapter {
ArrayList<ListModel> myList = new ArrayList<ListModel>();
LayoutInflater inflater;
Context context;
int flag = 0;
private static final int TYPE_ITEM1 = 1;
private static final int TYPE_ITEM2 = 2;
private static final int TYPE_ITEM3 = 3;
private static final int TYPE_ITEM4 = 4;
private String url;
private String vPath;
private MediaPlayer mp;
public ListViewAdapter(Context context, ArrayList<ListModel> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
int type;
#Override
public int getItemViewType(int position) {
ListModel listModel = myList.get(position);
String data = listModel.getType();
if (data.equals("Text")) {
type = TYPE_ITEM1;
} else if (data.equals("Image")) {
type = TYPE_ITEM2;
} else if (data.equals("Audio")) {
type = TYPE_ITEM3;
}else if(data.contains("Video")){
type=TYPE_ITEM4;
}
return type;
}
#Override
public int getViewTypeCount() {
return myList.size() + 1;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListModel getItem(int position) {
// return myList.get(position);
if (position >= myList.size()) {
return null;
}
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder holder = null;
TextView textView = null;
ImageView imageView = null;
VideoView vPlayer = null;
Button pause = null;
Button play = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + v + " type = " + type);
if (v == null) {
holder = new ViewHolder();
if (type == TYPE_ITEM1) {
v = inflater.inflate(R.layout.list_text, null);
textView = (TextView) v.findViewById(R.id.text);
} else if (type == TYPE_ITEM2) {
v = inflater.inflate(R.layout.list_image, null);
imageView = (ImageView) v.findViewById(R.id.imgView);
} else if (type == TYPE_ITEM3) {
v = inflater.inflate(R.layout.list_audio, null);
play = (Button) v.findViewById(R.id.btn_play);
pause = (Button) v.findViewById(R.id.stop);
} else if (type == TYPE_ITEM4) {
v = inflater.inflate(R.layout.list_video, null);
vPlayer = (VideoView) v.findViewById(R.id.video_player);
}
holder.textView = textView;
holder.videoPlayer = vPlayer;
holder.imageView = imageView;
holder.play = play;
holder.stop = pause;
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
ListModel model = myList.get(position);
if (holder.play != null) {
holder.play.setId(position);
}if (holder.videoPlayer!=null){
holder.videoPlayer.setId(position);
}if (holder.stop!=null){
holder.stop.setId(position);
}
String datatype = model.getType();
if (datatype.equals("Text")) {
holder.textView.setText(model.getData());
} else if (datatype.equals("Image")) {
UrlImageViewHelper.setUrlDrawable(holder.imageView, model.getData());
} else if (datatype.equals("Audio")) {
url = model.getData();
}else if (datatype.equals("Video")){
vPath=model.getData();
}
if (holder.play != null) {
holder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = view.getId();
ListModel model = myList.get(i);
String audioUri = model.getData();
new PlayMusicFromPath().execute(audioUri);
}
});
if (holder.stop!=null){
holder.stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});}
if (holder.videoPlayer!=null) {
final ViewHolder finalHolder = holder;
holder.videoPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int videoId = view.getId();
ListModel model1 = myList.get(videoId);
String videoUrl = model1.getData();
finalHolder.videoPlayer.setVideoPath(videoUrl);
}
});
}
}
return v;
}
public static class ViewHolder {
public TextView textView;
public ImageView imageView;
public Button play, stop;
public VideoView videoPlayer;
}
public void audioPlayer(String fileName) {
//set up MediaPlayer
mp = new MediaPlayer();
try {
mp.setDataSource(fileName);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
class PlayMusicFromPath extends AsyncTask<String, String, String> {
// Show Progress bar before downloading Music
#Override
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
}
// Download Music File from Internet
#Override
protected String doInBackground(String... f_url) {
audioPlayer(f_url[0]);
return null;
}
// Once Music File is downloaded
#Override
protected void onPostExecute(String file_url) {
System.out.print(file_url);
}
}
You only set the Button play when type == TYPE_ITEM3, but you always call holder.play.setOnClickListener. Hence you either only call the setOnClickListener method when play is not null, e.i:
if(holder.play != null){
holder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//mycode
}
});
}
Or you always set the play button to a Button object
I have a custom list view where each list item has two buttons, one text view and one seek bar where the seek bar visibility is set to gone in list item's XML.
Now what I want to do is on click of button one in the list item I want to hide the text view and display the seek bar of that list item whose button is clicked and show hide the seek bar and display the text view of all other list items.
The code that I have written works well if the total items are less than the views that can be displayed at once in a list view but for a lot of views this does not works.
What I am doing is load a list of files from a a folder into the list view and play the in the list view only
Please tell me where I am going wrong.
Any help would be appreciated.
My Adapter Code:
public class AudioFileListAdapter extends BaseAdapter {
Context context;
ArrayList<String> fileList;
LayoutInflater inflater;
String folder;
ListView mListView;
public MediaPlayer mPlayer;
public Handler seekHandler;
SeekBar mSeekBar;
int clickedPos = -1;
protected static class RowViewHolder {
public TextView fileName;
public Button filePlay;
public Button rate;
public SeekBar fileSeek;
}
public AudioFileListAdapter(Context context, ArrayList<String> fileList,
String folder) {
this.fileList = fileList;
this.context = context;
this.folder = folder;
mListView = (ListView) ((Activity) context)
.findViewById(R.id.Filelistview);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
seekHandler = new Handler();
}
#Override
public int getCount() {
return fileList.size();
}
#Override
public Object getItem(int position) {
return fileList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.audio_file_list_item, null);
viewHolder = new RowViewHolder();
viewHolder.fileName = (TextView) convertView
.findViewById(R.id.file_name);
viewHolder.filePlay = (Button) convertView
.findViewById(R.id.file_play);
viewHolder.filePlay.setTag(position);
viewHolder.rate = (Button) convertView.findViewById(R.id.rate);
viewHolder.fileSeek = (SeekBar) convertView
.findViewById(R.id.file_seek);
viewHolder.filePlay.setOnClickListener(mListener);
viewHolder.rate.setOnClickListener(mListener);
convertView.setTag(viewHolder);
} else {
viewHolder = (RowViewHolder) convertView.getTag();
}
viewHolder.fileName.setText(fileList.get(position));
return convertView;
}
OnClickListener mListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.file_play)
{
final int position = mListView.getPositionForView((View) v
.getParent());
Log.d("position"+position, "count"+mListView.getCount());
for (int i = 0 ; i < mListView.getChildCount(); i++) {
RowViewHolder viewholder = (RowViewHolder) ((View) mListView
.getChildAt(i)).getTag();
if (i == position) {
String path = Environment.getExternalStorageDirectory()
.toString()
+ "/analyser/"
+ folder
+ "/"
+ fileList.get(i);
mSeekBar = viewholder.fileSeek;
Log.d("IN the click "+i,path);
// mSeekBar.setEnabled(false);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(mPlayer != null && fromUser){
mPlayer.seekTo(progress);
}
}
});
viewholder.fileSeek.setVisibility(View.VISIBLE);
viewholder.fileName.setVisibility(View.GONE);
play(path);
} else {
viewholder.fileSeek.setVisibility(View.GONE);
viewholder.fileName.setVisibility(View.VISIBLE);
}
}
}
if (v.getId() == R.id.rate) {
}
}
};
public void play(String path) {
if (mPlayer == null) {
mPlayer = new MediaPlayer();
mPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mSeekBar.setMax(mPlayer.getDuration());
mp.start();
seekUpdation();
}
});
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mPlayer.release();
mPlayer = null;
seekHandler.removeCallbacks(run);
}
});
}
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
seekHandler.removeCallbacks(run);
}
try {
mPlayer.setDataSource(path);
mPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Runnable run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mPlayer != null) {
seekUpdation();
}
}
};
public void seekUpdation() {
if (mPlayer != null) {
mSeekBar.setProgress(mPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}
}
}
You have to set the listeners for the button in the Adapter class getView method.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.audio_file_list_item, null);
viewHolder = new RowViewHolder();
viewHolder.fileName = (TextView) convertView.findViewById(R.id.file_name);
viewHolder.filePlay = (Button) convertView.findViewById(R.id.file_play);
viewHolder.filePlay.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view){
// Do Your Work Here
}
});
viewHolder.filePlay.setTag(position);
viewHolder.rate = (Button) convertView.findViewById(R.id.rate);
viewHolder.fileSeek = (SeekBar) convertView.findViewById(R.id.file_seek);
viewHolder.filePlay.setOnClickListener(mListener);
viewHolder.rate.setOnClickListener(mListener);
convertView.setTag(viewHolder);
} else {
viewHolder = (RowViewHolder) convertView.getTag();
}
viewHolder.fileName.setText(fileList.get(position));
return convertView;
}
It is my java file named Dataadapter_PaidTicket.java
public class Dataadapter_PaidTicket extends BaseAdapter {
public static String ticket_id;
private final Context context;
public JSONArray values;
public TextView textview;
public TextView textview1;
public TextView textview2;
public TextView textview3;
public TextView textview4;
public Button btn;
public Dataadapter_PaidTicket(Context context, int _resource, JSONArray values) {
// TODO Auto-generated constructor stub
this.context = context;
this.values = values;
}
#Override
public int getCount() {
return values.length();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
try {
return values.get(position);
} catch (JSONException e) {
return e;
}
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder holder = new ViewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row_ticket, null);
holder.textview = (TextView) convertView.findViewById(R.id.ticket_name);
holder.textview1 = (TextView) convertView.findViewById(R.id.ticket_start_date);
holder.textview2 = (TextView) convertView.findViewById(R.id.ticket_end_date);
holder.textview3=(TextView)convertView.findViewById(R.id.ticket_price);
holder.textview4=(TextView)convertView.findViewById(R.id.ticket_qty);
holder.btn=(Button)convertView.findViewById(R.id.btn_edit_buy);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
JSONObject temp = null;
try {
temp = (JSONObject) values.get(position);
String title=temp.get("paid_ticket_name").toString();
//String Ctitle = title.substring(0, 10);
holder.textview.setText(title.replace("null", " "));
String tkt_s_date = temp.get("paid_start_sale").toString();
String s_dat e= Constants.formatteddate(tkt_s_date);
holder.textview1.setText(s_date.replace("null", " "));
String tkt_e_date = temp.get("paid_end_sale").toString();
String e_date = Constants.formatteddate(tkt_e_date);
holder.textview2.setText(e_date.replace("null", " "));
String q = temp.get("paid_qty").toString();
holder.textview3.setText(q.replace("0", " "));
String p = temp.get("paid_price").toString();
holder.textview4.setText(p.replace("null", " "));
if (Constants.id.equals(Dataadapter.user_id)) {
holder.btn.setText("EDIT");
} else {
holder.btn.setText("BUY");
}
Log.e("Title",temp.get("paid_ticket_name").toString());
Log.e("Venue",temp.get("paid_description").toString());
Log.e("Date",temp.get("paid_start_sale").toString());
ticket_id = temp.get("id").toString();
Log.e("Ticket ID",ticket_id);
convertView.setId(position);
} catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
public TextView textview;
public TextView textview1;
public TextView textview2;
public TextView textview3;
public TextView textview4;
public Button btn;
}
}
Here, I need to do something like this. If the value of title, s_date, e_date, paid_qty, paid_price are null, then I don't want to show the button(here btn). Is it possible to hide that button? How can I do this?
Please replace " " with "" (without empty space) in your replace("null", " ") functions because if JSON has no value it is not an emptyspace it is just null. And then try this again.
if (title==null || s_date==null || e_date==null || paid_qty==null || paid_price == null){
holder.btn.setVisibility(View.INVISIBLE);
}
else{
holder.btn.setVisibility(View.VISIBLE);
}
Button btn;
btn= (Button) findViewById(R.id.button1);
if (title.equals(" ") || s_date.equals(" ") || e_date.equals(" ") || paid_qty.equals(" ") || paid_price.equals(" "))
{
btn.setVisibility(View.GONE);
}
else
{
btn.setVisibility(View.VISIBLE);
}