images not appearing in gridView but after keyboard actived - android

i have two activites,transporting arraylist imageurls to activity AddProductActivity from activity Sdcard. The Sdcard.java code is:
public class Sdcard extends Activity {
private ArrayList<String> imageUrls;
private DisplayImageOptions options;
private ImageAdapter imageAdapter;
ImageLoader imageLoader;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photoalbum);
getActionBar();
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayShowTitleEnabled(true);
getActionBar().setTitle("select image");
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
System.out.println("=====> Array path => " + imageUrls.get(i));
}
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_error_loadingsmall)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
imageAdapter = new ImageAdapter(this, imageUrls);
GridView gridView = (GridView) findViewById(R.id.album_gridview);
gridView.setAdapter(imageAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.select_image, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(Sdcard.this, AddProductActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.select_image_submit:
ArrayList<String> selectedItems = imageAdapter.getCheckedItems();
if (selectedItems.size() == 0) {
Toast.makeText(getBaseContext(), "no selected image!", Toast.LENGTH_LONG)
.show();
} else if (selectedItems.size() > 9) {
Toast.makeText(getBaseContext(), "must below 9 images", Toast.LENGTH_LONG)
.show();
} else {
Intent intent1 = new Intent(this, AddProductActivity.class);
intent1.putStringArrayListExtra("select_image", selectedItems);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
setResult(9392,intent1);
finish();
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
public class ImageAdapter extends BaseAdapter {
ArrayList<String> mList;
LayoutInflater mInflater;
Context mContext;
SparseBooleanArray mSparseBooleanArray;
public ImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
mSparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<String>();
this.mList = imageList;
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < mList.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ProgressBar spinner = (ProgressBar) findViewById(R.id.loading_image_fromsdcard);
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.photoalbum_gridview_item, null);
}
CheckBox mCheckBox = (CheckBox) convertView
.findViewById(R.id.select_image_cb);
final ImageView imageView = (ImageView) convertView
.findViewById(R.id.photo_img_view);
imageLoader.displayImage("file://" + imageUrls.get(position),
imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(Sdcard.this, message,
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim =AnimationUtils.loadAnimation(Sdcard.this,
R.anim.push_left_in);
imageView.setAnimation(anim);
anim.start();
}
});
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"selected item is " + position, Toast.LENGTH_LONG)
.show();
}
});
mCheckBox.setTag(position);
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mSparseBooleanArray.put((Integer) buttonView.getTag(),
isChecked);
}
};
}
}
and activity AddProductActivity recive imageurls from activity Sdcard and display image on it, like the code
public class AddProductActivity extends Activity{
GridView gridView;
private String image;
private static final int GALLERY_REQUEST = 9390;
private DisplayImageOptions options;
ImageLoader imageLoader;
private ArrayList<String> selectImageUrls;
String[] f;
private SelectImageAdapter selectImageAdapter;
ImageView imageView;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("add product");
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_error_loadingsmall)
.cacheInMemory().cacheOnDisc().build();
gridView = (GridView) findViewById(R.id.select_image_gridview);
this.selectImageUrls = new ArrayList<String>();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_product, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(AddProductActivity.this,
MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.action_upload_picture:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onSelectFromSD(MenuItem item) {
Intent selectFromSdcard = new Intent(AddProductActivity.this,Sdcard.class);
startActivityForResult(selectFromSdcard, GALLERY_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("[requestCode=" + requestCode + "]" + "[resultCode="
+ resultCode + "]");
if (requestCode == GALLERY_REQUEST && resultCode == 9392
&& data != null) {
// image = data.getData().toString();
selectImageUrls = data.getStringArrayListExtra("select_image");
if (selectImageUrls != null) {
// System.out.println("recieve =" + selectImageUrls.size());
f = (String[]) selectImageUrls
.toArray(new String[selectImageUrls.size()]);
if (selectImageAdapter == null) {
selectImageAdapter = new SelectImageAdapter(this,
selectImageUrls);
imageLoader.init(ImageLoaderConfiguration
.createDefault(this));
gridView.setAdapter(selectImageAdapter);
selectImageAdapter.notifyDataSetChanged();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
startFullImagePagerActivity(position);
}
});
} else {
selectImageAdapter.notifyDataSetChanged();
}
} else {
return;
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
protected void startFullImagePagerActivity(int position) {
// TODO Auto-generated method stub
Intent i = new Intent(AddProductActivity.this,
FullScreenViewActivity.class);
i.putStringArrayListExtra("position_url", selectImageUrls);
i.putExtra("position", position);
startActivity(i);
}
public class SelectImageAdapter extends BaseAdapter {
LayoutInflater mInflater;
Context mContext;
public SelectImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
imageLoader = ImageLoader.getInstance();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return selectImageUrls.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = mInflater.inflate(R.layout.select_image, null);
}
final ImageView imageView = (ImageView) convertView.findViewById(R.id.select_images);
final ProgressBar spinner = (ProgressBar)convertView.findViewById(R.id.select_image_loading);
//final ViewAnimator animator = (ViewAnimator)convertView.findViewById(R.id.animator);
imageLoader.displayImage("file://" + selectImageUrls.get(position), imageView,
options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
//animator.setDisplayedChild(1);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}Toast.makeText(AddProductActivity.this, message,Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
//animator.setDisplayedChild(0);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
// Animation anim =
// AnimationUtils.loadAnimation(Sdcard.this,
// R.anim.push_left_in);
// imageView.setAnimation(anim);
// anim.start();
spinner.setVisibility(View.GONE);
notifyDataSetChanged();//followed with Armin's suggestion
}
});
return convertView;
}
}
but when it returned activity AddProductActivity,the images did not appear in gridview ,if i clicked the editorText to active the keyboard,the images appearing in the gridview. So i am puzzled,waiting for some suggestions, thanks!
image url :http://i61.tinypic.com/2ch9onq.png
actived keyboard image appearing: http://i61.tinypic.com/2l8uumc.png
if i used this getView() method in AddProductActivity,it works fine.
#Override
public View getView(final int position, View convertView, ViewGroup
parent)
{
if (convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(245, 150));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
else {
imageView = (ImageView) convertView;
}
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false ;
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true ;
Bitmap bitmap = BitmapFactory.decodeFile(selectImageUrls.get(position), bmOptions);
imageView.setImageBitmap(bitmap);
return imageView;
}
but it does not smooth when it transfored the imageurls back to AddProductActivity.

