Android ListView the gallery shows in wrong places - android

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

Related

ImageViews custom checkboxes repeats itself randomly

I have a gridview with an adapter, which also has a checkbox look to be shown when an imageview has been clicked. But something goes wrong. If an image is checked and you scroll to the bottom, one of the images are also checked. If you scroll up again, another image than the one you clicked to begin with, is checked (in most cases).
So here is the code for my adapter. The code in concern is the getView method:
public class ImageAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> files;
private Bitmap mPlaceHolderBitmap;
private File directory;
private int thumbSize;
private GridImageListener gridImageListener;
private LayoutInflater inflater;
private View rootView;
private final int MAX_PICTURE_LIMIT = 5;
private int picturesChosenCount = 0;
public ImageAdapter(Context context, ArrayList<String> files, File directory, int thumbSize, GridImageListener gridImageListener, LayoutInflater inflater, View rootView) {
super();
this.context = context;
this.files = files;
this.directory = directory;
this.thumbSize = thumbSize;
this.gridImageListener = gridImageListener;
this.inflater = inflater;
this.rootView = rootView;
mPlaceHolderBitmap = drawableToBitmap(context.getResources().getDrawable(R.drawable.logo));
}
public Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
#Override
public int getCount() {
return files.size();
}
#Override
public Object getItem(int position) {
return files.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup container) {
final ViewHolder holder;
if (convertView == null) { // if it's not recycled, initialize some attributes
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.component_imageview_checkable, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.checkableImageView);
holder.imageview.getLayoutParams().height = thumbSize;
holder.imageview.getLayoutParams().width = thumbSize;
holder.imageCheckBox = (RelativeLayout) convertView.findViewById(R.id.image_check_view);
loadBitmap(files.get(position), holder.imageview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageCheckBox.setId(position);
holder.imageview.setId(position);
holder.imageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.imageCheckBox.getVisibility() == View.VISIBLE) {
holder.imageCheckBox.setVisibility(View.INVISIBLE);
picturesChosenCount--;
} else {
if (picturesChosenCount < 5) {
holder.imageCheckBox.setVisibility(View.VISIBLE);
picturesChosenCount++;
} else {
Toast.makeText(context, "Max number of pictures has been reached", Toast.LENGTH_SHORT).show();
}
}
gridImageListener.onClickImage(files.get(position));
}
});
holder.id = position;
return convertView;
}
public void loadBitmap(String path, ImageView imageView) {
if (cancelPotentialWork(path, imageView)) {
final BitmapWorkerTask task = new BitmapWorkerTask(imageView, context, path, directory, thumbSize);
final AsyncDrawable asyncDrawable =
new AsyncDrawable(context.getResources(), mPlaceHolderBitmap, task);
imageView.setImageDrawable(asyncDrawable);
task.execute(path);
}
}
public static boolean cancelPotentialWork(String path, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final String bitmapData = bitmapWorkerTask.path;
// If bitmapData is not yet set or it differs from the new data
if (bitmapData.equals("0") || !bitmapData.equals(path)) {
// Cancel previous task
bitmapWorkerTask.cancel(true);
} else {
// The same work is already in progress
return false;
}
}
// No task associated with the ImageView, or an existing task was cancelled
return true;
}
private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap,
BitmapWorkerTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference =
new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
}
public BitmapWorkerTask getBitmapWorkerTask() {
return bitmapWorkerTaskReference.get();
}
}
}
class ViewHolder {
int id;
ImageView imageview;
RelativeLayout imageCheckBox;
}
I know it has something to do with the recycling of views in the gridview, but I don't know how to avoid/fix it. Each imageview is loaded separately in an asynctask and is reloaded when you scroll to it. If you need to take a look at it, the code is here: http://pastebin.com/2BcBW7PN
And finally, here is my XML for the item of each image:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/checkableImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<RelativeLayout
android:id="#+id/image_check_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/checkableImageView"
android:layout_alignTop="#+id/checkableImageView"
android:layout_alignRight="#+id/checkableImageView"
android:layout_alignBottom="#+id/checkableImageView"
android:visibility="invisible">
<com.ivankocijan.magicviews.views.MagicTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#color/white"
android:background="#drawable/blue_border"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<com.ivankocijan.magicviews.views.MagicTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/icon_check"
android:textColor="#color/white"
android:textSize="#dimen/txtsize_standard_smaller_icon"
android:padding="4dp"
app:typeFace="#string/icon_font"
android:background="#color/standard_blue"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</RelativeLayout>
What might be wrong? I have read all the tutorials I could find, but none of them seemed to do any difference.
You can use : Eg: Android – Select multiple photos from Gallery
Or :
Entity -CustomGallery.class
public class CustomGallery {
public String sdcardPath;
public boolean isSeleted = false;
}
Adapter -GalleryAdapterCustom.class
private Context mContext;
private LayoutInflater infalter;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public GalleryAdapterCustom(Context c, ImageLoader imageLoader) {
infalter = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = c;
this.imageLoader = imageLoader;
// clearCache();
}
#Override
public int getCount() {
return data.size();
}
#Override
public CustomGallery getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void setMultiplePick(boolean isMultiplePick) {
this.isActionMultiplePick = isMultiplePick;
}
public void selectAll(boolean selection) {
for (int i = 0; i < data.size(); i++) {
data.get(i).isSeleted = selection;
}
notifyDataSetChanged();
}
public boolean isAllSelected() {
boolean isAllSelected = true;
for (int i = 0; i < data.size(); i++) {
if (!data.get(i).isSeleted) {
isAllSelected = false;
break;
}
}
return isAllSelected;
}
public boolean isAnySelected() {
boolean isAnySelected = false;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
isAnySelected = true;
break;
}
}
return isAnySelected;
}
public ArrayList<CustomGallery> getSelected() {
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
dataT.add(data.get(i));
}
}
return dataT;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
} else {
data.get(position).isSeleted = true;
}
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
dataT.add(data.get(i));
}
}
if (dataT.size() > NewPostActivity.max_image) {
Toast.makeText(mContext, "Bạn chỉ được đăng tối đa 20 ảnh / 1 tin",
Toast.LENGTH_SHORT).show();
data.get(position).isSeleted = false;
}
((ViewHolder) v.getTag()).imgQueueMultiSelected.setSelected(data
.get(position).isSeleted);
// }
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = infalter.inflate(R.layout.gallery_item, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView
.findViewById(R.id.imgQueue);
holder.imgQueueMultiSelected = (ImageView) convertView
.findViewById(R.id.imgQueueMultiSelected);
if (isActionMultiplePick) {
holder.imgQueueMultiSelected.setVisibility(View.VISIBLE);
} else {
holder.imgQueueMultiSelected.setVisibility(View.GONE);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgQueue.setTag(position);
try {
imageLoader.displayImage("file://" + data.get(position).sdcardPath,
holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue
.setImageResource(R.drawable.default_icon2);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgQueueMultiSelected
.setSelected(data.get(position).isSeleted);
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgQueueMultiSelected;
}
public void clearCache() {
imageLoader.clearDiscCache();
imageLoader.clearMemoryCache();
}
public void clear() {
data.clear();
notifyDataSetChanged();
}
}
Activity- CustomGalleryActivity.class
public class CustomGalleryActivity extends Activity {
GridView gridGallery;
Handler handler;
GalleryAdapterCustom adapter;
String count_image;
RelativeLayout layout_select, layout_cancel;
ImageView imgNoMedia;
Button btnGalleryOk;
public static final int REQUEST_CODE_Gallery = 1111;
public static final int REQUEST_CODE_Gallery_OK = 2222;
String action;
private ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
action = getIntent().getStringExtra("action");
if (action == null) {
finish();
}
initImageLoader();
init();
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(),
CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
getBaseContext())
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.memoryCache(new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
} catch (Exception e) {
}
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapterCustom(getApplicationContext(), imageLoader);
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,
true, true);
gridGallery.setOnScrollListener(listener);
if (action.equalsIgnoreCase(Action.ACTION_MULTIPLE_PICK)) {
findViewById(R.id.layout_select).setVisibility(View.VISIBLE);
gridGallery.setOnItemClickListener(mItemMulClickListener);
adapter.setMultiplePick(true);
} else if (action.equalsIgnoreCase(Action.ACTION_PICK)) {
findViewById(R.id.layout_select).setVisibility(View.GONE);
gridGallery.setOnItemClickListener(mItemSingleClickListener);
adapter.setMultiplePick(false);
}
gridGallery.setAdapter(adapter);
imgNoMedia = (ImageView) findViewById(R.id.imgNoMedia);
layout_cancel = (RelativeLayout) findViewById(R.id.layout_cancel);
layout_cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
layout_select = (RelativeLayout) findViewById(R.id.layout_select);
layout_select.setOnClickListener(mOkClickListener);
new Thread() {
#Override
public void run() {
Looper.prepare();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addAll(getGalleryPhotos());
checkImageStatus();
}
});
Looper.loop();
};
}.start();
}
private void checkImageStatus() {
if (adapter.isEmpty()) {
imgNoMedia.setVisibility(View.VISIBLE);
} else {
imgNoMedia.setVisibility(View.GONE);
}
}
View.OnClickListener mOkClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<CustomGallery> selected = adapter.getSelected();
String[] allPath = new String[selected.size()];
for (int i = 0; i < allPath.length; i++) {
allPath[i] = selected.get(i).sdcardPath;
}
if (allPath.length == 0) {
Toast.makeText(CustomGalleryActivity.this, "Vui lòng chọn ảnh",
Toast.LENGTH_SHORT).show();
} else {
Intent data = new Intent().putExtra("all_path", allPath);
setResult(REQUEST_CODE_Gallery_OK, data);
finish();
}
}
};
AdapterView.OnItemClickListener mItemMulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
adapter.changeSelection(v, position);
}
};
AdapterView.OnItemClickListener mItemSingleClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomGallery item = adapter.getItem(position);
Intent data = new Intent().putExtra("single_path", item.sdcardPath);
setResult(REQUEST_CODE_Gallery_OK, data);
finish();
}
};
private ArrayList<CustomGallery> getGalleryPhotos() {
ArrayList<CustomGallery> galleryList = new ArrayList<CustomGallery>();
try {
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
if (imagecursor != null && imagecursor.getCount() > 0) {
while (imagecursor.moveToNext()) {
CustomGallery item = new CustomGallery();
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
item.sdcardPath = imagecursor.getString(dataColumnIndex);
galleryList.add(item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// show newest photo at beginning of the list
Collections.reverse(galleryList);
return galleryList;
}
Use .
Intent i = new Intent(NewPostActivity.this,
CustomGalleryActivity.class);
i.putExtra("action", Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, REQUEST_CODE_Gallery);

Listview not generating views on second time with different layouts?

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

listview of songs with checkbox using Aquery unable to save the State of chekckbox while list scrolldown?

Hi i have listview of songs with checkbox using Aquery i am unable to save the State of chekckbox while list scrolldown. i have two arraylist one is for by clicking song image & other is for checkbox if user select the chekbox it should play song accordingly to checkbox arraylist. i have used this also check.setChecked(SelectedBox.get(clickedposition).getisCheck()); . But no help
so far what i have done is here
private void createList() {
listAq = new AQuery(this);
adapter = new ArrayAdapter<Audio>(SongList.this, R.layout.list_row,details) {
#Override
public View getView(final int position, View convertView,final ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row, parent, false);
}
final int clickedposition = position;
final AQuery aq = listAq.recycle(convertView);
Audio item = getItem(position);
aq.id(R.id.MovieName).text(item.getAlbumName());
aq.id(R.id.SongName).text(item.getTitle());
aq.id(R.id.checkBox1).getCheckBox().setSelected(item.getisCheck());
aq.id(R.id.nameLayout).clicked(new OnClickListener() {
#Override
public void onClick(View v) {
DialogBuilder(position);
}
});
check = (CheckBox) convertView.findViewById(R.id.checkBox1);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
try {
if (isChecked) {
checkbox = true;
if (details.get(clickedposition).getisCheck() == false) {
SelectedBox.add(details.get(clickedposition));
System.out.println(SelectedBox.size());
details.get(clickedposition).setisCheck(true);
}
} else {
final String name = details.get(clickedposition).getFilename();
for (int i = 0; i <= SelectedBox.size(); i++) {
if (name.equals(SelectedBox.get(i).getFilename())) {
SelectedBox.remove(i);
details.get(clickedposition).setisCheck(false);
}
}
}
notifyDataSetChanged();
}
catch (Exception e) {
e.getMessage();
}
}
});
try{
}
catch (Exception e) {
// TODO: handle exception
}
url = "drawable/" + item.getThumbnail();
imageResource = getResources().getIdentifier(url, null,getPackageName());
aq.id(R.id.song_image).image(imageResource);
if (position != playingValue) {
aq.id(R.id.imageplay).invisible();
aq.id(R.id.imageplay).getImageView().bringToFront();
} else {
aq.id(R.id.imageplay).visible();
}
ImageView img = (ImageView)convertView.findViewById(R.id.song_image);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkbox = false;
SelectedBox.clear();
currentSongIndex = position;
try {
if (ChannelService.playerFlag == 0) {
playSong(currentSongIndex);
} else if ((ChannelService.playerFlag == 1)
|| ((ChannelService.playerFlag == 2))) {
if (currentSongIndex != playingValue) {
try {
final Intent serviceIntent = new Intent(
getApplicationContext(),
ChannelService.class);
stopService(serviceIntent);
mPlay.setBackgroundResource(R.drawable.play_btn);
playSong(currentSongIndex);
} catch (final IllegalStateException e) {
e.printStackTrace();
}
}
mPlay.setBackgroundResource(R.drawable.pause_btn);
final Intent in = new Intent("updateNotification");
sendBroadcast(in);
}
} catch (final IllegalStateException e) {
e.getMessage();
}
notifyDataSetChanged();
}
});
return convertView;
}
};
aq.id(R.id.listView1).adapter(adapter);
}
When you scroll down a list in Android, it destroys the rows that doesn't fit in the screen.
I allways use an array of objects to save the state of each row so when android calls getView you can ask the state of them:
public class AudioRow{
public int id;
public boolean checked;
...
}
Then at getView you can do something like that:
public View getView(final int position, View convertView,final ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row, parent, false);
}
final int clickedposition = position;
AudioRow ar = audioRows.get(position);
if(ar.checked) {
//do something;
}
...
#Override
public void onClick(View v) {
if(ar.checked) ar.checked = false;
else ar.checked = true;
DialogBuilder(position);
}
});
I hope it helps you.

