Share Intent on click - android

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

Related

images not appearing in gridView but after keyboard actived

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.

How to call intent based on item position in viewpager?

i want to make an intent from array of images, but i don't know how to use position. the intent doesn't match with the layout i created.
here's the code:
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] { R.drawable.kuhp_a,
R.drawable.kuhp_b, R.drawable.kuhp_c };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
Button btnOK = (Button) findViewById(R.id.btnOK);
if (position == 0) {
btnOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, FirstAct.class);
startActivity(i);
}
});
} else if (position == 1) {
btnOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this,
SecondAct.class);
startActivity(i);
}
});
} else if (position == mImages.length - 1) {
btnOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, ThirdAct.class);
startActivity(i);
}
});
}
((ViewPager) container).addView(imageView, 0);
return imageView;
}
firstact:
public class FirstAct extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.buku_satu);
}
secondact and third have same code like first act, but it has different layout.
Do this way
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] { R.drawable.kuhp_a, R.drawable.kuhp_b, R.drawable.kuhp_c };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
final Button btnOK = (Button) findViewById(R.id.btnOK);
btnOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, FirstAct.class);
startActivity(i);
break;
case 1:
Intent i = new Intent(MainActivity.this, SecondAct.class);
startActivity(i);
break;
case 2:
Intent i = new Intent(MainActivity.this, ThirdAct.class);
startActivity(i);
break;
default:
break;
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
}

Set As Wallpaper From ButtonClick Using ViewPager Adapter in Android?