Try to replace adapter code.
public class SelectImageAdapter extends BaseAdapter {
Context mContext;
ViewHolder holder;
public SelectImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
imageLoader = ImageLoader.getInstance();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return selectImageUrls.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.select_image, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.select_images);
holder.spinner = (ProgressBar)convertView.findViewById(R.id.select_image_loading);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//final ViewAnimator animator = (ViewAnimator)convertView.findViewById(R.id.animator);
imageLoader.displayImage("file://" + selectImageUrls.get(position),holder.imageView,
options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.spinner.setVisibility(View.VISIBLE);
//animator.setDisplayedChild(1);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(AddProductActivity.this, message,Toast.LENGTH_SHORT).show();
holder.spinner.setVisibility(View.GONE);
//animator.setDisplayedChild(0);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
// Animation anim =
// AnimationUtils.loadAnimation(Sdcard.this,
// R.anim.push_left_in);
// imageView.setAnimation(anim);
// anim.start();
holder.spinner.setVisibility(View.GONE);
}
});
return convertView;
}
class ViewHolder {
ImageView imageView;
ProgressBar spinner;
}
}

I believe what is missing in the code is a call to notifyDataSetChanged() after the images are loaded (in onLoadingComplete() callback of the listener).
The way the above code is written, if notifyDataSetChanged() is called in onLoadingComplete(), it will solve the problem that you have.
However, calling notifyDataSetChanged() every time in that callback method, may degrade the performance significantly. The more images you have, the more the performance may drop.
If you do observe performance drop by doing the above, to solve it, I would suggest using an image refresh helper mechanism. This way you can either call notifyDataSetChanged():
after n images have been loaded
or after every t seconds has passed
I hope the information above helps you.

Related

how to remove the empty cell of custom list-view in my android application