notifydatasetchange not working

I know that this question is asked many times but i can't seem to make it work in my app
I create custom adapter that extends BaseAdapter, and inside it I put listener of drag and drop function to rearrange the order of the items on the list.
so I need to call notifydatasetchanged when drop action is performed, and I did, but don't seem to reorder the data even though when I print out the data to LogCat is already sorted the way I want it.
I try recommendation like using asyncTask, Activity.runOnUIThread but no result for me. I also that's not very suitable for me since i calling it inside the adapter itself, though I called it from another class inside the adapter.
The data for my adapter I provide inside the adapter itself, get from local DB.
Please help me and take a look at my code:
CategoryAdapter -> customAdapter
public class CategoryAdapter extends BaseAdapter {
private static final String TAG = CategoryAdapter.class.getSimpleName();
private List<CategoryUIO> categoryUIOs;
private Context context;
private LayoutInflater inflater;
private CategorySequenceComparator comparator = new CategorySequenceComparator();
public CategoryAdapter(Activity activity) {
this.context = activity;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getData();
}
private void getData() {
Cursor cursor = MoneyTracker.getCategoryDB().queryAll();
categoryUIOs = new ArrayList<CategoryUIO>();
if (cursor != null && cursor.moveToFirst()) {
do {
CategoryUIO bo = new CategoryUIO(cursor);
categoryUIOs.add(bo);
} while (cursor.moveToNext());
cursor.close();
}
notifyDataSetChanged();
}
private void sortData() {
if (categoryUIOs != null) {
Collections.sort(categoryUIOs, comparator);
notifyDataSetChanged();
Log.w(TAG, "\n\n");
for (CategoryUIO uio : categoryUIOs) {
Log.w(TAG, Utilities.formatString("Name = %s", uio.getName()));
}
}
}
#Override
public int getCount() {
if (categoryUIOs != null) {
return categoryUIOs.size();
} else {
return 0;
}
}
#Override
public Object getItem(int position) {
if (categoryUIOs != null) {
return categoryUIOs.get(position);
} else {
return null;
}
}
#Override
public long getItemId(int position) {
if (categoryUIOs != null) {
return ((CategoryUIO) getItem(position)).getId();
} else {
return -1;
}
}
public void refresh() {
getData();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = inflater.inflate(R.layout.row_list, parent, false);
CategoryUIO uio = ((CategoryUIO) getItem(position));
v.setTag(uio);
if (uio != null) {
final TextView tvItem = (TextView) v.findViewById(R.id.tvItem);
final ImageView ivMove = (ImageView) v.findViewById(R.id.ivMove);
final ImageView ivSecured = (ImageView) v.findViewById(R.id.ivSecured);
tvItem.setText(uio.getDisplayName());
v.setOnDragListener(new MyDragListener());
ivMove.setOnTouchListener(new MyTouchListener());
if (uio.isSecured()) {
ivSecured.setVisibility(ImageView.VISIBLE);
} else {
ivSecured.setVisibility(ImageView.INVISIBLE);
}
}
} else {
}
return v;
}
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
View parent = (View) view.getParent();
CategoryUIO uio = (CategoryUIO) parent.getTag();
ClipData data = ClipData.newPlainText("label", uio.getDisplayName());
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(parent);
// shadowBuilder.onProvideShadowMetrics(new Point(parent.getWidth() / 2, parent.getHeight() / 2), new Point(0, 0));
view.startDrag(data, shadowBuilder, parent, 0);
// view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
private final class MyDragListener implements OnDragListener {
#Override
public boolean onDrag(View droppedView, DragEvent event) {
int action = event.getAction();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED: {
return true;
}
case DragEvent.ACTION_DRAG_ENTERED: {
return true;
}
case DragEvent.ACTION_DRAG_EXITED: {
return true;
}
case DragEvent.ACTION_DROP: {
View draggedView = (View) event.getLocalState();
CategoryBO draggedBO = ((CategoryBO) draggedView.getTag());
CategoryBO dropedBO = ((CategoryBO) droppedView.getTag());
// persist the sequence to db
SQLiteDatabase db = MoneyTracker.getDB();
db.beginTransaction();
try {
// swap the sequence
int temp = draggedBO.getSequence();
draggedBO.setSequence(dropedBO.getSequence());
dropedBO.setSequence(temp);
ContentValues cv = new ContentValues();
cv.put(CategoryDB.C_ID, draggedBO.getId());
cv.put(CategoryDB.C_SEQUENCE, draggedBO.getSequence());
Response response1 = CategoryBLService.getInstance().update(cv);
cv = new ContentValues();
cv.put(CategoryDB.C_ID, dropedBO.getId());
cv.put(CategoryDB.C_SEQUENCE, dropedBO.getSequence());
Response response2 = CategoryBLService.getInstance().update(cv);
// TODO: THIS PART IS NOT NECESSARY IF CALL TO NOTIFYDATASETCHANGED WORKS {
// the data is updated but seems like notifydatasetchanged in sortData()
// don't have any effect
// swap the BOs
// CategoryBO tempBO = draggedBO;
// draggedBO = dropedBO;
// dropedBO = tempBO;
//
// droppedView.setTag(dropedBO);
// draggedView.setTag(draggedBO);
//
// // refresh the views
// TextView droppedTvItem = (TextView) droppedView.findViewById(R.id.tvItem);
// droppedTvItem.setText(dropedBO.getDisplayName());
// TextView draggedTvItem = (TextView) draggedView.findViewById(R.id.tvItem);
// draggedTvItem.setText(draggedBO.getDisplayName());
// TODO: } THIS IS THE END OF UNNECESSARY BLOCK
if (response1.isSuccess() && response2.isSuccess()) {
db.setTransactionSuccessful();
sortData();
return true;
} else {
return false;
}
} finally {
db.endTransaction();
}
}
case DragEvent.ACTION_DRAG_ENDED: {
return true;
}
default: {
return true;
}
}
}
}
}
You are messing with your getView's implementation.
if (v == null)
you should only inflate the View you want to fill up with your dataset. I will try something like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = inflater.inflate(R.layout.row_list, parent, false);
final TextView tvItem = (TextView) v.findViewById(R.id.tvItem);
final ImageView ivMove = (ImageView) v.findViewById(R.id.ivMove);
final ImageView ivSecured = (ImageView) v.findViewById(R.id.ivSecured);
}
CategoryUIO uio = ((CategoryUIO) getItem(position));
v.setTag(uio);
if (uio != null) {
tvItem.setText(uio.getDisplayName());
v.setOnDragListener(new MyDragListener());
ivMove.setOnTouchListener(new MyTouchListener());
if (uio.isSecured()) {
ivSecured.setVisibility(ImageView.VISIBLE);
} else {
ivSecured.setVisibility(ImageView.INVISIBLE);
}
}
return v;
}
try
CategoryAdapter. notifyDataSetChanged()
When ever you have to refresh an adapter your should enter his name before notifydatasetchanged();

android Use own Image in ListView

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);

Categories

Resources