i want set wallpaper which is currenton viewpager imageview on buttonclick but button is not in view pager so how to set the wall paper from viewpager adapter and button is not in the imageview
onclick where i want to set as wall paper
imagebutton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// coding for wall set as wallpaper
int b=pager.getCurrentItem();
WallpaperManager myWallpaperManager=WallpaperManager. getInstance(getApplicationContext());
myWallpaperManager.setResource(id);
}
});
CopyOfClickedImagesActivity .java
public class CopyOfClickedImagesActivity extends BaseActivity
{
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
public static final String TAG_STATUS="status";
public static final String TAG_DATA="data";
public static final String TAG_ID="id";
public static final String TAG_CATEGORYNAME="category_name";
public static final String TAG_IMAGENAME="image_name";
public static final String TAG_SETID="set_id";
DisplayImageOptions options;
ViewPager pager;
ImageView imagebutton;
ImagePagerAdapter pagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clickedimage);
pager=(ViewPager)findViewById(R.id.myviewpager);
imagebutton=(ImageView)findViewById(R.id.imagebutton);
BaseActivity.imageLoader.init(ImageLoaderConfiguration.createDefault(getBaseContext()));
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.resetViewBeforeLoading(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300))
.build();
imagebutton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// coding for wall set as wallpaper
int b=pager.getCurrentItem();
WallpaperManager myWallpaperManager=WallpaperManager. getInstance(getApplicationContext());
myWallpaperManager.setResource(id);
}
});
}
public class GetImagesAsync extends AsyncTask<String, ArrayList<HashMap<String,String>>, ArrayList<HashMap<String,String>>>
{
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params)
{
JsonParser json = new JsonParser();
String url="myurlhere";
String data=json.getdata(url);
try
{
JSONObject jobject= new JSONObject(data);
String status=jobject.get(TAG_STATUS).toString();
if(status.equalsIgnoreCase("1"))
{
JSONArray jarray = jobject.getJSONArray(TAG_DATA);
for(int i=0;i<jarray.length();i++)
{
String id =jarray.getJSONObject(i).get(TAG_ID).toString();
String category=jarray.getJSONObject(i).get(TAG_IMAGENAME).toString();
HashMap<String, String> map = new HashMap<>();
map.put(TAG_ID,id);
map.put(TAG_IMAGENAME, category);
mylist.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
Log.e("ClickedImagesActivity","Data-------"+data);
return mylist;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result)
{
pagerAdapter=new ImagePagerAdapter(result);
//pager.setAdapter(new ImagePagerAdapter(result));
pager.setAdapter(pagerAdapter);
}
}
private class ImagePagerAdapter extends PagerAdapter
{
//private String[] images;
ArrayList<HashMap<String,String>> images;
private LayoutInflater inflater;
ImagePagerAdapter(ArrayList<HashMap<String,String>> images)
{
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.imagelayout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
imageView.setBackgroundResource(R.drawable.rounded_corner);
imageView.setScaleType(ScaleType.FIT_XY);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageView.setTag(position);
imageLoader.displayImage(images.get(position).get(TAG_IMAGENAME), 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;
}
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
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;
}
}

Search clears all object in ListView

I've got a problem with my search filter. When i start typing, all objects are gone and no search is performed. Only after refresh are they back. When I try to proof via Toast, that if (wp.getAnimal().toLowerCase(Locale.getDefault())
.contains(text)) in adapter is called, no toast views.
Do you have any idea, where the problem could be? Thanks in advance!
My MainActivity class with EditText listener
public class MainActivity extends ActionBarActivity{
private ListView mListView;
private AnimalAdapter mAdapter;
ProgressBar mProgressBar;
EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add your initialization code here
Parse.initialize(this, "code", "code");
ParseObject.registerSubclass(Animal.class);
ParseAnalytics.trackAppOpened(getIntent());
View header = getLayoutInflater().inflate(R.layout.header, null);
header.setPadding(2, 8, 4, 2);
mListView = (ListView) findViewById(R.id.animal_list);
mListView.setVisibility(View.INVISIBLE);
mListView.addHeaderView(header);
mProgressBar = (ProgressBar) findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.VISIBLE);
RemoteDataTask task = new RemoteDataTask();
task.execute();
}
public void updateData(){
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.setCachePolicy(CachePolicy.CACHE_THEN_NETWORK);
query.orderByAscending("animal");
query.findInBackground(new FindCallback<Animal>() {
#Override
public void done(List<Animal> animals, ParseException error) {
if(animals != null){
mAdapter.clear();
mProgressBar.setVisibility(View.INVISIBLE);
for (int i = 0; i < animals.size(); i++) {
mAdapter.add(animals.get(i));
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Intent refreshIntent = new Intent(MainActivity.this, MainActivity.class);
refreshIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
refreshIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(refreshIntent);
overridePendingTransition(0,0);
return true;
}
return super.onOptionsItemSelected(item);
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
updateData();
return null;
}
#Override
protected void onPostExecute(Void result) {
mListView = (ListView) findViewById(R.id.animal_list);
// Pass the results into ListViewAdapter.java
mAdapter = new AnimalAdapter(MainActivity.this, new ArrayList<Animal>());
mListView.setAdapter(mAdapter);
mListView.setVisibility(View.VISIBLE);
mListView.setTextFilterEnabled(true);
mEditText = (EditText) findViewById(R.id.search_animal);
mEditText.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
mListView.setVisibility(View.VISIBLE);
}
#Override
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {
mListView.setVisibility(View.VISIBLE);
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
mListView.setVisibility(View.VISIBLE);
String text = mEditText.getText().toString()
.toLowerCase(Locale.getDefault());
mAdapter.filter(text);
}
});
}
}
}
My Adapter class with filter method
public class AnimalAdapter extends ArrayAdapter<Animal> implements Filterable{
private Context mContext;
private List<Animal> mAnimals;
ImageLoader imageLoader;
ArrayList<Animal> array;
DisplayImageOptions options;
Activity activity;
private Filter animalFilter;
private List<Animal> animaly;
#SuppressWarnings("deprecation")
public AnimalAdapter(Context context, List<Animal> objects) {
super(context, R.layout.animal_row_item, objects);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
this.mContext = context;
this.mAnimals = objects;
this.animaly = objects;
}
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.animal_row_item, null);
}
final Animal animal = mAnimals.get(position);
TextView animalView = (TextView) convertView.findViewById(R.id.animal_text);
TextView areaView = (TextView) convertView.findViewById(R.id.area_text);
final ImageView animalPic = (ImageView)convertView.findViewById(R.id.animal_pic);
final ProgressBar indicator = (ProgressBar)convertView.findViewById(R.id.progress);
indicator.setVisibility(View.VISIBLE);
animalPic.setVisibility(View.INVISIBLE);
//Setup a listener we can use to switch from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
indicator.setVisibility(View.INVISIBLE);
animalPic.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View view, FailReason arg2) {
}
};
imageLoader.displayImage(getItem(position).getImgUrl(), animalPic,options, listener);
animalView.setText(animal.getAnimal());
areaView.setText(animal.getArea());
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), MoreActivity.class);
intent.putExtra("about", animal.getAbout());
intent.putExtra("animal", animal.getAnimal());
intent.putExtra("imgUrl", animal.getImgUrl());
getContext().startActivity(intent);
}
});
return convertView;
}
public int getCount() {}
return mAnimals.size();
public void filter(String text) {
if (text.length() == 0) {
mAnimals.addAll(animaly);
Toast.makeText(getContext(), "text 0", Toast.LENGTH_SHORT).show();
} else {
mAnimals.clear();
for (Animal wp : animaly) {
if (wp.getAnimal().toLowerCase(Locale.getDefault())
.contains(text)) {
Toast.makeText(getContext(), "contains", Toast.LENGTH_SHORT).show();
mAnimals.add(wp);
}
}}
notifyDataSetChanged();
}
}
I just solved this with doing it a little bit different way. For great tutorial check/codes:
For tutorial check this.
For the whole codes check this.
Good luck and have a great day!