Hi i am doing an application in which i want to show the content depending on the custom and the public ,data is coming from the sever.i am receiving the is_public as a parameter value as 0 and 1 if it is 1 it for public, we need to display to all user if t is 0,we need to display only the custom member like user id 8,10. for rest of the user the received content like user id 11 need to be invisible.
i able to make invisible the content, when i invisible it it is taking blank space in the list view how to remove the blank space i am posting my adapter class below
please help me
public class PlacementsBoardAdapter extends BaseAdapter{
private ArrayList<PlacementsBoardModel> listData;
private LayoutInflater layoutInflater;
ArrayList<PlacementsBoardModel> listData1;
public ImageLoader imageLoader;
DisplayImageOptions profile_options;
ImageView imageview;
private Context prova;
Bitmap bit_map_image;
int isPublic;
String custom;
public PlacementsBoardAdapter(Context context,ArrayList<PlacementsBoardModel> listData){
this.listData = listData;
listData1=listData;
prova = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listData.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
imageLoader =imageLoader.getInstance();
profile_options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.pdfimage)
.showImageForEmptyUri(R.drawable.pdfimage)
.showImageOnFail(R.drawable.pdfimage)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
final ViewHolder holder;
if (layoutInflater == null)
layoutInflater = (LayoutInflater) prova.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.placementsboardcutomview, null);
holder = new ViewHolder();
/*holder.title_of_placesment = (TextView) convertView.findViewById(R.id.title_of_placesment);
holder.pdf_image_custom=(ImageView)convertView.findViewById(R.id.pdf_image_custom);
holder.created_date = (TextView) convertView.findViewById(R.id.created_date);*/
holder.title_of_placesment = (TextView) convertView.findViewById(R.id.noticetopic);
holder.pdf_image_custom=(ImageView)convertView.findViewById(R.id.notice_title_name_image);
holder.readmore=(TextView)convertView.findViewById(R.id.readmore);
holder.placement_etext = (TextView) convertView.findViewById(R.id.noticetext);
holder.readmorelayout=(RelativeLayout)convertView.findViewById(R.id.bottom_layout);
holder.created_date = (TextView) convertView.findViewById(R.id.createddate);
holder.placementCustomLinear=(LinearLayout)convertView.findViewById(R.id.placementCustomLinear);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
final PlacementsBoardModel placementboardItem = (PlacementsBoardModel) listData.get(position);
holder.title_of_placesment.setText(placementboardItem.getTitle());
holder.created_date.setText(placementboardItem.getCreated_date());
holder.placement_etext.setText(placementboardItem.getDescription());
String description=placementboardItem.getDescription();
isPublic=placementboardItem.getIsPublic();
custom=placementboardItem.getCustom();
if (description!=null&&!placementboardItem.getDownload_file_path().contains("null")) {
holder.placement_etext.setVisibility(View.VISIBLE);
holder.pdf_image_custom.setVisibility(View.VISIBLE);
if(isPublic==0&&Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}
if (description.length()>350) {
holder.placement_etext.setText(placementboardItem.getDescription().trim().subSequence(0, 300)+"....");
holder.readmorelayout.setVisibility(View.VISIBLE);
}
}
else if(description!=null&&placementboardItem.getDownload_file_path().contains("null")){
if (description.length()>350) {
holder.placement_etext.setText(placementboardItem.getDescription().trim().subSequence(0, 300)+"....");
holder.readmorelayout.setVisibility(View.VISIBLE);
}
else{
holder.readmorelayout.setVisibility(View.GONE);
holder.placement_etext.setVisibility(View.VISIBLE);
holder.pdf_image_custom.setVisibility(View.GONE);
}
}
if(placementboardItem.getDescription().contains("null")&&!placementboardItem.getDownload_file_path().contains("null")) {
holder.placement_etext.setVisibility(View.GONE);
holder.pdf_image_custom.setVisibility(View.VISIBLE);
holder.readmorelayout.setVisibility(View.GONE);
}
//holder.pdf_image_custom.setBackground(background)
if (placementboardItem.getDownload_file_type().contains("jpg")||placementboardItem.getDownload_file_type().contains("jpeg")||placementboardItem.getDownload_file_type().contains("png")) {
Log.i("only jpg or png", "tittle the file for display");
if (placementboardItem.getTitle().length()>=20) {
holder.title_of_placesment.setText(placementboardItem.getTitle().trim().subSequence(0, 20)+"....");
//holder.imageview.setImageBitmap(noticeboardItem.getBit_image());
}else{
//noticeboardItem.getBit_image()
holder.title_of_placesment.setText(placementboardItem.getTitle());
holder.pdf_image_custom.setImageBitmap(bit_map_image);
}
} else {
if (placementboardItem.getTitle().length()>=20) {
holder.title_of_placesment.setText(placementboardItem.getTitle().trim().subSequence(0, 20)+"....");
//holder.imageview.setImageResource(R.drawable.pdfimage);
}else{
holder.title_of_placesment.setText(placementboardItem.getTitle());
//holder.imageview.setImageResource(R.drawable.pdfimage);
Log.i("only pdf", "only pdf");;
}
}
if(isPublic==1&&!Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}
holder.pdf_image_custom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PlacementsBoardModel notice_data = (PlacementsBoardModel) listData.get(position);
/*String title=notice_data.getTitle();
String description=notice_data.getDescription();
Intent intent = new Intent(prova,DscriptionDisplay.class);
intent.putExtra("title",title);
intent.putExtra("description",description);
prova.startActivity(intent);*/
if (notice_data.getDownload_file_type().contains("jpg")||notice_data.getDownload_file_type().contains("gif")||notice_data.getDownload_file_type().contains("jpeg")||notice_data.getDownload_file_type().contains("png")) {
Log.i("only jpg or png", "tittle the file for display");
Intent intent1 = new Intent(prova,NoticeBoardImageDisplayActivity.class);
intent1.putExtra("noticeimagelink",notice_data.getDownload_file_path());
intent1.putExtra("noticetitle",notice_data.getTitle());
prova.startActivity(intent1);
} else {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(notice_data.getDownload_file_path()));
prova.startActivity(browserIntent);
Log.i("only pdf", "only pdf");
}
notifyDataSetChanged();
}
});
holder.readmore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//placementboardItem = (PlacementsBoardModel) listData.get(position);
String title=placementboardItem.getTitle();
String description=placementboardItem.getDescription();
Intent intent = new Intent(prova,DscriptionDisplay.class);
intent.putExtra("title",title);
intent.putExtra("description",description);
prova.startActivity(intent);
notifyDataSetChanged();
}
});
imageLoader.displayImage(placementboardItem.getDownload_file_path(), holder.pdf_image_custom, profile_options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//bit_map_image=loadedImage;
}
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current,
int total) {
}
}
);
notifyDataSetChanged();
return convertView;
}
static class ViewHolder{
RelativeLayout readmorelayout;
TextView placement_etext;
TextView readmore;
TextView title_of_placesment;
TextView created_date;
ImageView pdf_image_custom;
LinearLayout placementCustomLinear;
}
}
holder.placementCustomLinear is the custom leaner-layout need to be make it invisible
After some research i have solved my problem by adding a parent layout in the the xml and adding the some logic in the adapter class like
if (Util.ROLE.equalsIgnoreCase("admin")) {
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}else
if(isPublic==0){
Log.i("inside if ", ""+isPublic);
Log.i("custom disply", custom);
int[] arry= stringToInteger(custom);
Log.i("numbers to ccheck ", ""+(arry));
for (int i = 0; i < arry.length; i++) {
if(custom.contains(Util.USER_ID)){
Log.i("true checked ", "inside");
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}else{
holder.placementCustomLinear.setVisibility(View.GONE);
notifyDataSetChanged();
}
}
if(isPublic==0&&Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
}
else{
Log.i("else block ",""+isPublic);
if(isPublic==1)
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
my problem is solved thanks for the people who have give some suggestion

Handlle image orientation in GridView android

I am using the code below to display the device images in a GridView.
But I am getting an image orientation problem while displaying them in the GridView.
Some images are showing in horizontal orientation mode
public class MultiImagePicActivity extends Activity {
GridView mGrid;
static public String[] arrPath,modifiedArrayPath;
private int ids[];
private int count;
static int selectCount;
Activity act=this;
Context ctx=this;
ArrayList<String> imagepaths;
public static int count1 = 0;
public static String classs;
static int maximageselection;
static int width,height;
//int sel=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//now get Intent Extras
Bundle extras;
if (savedInstanceState == null)
{
//fetching extra data passed with intents in a Bundle type variable
extras = getIntent().getExtras();
if(extras == null)
{ maximageselection= 0;
classs=null;
}
else
{ /* fetching the string passed with intent using ‘extras’*/
maximageselection= extras.getInt("maximage");
classs=extras.getString("From");
}
}
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
imagepaths=new ArrayList<String>();
imagepaths.clear();
loadApps();
setContentView(R.layout.grid_1);
mGrid = (GridView) findViewById(R.id.myGrid);
mGrid.setAdapter(new ImageAdapterxtends());
mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener());
}
private void loadApps() {
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.arrPath = new String[this.count];
ids = new int[count];
for (int i = 0; i <this.count; i++) {
imagecursor.moveToPosition(i);
ids[i] = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
imagecursor.close();
}
#Override
public void onBackPressed() {
setResult(Activity.RESULT_CANCELED);
super.onBackPressed();
}
public class ImageAdapterxtends extends BaseAdapter{
CheckableLayout l;
ImageView i;
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrPath.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrPath[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
i = new ImageView(MultiImagePicActivity.this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ViewGroup.LayoutParams(50, 50));
l = new CheckableLayout(MultiImagePicActivity.this);
l.setLayoutParams(new GridView.LayoutParams(
GridView.LayoutParams.WRAP_CONTENT,
GridView.LayoutParams.WRAP_CONTENT));
l.addView(i);
} else {
l = (CheckableLayout) convertView;
i = (ImageView) l.getChildAt(0);
}
try {
setBitmap(i, ids[position]);
} catch (Throwable e) {
}
return l;
}
}
private void setBitmap(final ImageView iv,final int id) {
new AsyncTask<Void, Void, Bitmap>() {
Bitmap myBitmap;
#Override
protected Bitmap doInBackground(Void... params) {
return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//iv.setImageBitmap(result);
setMyBitmap(result);
}
public final void setMyBitmap(Bitmap bitmap) {
if (this.myBitmap != null) {
this.myBitmap.recycle();
}
this.myBitmap = bitmap;
iv.getLayoutParams().height = width/3;
iv.getLayoutParams().width = width/3;
iv.setImageBitmap(myBitmap);
}
}.execute();
}
public class CheckableLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableLayout(Context context) {
super(context);
}
public void setChecked(boolean checked) {
mChecked = checked;
setForeground(checked ? getResources().getDrawable(R.drawable.tr) : null);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
//return true;
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.menu_ok:
if(classs.equals("SliderExistingDetailedActivity")){
Intent i = new Intent();
modifiedArrayPath=imagepaths.toArray(new String[imagepaths.size()]);
i.putExtra("selectedImagepath", modifiedArrayPath);
//i.putExtra("data", selectedPath);
setResult(Activity.RESULT_OK, i);
finish();
}else{
Intent intent=new Intent(MultiImagePicActivity.this, AudioSelectActivity.class);
intent.putExtra("IMAGEPATHS", imagepaths);
startActivity(intent);
finish();
}
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
Toast.makeText(getApplicationContext(), "text", 1);
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
selectCount = mGrid.getCheckedItemCount();
if(checked){
imagepaths.add(arrPath[position]);
if(selectCount>maximageselection){
imagepaths.remove(arrPath[position]);
new AlertDialog.Builder(MultiImagePicActivity.this)
.setTitle("Restriction")
.setMessage("You can add at max "+maximageselection+" images !!!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
mGrid.refreshDrawableState();
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
else{
imagepaths.remove(arrPath[position]);
}
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount + " items selected");
break;
}
}
//}
}
}

