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;
}
}
Related
i have images that downloaded from a server and it downloaded into grid view when i clicked an image it opened in another activity i need to swip between images when opened into the second activity what is the wrong in my code?
public class customswitcher extends PagerAdapter{
Context c;
ArrayList<photos> sites;
LayoutInflater inflater;
public customswitcher(Context c, ArrayList<photos> sites)
{
this.c = c;
this.sites = sites;
}
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view== (LinearLayout) object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.imageswitcher,container,false);
ImageView imageView = (ImageView) view.findViewById(R.id.iv);
photos photos = sites.get(position);
Picasso.with(c).load(photos.getImage()).into(imageView);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
}
public class Funny extends AppCompatActivity {
MyDataBase dataBase = new MyDataBase(Funny.this);
String url = "http://javawy.fulba.com/yphotos.php";
ProgressDialog dialog;
String pw;
List<photos> list;
photos posts;
customfunny adapter;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_funny);
list= dataBase.getallcontacts();
final GridView gridView = (GridView) findViewById(R.id.gridview);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("photos");
list = new ArrayList<>();
for (int i = 0;i<jsonArray.length();i++)
{
JSONObject object1 = jsonArray.getJSONObject(i);
pw = object1.getString("image");
posts = new photos(pw);
dataBase.AddnewContact(posts);
list.add(posts);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(Funny.this,"اتصل بالانترنت لتحصل علي احيث الصور",Toast.LENGTH_LONG).show();
}
});
adapter = new customfunny(Funny.this,list);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
photos photos = (com.example.yasser.ahlysc.photos) gridView.getItemAtPosition(i);
Intent intent = new Intent(Funny.this,SelectedImage.class);
intent.putExtra("one",photos.getImage());
startActivity(intent);
adapter.notifyDataSetChanged();
}
});
dialog = new ProgressDialog(Funny.this);
dialog.setTitle("downloading");
dialog.setMessage("جاري تحديث الصور....انتظر");
dialog.show();
Volley.newRequestQueue(Funny.this).add(stringRequest);
}
}
public class SelectedImage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_image);
Intent i = getIntent();
String s = i.getStringExtra("one");
ArrayList<photos> list = new ArrayList<>();
list.add(new photos(s));
ViewPager pager = (ViewPager) findViewById(R.id.vp);
customswitcher customswitcher = new customswitcher(SelectedImage.this,list);
pager.setAdapter(customswitcher);
}
}
Listview doesn't appear at Fragment after second compile.
The button at fragment works, so the problem is with listview and adapter, but I can't understand where the problem is.
Even if I delete the program and reinstall, it doesn't help. Only if move some other place method updatepost it can work once.
Hope for advice! I'm just learning all this.
Main fragment:
public class MainFragment extends Fragment {
ArrayList<Bitmap> bitArray;
CustomListAdapter adapter;
public MainFragment() {
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listview = (ListView)rootView.findViewById(R.id.listViewPost);
Log.v("Plaxehere","1");
adapter = new CustomListAdapter(getContext(), bitArray);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getActivity(), "YESS", Toast.LENGTH_SHORT).show();
}
});
Button but =(Button) rootView.findViewById(R.id.button_back_to_home);
but.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(getContext(), "Text", Toast.LENGTH_SHORT).show();
/*Intent intent = new Intent(getActivity(), MainActivity.class).putExtra(Intent.EXTRA_TEXT, "Hello");
startActivity(intent);*/
}
});
return rootView;
}
private void updatePost() {
FetchPosterTask postTask = new FetchPosterTask(getActivity());
postTask.execute("uk_news.json");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bitArray = new ArrayList<>();
updatePost();
}
class FetchPosterTask extends AsyncTask<String, Void, ArrayList<Bitmap>> {
private final String LOG_TAG = FetchPosterTask.class.getSimpleName();
private Context context;
public FetchPosterTask (Context myContext) {
this.context = myContext;
}
#Override
protected ArrayList<Bitmap> doInBackground(String... params) {
if(params.length ==0 ){
return null;
}
String json = null;
try {
json = getJson(params[0]);
} catch (IOException e)
{
e.printStackTrace();
}
try {
String[] masPst = getPosterfromJsonAsString(json);
ArrayList<Bitmap> result =decodeImageToBitmap(masPst);
return result;
}catch (JSONException e){
Log.e(LOG_TAG, "Place 5", e);
}
return null;
}
private String getJson(String filename) throws IOException{
InputStream is = this.context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
}
private String[] getPosterfromJsonAsString(String posterJson) throws JSONException {
final String OWM_NFO = "nfo";
final String OWM_NWS = "nws";
final String OWM_PST = "pst";
JSONObject imageJson = new JSONObject(posterJson);
JSONObject nfoArray = imageJson.getJSONObject(OWM_NFO);
JSONArray nwsArray = nfoArray.getJSONArray(OWM_NWS);
String[] resultStr = new String[nwsArray.length()];
for(int i =0; i<nwsArray.length(); i++){
JSONObject pst = nwsArray.getJSONObject(i);
String im = pst.getString(OWM_PST);
resultStr[i] = im;
}
return resultStr;
}
public ArrayList<Bitmap> decodeImageToBitmap (String[] base64Image) {
ArrayList<Bitmap> bitmapArrayList = new ArrayList<Bitmap>();
for(int i =0; i<4; i++) {
byte[] decodedString = Base64.decode(base64Image[i], Base64.DEFAULT);
Bitmap base64Bitmap = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
bitmapArrayList.add(i, base64Bitmap);
}
return bitmapArrayList;
}
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
if(bitArray.size()!=0){
bitArray.clear();
bitArray.addAll(bitmapArrayList);
}
else{
bitArray.addAll(bitmapArrayList);
}
}
}
}
Adapter
public class CustomListAdapter extends BaseAdapter {
private final String LOG_TAG = CustomListAdapter.class.getSimpleName();
private ArrayList<Bitmap> bitmapArrayList;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<Bitmap> bitmapArrayList) {
this.bitmapArrayList = bitmapArrayList;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return bitmapArrayList.size();
}
#Override
public Object getItem(int position) {
return bitmapArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_post_item, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.list_item);
convertView.setTag(holder);
Log.v(LOG_TAG,"1");
}
else {
holder = (ViewHolder) convertView.getTag();
Log.v(LOG_TAG,"2");
}
Log.v(LOG_TAG,"3");
if(getItem(position) == null) {
holder.imageView.setImageResource(R.drawable.pst_0);
Log.v(LOG_TAG,"5");
}
else{
holder.imageView.setImageBitmap((Bitmap) getItem(position));
Log.v(LOG_TAG,"6");
}
Log.v(LOG_TAG,"4");
return convertView;
}
static class ViewHolder {
ImageView imageView;
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MainFragment())
.commit();
}
}
}
What I'm trying to achieve is to obtain the URL received from Instagram and pass its array position to an onlick listener for each corresponding photo in a grid view.
Here is my code:
MainActivity.java
public class MainActivity extends Activity {
private InstagramSession mInstagramSession;
private Instagram mInstagram;
private ProgressBar mLoadingPb;
private GridView mGridView;
private static final String CLIENT_ID = "83549f9eb76f4a5b90daf6e4e14da107";
private static final String CLIENT_SECRET = "6df26b0c8f664323a07126bfe8511651";
private static final String REDIRECT_URI = "http://www.yahoo.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mInstagram = new Instagram(this, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
mInstagramSession = mInstagram.getSession();
if (mInstagramSession.isActive()) {
setContentView(R.layout.activity_user);
InstagramUser instagramUser = mInstagramSession.getUser();
mLoadingPb = (ProgressBar) findViewById(R.id.pb_loading);
mGridView = (GridView) findViewById(R.id.gridView);
((TextView) findViewById(R.id.tv_name)).setText(instagramUser.fullName);
((TextView) findViewById(R.id.tv_username)).setText(instagramUser.username);
((Button) findViewById(R.id.btn_logout)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mInstagramSession.reset();
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
ImageView userIv = (ImageView) findViewById(R.id.iv_user);
DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_user)
.showImageForEmptyUri(R.drawable.ic_user)
.showImageOnFail(R.drawable.ic_user)
.cacheInMemory(true)
.cacheOnDisc(false)
.considerExifParams(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.writeDebugLogs()
.defaultDisplayImageOptions(displayOptions)
.build();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
AnimateFirstDisplayListener animate = new AnimateFirstDisplayListener();
imageLoader.displayImage(instagramUser.profilPicture, userIv, animate);
new DownloadTask().execute();
} else {
setContentView(R.layout.activity_main);
((Button) findViewById(R.id.btn_connect)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mInstagram.authorize(mAuthListener);
}
});
}
}
private void showToast(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
private Instagram.InstagramAuthListener mAuthListener = new Instagram.InstagramAuthListener() {
#Override
public void onSuccess(InstagramUser user) {
finish();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
#Override
public void onError(String error) {
showToast(error);
}
#Override
public void onCancel() {
showToast("OK. Maybe later?");
}
};
public static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
ArrayList<String> photoList;
public class DownloadTask extends AsyncTask<URL, Integer, Long> {
protected void onCancelled() {
}
protected void onPreExecute() {
}
protected Long doInBackground(URL... urls) {
long result = 0;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("count", "20"));
InstagramRequest request = new InstagramRequest(mInstagramSession.getAccessToken());
String response = request.createRequest("GET", "/users/21846697/media/recent", params);
if (!response.equals("")) {
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray jsonData = jsonObj.getJSONArray("data");
int length = jsonData.length();
if (length > 0) {
photoList = new ArrayList<String>();
for (int i = 0; i < length; i++) {
JSONObject jsonPhoto = jsonData.getJSONObject(i).getJSONObject("images").getJSONObject("standard_resolution");
photoList.add(jsonPhoto.getString("url"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
mLoadingPb.setVisibility(View.GONE);
if (photoList == null) {
Toast.makeText(getApplicationContext(), "No Photos Available", Toast.LENGTH_LONG).show();
} else {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = (int) Math.ceil((double) dm.widthPixels / 2);
width=width-50;
int height = width;
PhotoListAdapter adapter = new PhotoListAdapter(MainActivity.this);
adapter.setData(photoList);
adapter.setLayoutParam(width, height);
mGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Maybe you'll have to cast it to a string, I'm currently writing directly in SO
String url = (String) parent.getAdapter().getItem(position);
Intent myintent=new Intent(MainActivity.this, FullscreenImageView.class).putExtra("SelectedImageURL", position);
startActivity(myintent);
}
});
mGridView.setAdapter(adapter);
}
}
}
}
PhotoListAdapter.java
public class PhotoListAdapter extends BaseAdapter {
private Context mContext;
private ImageLoader mImageLoader;
private AnimateFirstDisplayListener mAnimator;
private ArrayList<String> mPhotoList;
private int mWidth;
private int mHeight;
public PhotoListAdapter(Context context) {
mContext = context;
DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.instagram_logo)
.showImageForEmptyUri(R.drawable.instagram_logo)
.showImageOnFail(R.drawable.instagram_logo)
.cacheInMemory(true)
.cacheOnDisc(false)
.considerExifParams(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.writeDebugLogs()
.defaultDisplayImageOptions(displayOptions)
.build();
mImageLoader = ImageLoader.getInstance();
mImageLoader.init(config);
mAnimator = new AnimateFirstDisplayListener();
}
public void setData(ArrayList<String> data) {
mPhotoList = data;
}
public void setLayoutParam(int width, int height) {
mWidth = width;
mHeight = height;
}
#Override
public int getCount() {
return (mPhotoList == null) ? 0 : mPhotoList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageIv;
if (convertView == null) {
imageIv = new ImageView(mContext);
imageIv.setLayoutParams(new GridView.LayoutParams(mWidth, mHeight));
imageIv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageIv.setPadding(0, 0, 0, 0);
} else {
imageIv = (ImageView) convertView;
}
mImageLoader.displayImage(mPhotoList.get(position), imageIv, mAnimator);
return imageIv;
}
}
FullScreenImageView.java
import android.app.Activity;
public class FullscreenImageView extends Activity {
String imageURL = getIntent().getStringExtra("SelectedImageURL");
}
The workflow of the gridView as you understood is to have an adapter to populate this view.
What I would do is that the getItem(int position) returns the URL which, if I good understood, is contained in your mPhotoList. Something like:
#Override
public Object getItem(int position) {
return mPhotoList.get(position);
}
And use it where you need it like this:
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Maybe you'll have to cast it to a string, I'm currently writing directly in SO
String url = parent.getAdapter().getItem(position)
Intent myintent=new Intent(MainActivity.this, FullscreenImageView.class).putExtra("SelectedImageURL", url);
startActivity(myintent);
}
});
Hope it helps.
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.
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;
}
}