ViewPager uses the wrong entry

I have the following class to show some images...
I have implemented an ability to download images to the sd card.
If I go through them everything is fine (Image + Title showing) but if I start the download at a certain image, uses another url (of another image) so I somehow think that my ViewPager is not updated correctly or something.
This is my class:
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
LinearLayout buttonBar;
TextView txtTitle;
String urlOfImageToDownload;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
private static DisplayImageOptions options;
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
String[] imageTitles = bundle.getStringArray(Extra.TITLES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.cacheOnDisc().showImageForEmptyUri(R.drawable.no_image)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls, imageTitles));
pager.setCurrentItem(pagerPosition);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (imageView.getDrawable() == null)
menu.getItem(0).setEnabled(false);
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0,
getString(R.string.save_image)).setIcon(android.R.drawable.ic_menu_save);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Random randomGenerator = new Random();
int randomInt = 0;
for (int idx = 1; idx <= 10; ++idx) {
randomInt = randomGenerator.nextInt(100000);
}
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
try {
b.compress(CompressFormat.JPEG, 100,
new
FileOutputStream(Environment.getExternalStorageDirectory()
.getPath() + "/DCIM/image" + randomInt + ".jpg"));
Crouton.makeText(ImagePagerActivity.this,
"Bild erfolgreich gespeichert",
Style.INFO)
.show();
} catch (FileNotFoundException e) {
Crouton.makeText(ImagePagerActivity.this,
"Fehler beim speichern von Datei",
Style.ALERT)
.show();
}
startDownload();
return true;
}
return false;
}
private void startDownload() {
String url = urlOfImageToDownload;
Log.e(MainActivity.LOG_TAG, "url=" + urlOfImageToDownload);
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.downloading_image));
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private String[] titles;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images, String[] imageTitles) {
this.images = images;
this.titles = imageTitles;
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);
imageView = (ImageView) imageLayout
.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout
.findViewById(R.id.loading);
txtTitle = (TextView) imageLayout.findViewById(R.id.txtTitle);
urlOfImageToDownload = images[position];
buttonBar = (LinearLayout) imageLayout.findViewById(R.id.buttonBar);
txtTitle.setText(titles[position]);
imageLoader.displayImage(images[position], imageView, options,
new ImageLoadingListener() {
#Override
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(FailReason failReason) {
switch (failReason) {
case IO_ERROR:
break;
case OUT_OF_MEMORY:
break;
case UNKNOWN:
break;
}
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
#Override
public void onLoadingComplete(Bitmap bm) {
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled() {
spinner.setVisibility(View.GONE);
}
});
((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) {
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Random rand = new Random();
int randomNumber = rand.nextInt(100000);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
"sdcard/nature_" + randomNumber + ".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Crouton.makeText(ImagePagerActivity.this,
getString(R.string.image_saved),
Style.CONFIRM)
.show();
}
}
}
Thanks for any help!
Issue:
The first time the user looks at an image in the ViewPager, instantiateItem(..) for that image will be called and the field urlOfImagetoDownload will be set to the correct URL:
urlOfImageToDownload = images[position];
However if the user now returns to an image he has seen before that is already instantiated, instantiateItem(...) will not be called and urlOfImageToDownload will hold the wrong URL (of the previous image).
Solution:
You can use ViewPager#getCurrentItem() to retrieve the index of the current image, then use that index with images[] to get the right URL when the user clicks to download.

Categories

Resources