Android how to mange spinner with radio button in listview?

My problem is that when I am clicking on radio button it will change the spinner value randomly at any position..please help here is my adapter class..
public class ManageAdapter extends BaseAdapter {
ArrayList<String> _manageArrayList = null;
private Context _Context = null;
private Integer selectedPosition = 0;
String List1[]=new String[]{"In use","Lost" ,"Stolen" , "For sale"};
private int flag = 0;
public ManageAdapter(ArrayList<String> _manageArrayList, Context _Context) {
super();
this._manageArrayList = _manageArrayList;
this._Context = _Context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return _manageArrayList != null? _manageArrayList.size():0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public TextView itemTextView;
public RadioButton myitemButton;
public Spinner inUseSpinner;
public RelativeLayout managelayout;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater)_Context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(v == null)
{
holder = new ViewHolder();
v = inflater.inflate(R.layout.manage_single_row, null,false);
holder.managelayout = (RelativeLayout)v.findViewById(R.id.single_row_layout);
holder.itemTextView = (TextView)v.findViewById(R.id.item_name_txt);
holder.myitemButton = (RadioButton)v.findViewById(R.id.manage_radio_buton);
holder.inUseSpinner = (Spinner)v.findViewById(R.id.Status_spinner);
v.setTag(holder);
ArrayAdapter<String> Adapter = new ArrayAdapter<String>(_Context,R.layout.spinner_color,List1);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
holder.inUseSpinner.setAdapter(Adapter);
}else {
holder = (ViewHolder) v.getTag();
}
holder.itemTextView.setText(_manageArrayList.get(position));
holder.inUseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// int getPosition = (Integer) arg0.getTag();
// Toast.makeText(_Context,List1[position] ,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
if(flag == 0)
{
flag = 1;
holder.myitemButton.setChecked(false);
holder.myitemButton.setTag(position);
}else {
holder.myitemButton.setChecked(position == selectedPosition);
holder.myitemButton.setTag(position);
}
holder.myitemButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer)v.getTag();
notifyDataSetInvalidated();
}
});
return v;
}
}
Thanks in advance
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_item);
_backButton = (Button)findViewById(R.id.back);
_backButton.setOnClickListener(this);
_headerTextView = (TextView)findViewById(R.id.header_TextView);
_headerTextView.setText("My Items");
_uploadButton = (ImageButton)findViewById(R.id.Upload_file_button);
_uploadButton.setOnClickListener(this);
_addmanullyButton = (ImageButton)findViewById(R.id.add_item_manually);
_addmanullyButton.setOnClickListener(this);
_addphoneButton = (ImageButton)findViewById(R.id.auto_add_phone);
_addphoneButton.setOnClickListener(this);
_modifyButton = (ImageButton)findViewById(R.id.modify_button);
_modifyButton.setOnClickListener(this);
_transferButton = (ImageButton)findViewById(R.id.transfer_ownership);
_transferButton.setOnClickListener(this);
_hideenButton = (Button)findViewById(R.id.hideen_button);
_hideenButton.setOnClickListener(this);
_manageListView = (ListView)findViewById(R.id.manage_listview);
prepareList();
_adapter = new ManageAdapter(listItem, this);
_manageListView.setAdapter(_adapter);
}
public void prepareList() {
listItem = new ArrayList<String>();
listItem.add("Android smart");
listItem.add("sony");
listItem.add("samsung");
listItem.add("micromax");
listItem.add("tablet");
}
#Override
public void onClick(View view) {
Intent intent = null;
switch (view.getId()) {
case R.id.Upload_file_button:
intent = new Intent(ManageItems.this, UploadFileActivity.class);
startActivity(intent);
break;
case R.id.modify_button:
intent = new Intent(ManageItems.this, ModifyActivity.class);
startActivity(intent);
break;
case R.id.transfer_ownership:
intent = new Intent(ManageItems.this, TransferOwnerShip.class);
startActivity(intent);
break;
case R.id.add_item_manually:
intent = new Intent(ManageItems.this, AddManuallyActivity.class);
startActivity(intent);
break;
case R.id.auto_add_phone:
intent = new Intent(ManageItems.this, AutoAddActivity.class);
startActivity(intent);
break;
case R.id.back:
intent = new Intent(ManageItems.this, MenuActivtiy.class);
startActivity(intent);
break;
case R.id.hideen_button:
intent = new Intent(ManageItems.this, MenuActivtiy.class);
startActivity(intent);
break;
}
Thanks all but I got the solution of my question..
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
MyItemListDataHolder myItemListDataHolder = _manageArrayList.get(position);
LayoutInflater inflater = (LayoutInflater)_Context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(v == null)
{
holder = new ViewHolder();
v = inflater.inflate(R.layout.manage_single_row, null,false);
holder.managelayout = (RelativeLayout)v.findViewById(R.id.single_row_layout);
holder.itemTextView = (TextView)v.findViewById(R.id.item_name_txt);
holder.myitemButton = (RadioButton)v.findViewById(R.id.manage_radio_buton);
holder.inUseSpinner = (Spinner)v.findViewById(R.id.Status_spinner);
v.setTag(holder);
}else {
holder = (ViewHolder) v.getTag();
}
holder.itemTextView.setText(myItemListDataHolder.get_itemName());
Adapter = new ArrayAdapter<String>(_Context,R.layout.spinner_color,List1);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
holder.inUseSpinner.setAdapter(Adapter);
if(myItemListDataHolder.get_selectedItem() > 0){
holder.inUseSpinner.setSelection(myItemListDataHolder.get_selectedItem());
}else{
holder.inUseSpinner.setSelection(0);
}
holder.inUseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
private Intent intent;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position1, long arg3) {
_manageArrayList.get(position).set_selectedItem(position1);
// notifyDataSetChanged();
String status=holder.inUseSpinner.getSelectedItem().toString();
if(status.equalsIgnoreCase("Lost"))
{
intent = new Intent (_Context, LostItemActivity.class);
startActivity(intent);
}else if (status.equalsIgnoreCase("Stolen")) {
intent = new Intent (_Context, StolenItemActivity.class);
startActivity(intent);
}else if (status.equalsIgnoreCase("Stolen")) {
intent = new Intent (_Context, LostFoundActivity.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
if(flag == 0)
{
flag = 1;
holder.myitemButton.setChecked(false);
}else {
holder.myitemButton.setChecked(position == selectedPosition);
}
holder.myitemButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = position;
notifyDataSetChanged();
//_adapter.notifyDataSetChanged();
}
});
return v;
}
}

notifyDataSetChanged() doesn't work with my adapter for gridview

I have a GridView and adapter for GridView (BasketAdapter extends BaseAdapter).
I load data in GridView from sharedpref file.
After I change data, I resave sharedpref file with data and call notifyDataSetChanged().
But notifyDataSetChanged() doesn't work unfortunately.
If I create new adapter and set it to my GridView, it works.
Can anyone help me with this issue?
Here is my code:
public class FragmentBasket extends SherlockFragment {
// my gridview
GridView gvCatalogAllStoneBasket;
// list of data from shared pref
ArrayList<CatalogItem> catalogItemBasket = new ArrayList<CatalogItem>();
ActionMode mode;
public static CatalogItem catalogItem;
// id variables for actionmode's actions
static final int ID_DELETE = 1;
static final int ID_EDIT = 2;
// shared pref id string
static String SHARED_PREFS_FILE = "basket";
// my adapter
BasketAdapter adapter = null;
public FragmentBasket() {
}
#Override
public void onStart() {
super.onStart();
// loading saved data from file
new GetCatalogAllStoneBasket().execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Receiver receiver = new Receiver();
IntentFilter intentFilterAdd = new IntentFilter("com.example.myproject.ADD_ITEM_BASKET");
IntentFilter intentFilterEdit = new IntentFilter("com.example.myproject.EDIT_ITEM_BASKET");
IntentFilter intentFilterDelete = new IntentFilter("com.example.myproject.DELETE_ITEM_BASKET");
getActivity().registerReceiver(receiver, intentFilterAdd);
getActivity().registerReceiver(receiver, intentFilterEdit);
getActivity().registerReceiver(receiver, intentFilterDelete);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid, container, false);
gvCatalogAllStoneBasket = (GridView)view.findViewById(R.id.gvCatalogAllStoneBasket);
gvCatalogAllStoneBasket.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// start action mode and send id of clicked item
mode = getSherlockActivity().startActionMode(new ActionModeOfBasket(String.valueOf(view.getTag())));
return false;
}
});
return view;
}
private final class ActionModeOfBasket implements ActionMode.Callback
{
String itemId;
public ActionModeOfBasket(String itemId) {
// get id from clicked item
this.itemId = itemId;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add(0, ID_EDIT, 0, "Edit")
.setIcon(android.R.drawable.ic_menu_edit)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
menu.add(0, ID_DELETE, 1, "Delete")
.setIcon(android.R.drawable.ic_menu_delete)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// get file
SharedPreferences sPref = getActivity().getSharedPreferences(SHARED_PREFS_FILE, getActivity().MODE_PRIVATE);
// open file for reading, writing
BasketHelper bHelper = new BasketHelper(sPref, getActivity());
switch (item.getItemId())
{
// if clicked del button
case ID_DELETE:
// delete item
bHelper.DelItem(itemId);
mode.finish();
catalogItemBasket = bHelper.GetAllItems();
break;
// if clicked edit button
case ID_EDIT:
// edit item
bHelper.EditItem(itemId, getFragmentManager());
mode.finish();
catalogItemBasket = bHelper.GetAllItems();
break;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
class GetCatalogAllStoneBasket extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
SharedPreferences sPref = getActivity().getSharedPreferences(FragmentCatalogStonePosition.SHARED_PREFS_FILE, getActivity().MODE_PRIVATE);
try {
if(sPref.getString(FragmentCatalogStonePosition.TASK, null) != null)
{
BasketHelper bHelper = new BasketHelper(sPref, getActivity());
catalogItemBasket = bHelper.GetAllItems();
}
} catch (Exception e) {
Log.d(MainActivity.tag, e.getMessage() + " " + e.getCause());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
adapter = new BasketAdapter(getActivity(), catalogItemBasket);
gvCatalogAllStoneBasket.setAdapter(adapter);
}
}
class Receiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().toString() == "com.example.myproject.ADD_ITEM_BASKET")
{
}
else if(intent.getAction().toString() == "com.example.myproject.EDIT_ITEM_BASKET")
{
// this code doesn't work (((
adapter.notifyDataSetChanged();
// this one successfully works
BasketAdapter bAdapter = new BasketAdapter(getActivity(), catalogItemBasket);
gvCatalogAllStoneBasket.setAdapter(bAdapter);
}
else if(intent.getAction().toString() == "com.example.myproject.DELETE_ITEM_BASKET")
{
}
}
}
class BasketAdapter extends BaseAdapter
{
Context context = null;
ArrayList<CatalogItem> data = null;
public BasketAdapter(Context context, ArrayList<CatalogItem> data) {
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
public CatalogItem getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflater = getLayoutInflater(null);
view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid_item, parent, false);
CatalogItem item = getItem(position);
((TextView)view.findViewById(R.id.tvCatalogItemBasketName)).setText(item.name + " / " + item.code);
Double gPrice = Double.valueOf(item.price) * Double.valueOf(item.count);
((TextView)view.findViewById(R.id.tvCatalogItemBasketCount)).setText(String.valueOf(item.count));
((TextView)view.findViewById(R.id.tvCatalogItemBasketGeneralPrice)).setText(String.valueOf(gPrice));
((TextView)view.findViewById(R.id.tvCatalogItemBasketDescription)).setText(item.description);
final ImageView imgView = (ImageView)view.findViewById(R.id.ivCatalogItemBasketImage);
String strURL = "http://myproject.ua/images/stock/" + item.folder + "/" + item.images + "_800x600.jpg";
ImageLoaderConfiguration config = ImageHelper.ImageConfig(getActivity().getApplicationContext());
DisplayImageOptions options = ImageHelper.ImageOptions();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
final ProgressBar pImgDialog = (ProgressBar)view.findViewById(R.id.pbImage);
imageLoader.displayImage(strURL, imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
pImgDialog.setVisibility(View.VISIBLE);
imgView.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
});
view.setTag(item.catalog_id);
}
return view;
}
}
}
Your convertView isn't null in case the View is recycled, so your getView() should be something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflater = getLayoutInflater(null);
view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid_item, parent, false);
}
CatalogItem item = getItem(position);
((TextView)view.findViewById(R.id.tvCatalogItemBasketName)).setText(item.name + " / " + item.code);
Double gPrice = Double.valueOf(item.price) * Double.valueOf(item.count);
((TextView)view.findViewById(R.id.tvCatalogItemBasketCount)).setText(String.valueOf(item.count));
((TextView)view.findViewById(R.id.tvCatalogItemBasketGeneralPrice)).setText(String.valueOf(gPrice));
((TextView)view.findViewById(R.id.tvCatalogItemBasketDescription)).setText(item.description);
final ImageView imgView = (ImageView)view.findViewById(R.id.ivCatalogItemBasketImage);
String strURL = "http://myproject.ua/images/stock/" + item.folder + "/" + item.images + "_800x600.jpg";
ImageLoaderConfiguration config = ImageHelper.ImageConfig(getActivity().getApplicationContext());
DisplayImageOptions options = ImageHelper.ImageOptions();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
final ProgressBar pImgDialog = (ProgressBar)view.findViewById(R.id.pbImage);
imageLoader.displayImage(strURL, imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
pImgDialog.setVisibility(View.VISIBLE);
imgView.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
});
view.setTag(item.catalog_id);
return view;
}
and since you have your own ArrayList inside your adapter, you have to update this one as well. Just add this method to your BasketAdapter:
public void changeModelList(List<CatalogItem> models) {
this.data = models;
notifyDataSetChanged();
}
and use it instead of notifyDataSetChanged().
it's not tested, but i think this is your problem.

Share Intent on click

I have a ViewPager with an ImageView and I want to make it such that when someone clicks on the image they can share it with a share Intent.
I'm not sure how to do this. Below is my code.
If someone can show me how to do this that would be great!
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private TextView mSelected;
private String[] mLocations;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
mSelected = (TextView)findViewById(R.id.text);
mLocations = getResources().getStringArray(R.array.locations);
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.locations, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
getSupportActionBar().setSelectedNavigationItem(1);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(View view, int position) {
final FrameLayout imageLayout = (FrameLayout) inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
#Override
public void onLoadingComplete() {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
#Override
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (itemPosition == 0){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
getSupportActionBar().setSelectedNavigationItem(1);
return true;
}
}
Add this code in your object instantiateItem method
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, [image URI]);
startActivity(Intent.createChooser(intent, "Share image with"));
}
}
This is updated version of u'r code
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private TextView mSelected;
private String[] mLocations;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
mSelected = (TextView)findViewById(R.id.text);
mLocations = getResources().getStringArray(R.array.locations);
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.locations, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
getSupportActionBar().setSelectedNavigationItem(1);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(View view, int position) {
final FrameLayout imageLayout = (FrameLayout) inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
#Override
public void onLoadingComplete() {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
#Override
public void onLoadingCancelled() {
// Do nothing
}
});
//Changes START
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Create new Intent to send image
Intent intent = new Intent(Intent.ACTION_SEND);
//Set Intent Type
intent.setType("image/jpeg");
//Create URI for image link
Uri uri = Uri.parse(images[position]);
//Set Intent extra with URI created from image link
intent.putExtra(Intent.EXTRA_STREAM, uri);
//Start new activity to share image
startActivity(Intent.createChooser(intent, "Share image with"));
}
}
//Changes END
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (itemPosition == 0){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
getSupportActionBar().setSelectedNavigationItem(1);
return true;
}
}

Categories

Resources