getWidth() method returns 0 - android

I am building an activity that shows two horizontal scroll views. The top one holds large images while the lower one holds the thumbnails of those images. When the user clicks on a thumbnail the upper scroll view will automatically scroll to the image corresponding to the thumbnail. My problem is that getWidth() method of layout always returns 0. I am creating the layout at runtime and then calling the getwidth() method so it should return the correct value but it is not.
public class ZoomActivity extends Activity {
private final String THUMBS="http://kurdshopping.net/thumbs/";
private final String UPLOADS="http://kurdshopping.net/uploads/";
private ImageView imageView;
private String path;
private String[] filenames;
private LinearLayout l1,l2;
private int[] widths=null;
private HorizontalScrollView hsv=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_zoom);
ActionBarUtils.setActionBar(this);
path = getIntent().getExtras().getString("path");
filenames=getIntent().getExtras().getStringArray("images");
widths=new int[filenames.length];
l1=(LinearLayout) findViewById(R.id.LinearLayout1);
l2=(LinearLayout) findViewById(R.id.LinearLayout2);
hsv=(HorizontalScrollView) findViewById(R.id.horizontalScrollView1);
for(int i=0; i<filenames.length; i++){
BitmapLoaderTask task = new BitmapLoaderTask(i);
task.execute(UPLOADS+filenames[i],"1");
}
for(int i=0;i<filenames.length;i++){
BitmapLoaderTask task = new BitmapLoaderTask(i);
task.execute(THUMBS+filenames[i],"2");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.zoom, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
// case R.id.action_all:
// Intent allitemIntent = new Intent(MainActivity.this,
// AllItemsActivity.class);
// startActivity(allitemIntent);
// break;
// case R.id.action_search:
// Intent search = new Intent(this, SearchDialogActivity.class);
// startActivity(search);
// break;
}
return super.onOptionsItemSelected(item);
}
private void setImageBitmap(Bitmap bmp) {
imageView = new ScrollableImageView(this);
imageView.setLayoutParams(new LayoutParams(bmp.getWidth(), bmp
.getHeight()));
imageView.setImageBitmap(bmp);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
root.addView(imageView);
}
private class BitmapLoaderTask extends AsyncTask<String, Void, Bitmap> {
private String layout;
private int index;
private int x_coords=0;
public BitmapLoaderTask(int index){
super();
this.index=index;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
setProgressBarIndeterminateVisibility(true);
}
#Override
protected synchronized Bitmap doInBackground(String... params) {
// AssetManager assets = getAssets();
Bitmap bmp = null;
layout=params[1];
try {
URL url = new URL(params[0]);
bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
} catch (IOException e) {
Log.e("ZoomActivity", e.getMessage(), e);
}
return bmp;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
View view=null;
try {
view=ImageUtils.insertPhoto(ZoomActivity.this, result);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(layout.equals("1")){
l1.addView(view);
view.setTag(x_coords);
x_coords+=((LinearLayout)view).getMeasuredWidth();// this is always returning 0, view.getLayoutParams().width is also same.
}else{
l2.addView(view);
ImageView img=(ImageView) ((LinearLayout)view).getChildAt(0);
img.setTag(index);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int index=(Integer) v.getTag();
LinearLayout layout = (LinearLayout) l1.getChildAt(index);
int x=(Integer) layout.getTag();
hsv.scrollTo(x, 0);
}
});
}
// ImageView imageview=(ImageView) findViewById(R.id.imageView1);
// imageview.setImageBitmap(result);
// setImageBitmap(result);
setProgressBarIndeterminateVisibility(false);
}
}
}
The insertPhoto function where I am creating the layout-
public static View insertPhoto(final Activity activity, Bitmap bm) throws MalformedURLException, IOException {
LinearLayout layout = new LinearLayout(activity.getApplicationContext());
layout.setLayoutParams(new LayoutParams(bm.getWidth()+10, bm.getHeight()+10));
layout.setGravity(Gravity.CENTER);
final ImageView imageView = new ImageView(
activity.getApplicationContext());
imageView.setLayoutParams(new LayoutParams(bm.getWidth(), bm.getHeight()));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageBitmap(bm);
// imageView.setTag(filename);
layout.addView(imageView);
return layout;
}
Thanks in advance for the help.
Edit: I am posting only the portion of the code that needs the width. I modified it to use viewtreeoserver but it still doesn't work -
l1.addView(view);
view.setTag(x_coords);
view.requestLayout();
ViewTreeObserver vto=view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
x_coords+=((LinearLayout)view).getMeasuredWidth();
}
});

Try this code before using get width method-
yourlayout.requestLayout();
Hope this helps you!!!
If it is not working please let me know i will try to help you more.
Edit answer
try this code-
l1.addView(view);
view.setTag(x_coords);
view.requestLayout();
ViewTreeObserver vto=view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
x_coords+=((LinearLayout)view).getMeasuredWidth();
}
});

Related

Android kankan-wheel modification

I am making a slot machine app and using kankan's wheel for the same. I want to modify the library such that when the rotation stops the item it will point shoud be the one that I set . I have done this but there is a glitch that shows that we have changed the actual image to the one that we want . How to achieve this?
Update:
I have researched a lot on this and if I am right , android scroll is based on duration and distance not items . From kankan's wheel library I can get current item .Now , I am trying to stop the animation as well as scroll , as soon as a certain duration has been reached and the item is the one that I want (through index) . But this is not working .Please help!!
GameActivity
public class GameActivity extends Activity {
float mDeviceDensity;
String mUuid, mTitle, mContent, mReward;
ImageButton play;
SlotMachineAdapter slotAdapter;
private List<HashMap<String, Object>> slotImages = new ArrayList<HashMap<String, Object>>();
ArrayList<String> imagesWinId = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filler_up_game);
DisplayMetrics display = getResources().getDisplayMetrics();
mDeviceDensity = display.density;
slotAdapter = new SlotMachineAdapter(this);
getPassedData();
setSoundPlayer(R.raw.clicks,true);
initWheel(R.id.slot_1, false, 0);
initWheel(R.id.slot_2, false, 1);
initWheel(R.id.slot_3, true, 2);
play = (ImageButton) findViewById(R.id.btn_mix);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shuffle(R.id.slot_1, 5000);
shuffle(R.id.slot_2, 7000);
shuffle(R.id.slot_3, 9000);
}
});
}
protected ImageLoader imageLoader;
ArrayList<SlotItem> arrListSlotItems;
private void getPassedData() {
try {
mUuid = getIntent().getStringExtra(getString(R.string.FILLER_UP_UUID));
imageLoader = ImageLoader.getInstance();
Uuid slotImagesExtra = (Uuid) (getIntent()
.getSerializableExtra(getString(R.string.FILLER_UP_IMAGES)));
arrListSlotItems = slotImagesExtra.getArrSlotItemArray();
for (int i = 0; i < arrListSlotItems.size(); i++)
downloadSlotImages(arrListSlotItems.get(i).getSlotId(), arrListSlotItems.get(i).getImageUrl());
} catch (Exception e) {
e.printStackTrace();
}
}
// Wheel scrolled flag
private boolean wheelScrolled = false;
// Wheel scrolled listener
OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
setStatus(wheel.getId(), getWheel(wheel.getId()).getWinningIndex());
}
};
// Wheel changed listener
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
/**
* Updates status
*/
private void updateStatus() {
myThread();
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
GameActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
showAlertDialogWithSingleButton(GameActivity.this, mTitle, mContent, success);
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
android.content.DialogInterface.OnClickListener success = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mContent != null && mContent.contains("again"))
startHomeActivity();
else
startNewsActivity();
}
};
private void startHomeActivity() {
}
private void startNewsActivity() {
}
android.content.DialogInterface.OnClickListener fail = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
};
public void showAlertDialogWithSingleButton(final Activity ctx, final String title, final String message,
DialogInterface.OnClickListener onClickListener) {
// show dialog
}
private void initWheel(int id, boolean monitorScroll, int itemIndex) {
Random randomGenerator = new Random();
int index = randomGenerator.nextInt(arrListSlotItems.size());
WheelView wheel = getWheel(id);
wheel.setViewAdapter(slotAdapter);
wheel.setCurrentItem((index ));
wheel.setVisibleItems(1);
wheel.setWinningIndex(itemIndex);
wheel.addChangingListener(changedListener);
wheel.addScrollingListener(scrolledListener);
wheel.setCyclic(true);
wheel.setEnabled(false);
}
private WheelView getWheel(int id) {
return (WheelView) findViewById(id);
}
private void setStatus(int id, int item) {
int index = 0;
for (int i = 0; i < arrListSlotItems.size(); i++) {
SlotItem d = arrListSlotItems.get(i);
if (d.getSlotId() != 0 && d.getSlotId() == Integer.parseInt(imagesWinId.get(item)))
index = arrListSlotItems.indexOf(d);
}
getWheel(id).setCurrentItem(index, true);
if (id == R.id.slot_3) {
if(player.isPlaying())
{
stopBackgroundAudio();
}
updateStatus();
}
}
private void shuffle(int id, int duration) {
WheelView wheel = getWheel(id);
wheel.scroll(450 + (int) (Math.random() * 50), duration);
}
private class SlotMachineAdapter extends AbstractWheelAdapter {
final int IMAGE_WIDTH = getImageWidth(mDeviceDensity);
final int IMAGE_HEIGHT = getImageHeight(mDeviceDensity);
private Context context;
/**
* Constructor
*/
public SlotMachineAdapter(Context context) {
this.context = context;
}
/**
* Loads image from resources
*/
private Bitmap loadImage(Bitmap bitmap) {
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
return scaled;
}
#Override
public int getItemsCount() {
return slotImages.size();
}
// Layout params for image view
final LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setPadding(0, 5, 0, 5);
img.setLayoutParams(params);
#SuppressWarnings("unchecked")
SoftReference<Bitmap> bitmapRef = (SoftReference<Bitmap>) slotImages.get(index).get("image");
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(bitmap);
}
img.setImageBitmap(bitmap);
return img;
}
}
private int getImageWidth(float density) {
}
private int getImageHeight(float density) {
}
private void downloadSlotImages(final int id, String slotObj) {
//downloading slot images from server
}
}
This is the code. Through this code, when slot stops I want it to scroll some more untill it reaches the image position that I receaved from server. I can do this .But this is providing a lil glitch . Is there any way to stop scrolling when the image is reached as soon as certain duration is reached.
P.S. If you need anymore detail I can provide you.
P.P.S. Screenshots wont give you any detailed insight about the issue.
After days of searching I finally did it.All I had to do was set interpolater as LinearInterpolater and While setting setCurrentItem set animation as true.

Downloading and setting a wallpaper

I have this little piece of code and I want to achieve this: program should set a wallpaper from linked image.
ImgDownload:
public class ImgDownload extends AsyncTask {
private String requestUrl;
private ImageView view;
private Bitmap pic;
private ImgDownload(String requestUrl, ImageView view) {
this.requestUrl = requestUrl;
this.view = view;
}
#Override
protected Object doInBackground(Object... objects) {
try {
URL url = new URL(requestUrl);
URLConnection conn = url.openConnection();
pic = BitmapFactory.decodeStream(conn.getInputStream());
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(Object o) {
view.setImageBitmap(pic);
}
}
main
public class MainActivity extends Activity {
private ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img= (ImageView)findViewById(R.id.img);
//!!!! This is where I am stuck :)
Object s = new ImgDownload("http://images1.wikia.nocookie.net/__cb20120402213849/masseffect/images/4/42/Uncharted_Worlds_Codex_Image.jpg",img );
}
#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;
}
}
How to instantiate/create this class in my mainActivity, so it could download img from link? Any help suggestions, thoughts, will be appreciated :)
You execute this AsyncTask like this:
ImgDownload downloader = new ImgDownload("http://images1.wikia.nocookie.net/__cb20120402213849/masseffect/images/4/42/Uncharted_Worlds_Codex_Image.jpg",img);
downloader.execute();
But I would not recommend using your code as it will produce memory leaks. For example try to rotate your device while it is downloading an image. I guarantee you your application will crash. Plus AsyncTask is a generic class. You could use that to make your code a little simpler. Here is my improved image download task:
public class ImgDownload extends AsyncTask<Void, Void, Bitmap> { // Use Generics
private final String requestUrl;
private final WeakReference<ImageView> imageViewReference; // Use WeakReference to prevent memory leaks
public ImgDownload(String requestUrl, ImageView view) {
this.requestUrl = requestUrl;
this.imageViewReference = new WeakReference<ImageView>(view);
}
#Override
protected Bitmap doInBackground(Void... objects) {
try {
URL url = new URL(requestUrl);
URLConnection conn = url.openConnection();
return BitmapFactory.decodeStream(conn.getInputStream()); // Return bitmap instead of using global variable
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
ImageView imageView = imageViewReference.get();
if(imageView != null && bitmap != null) { // Check if image or ImageView are null
imageView.setImageBitmap(bitmap);
}
}
}
new ImgDownload("http://images1.wikia.nocookie.net/__cb20120402213849/masseffect/images/4/42/Uncharted_Worlds_Codex_Image.jpg", MainActivity.img).execute();

Android gallery and async loading

I'm trying to load images with an async taks from internet. The problem is that the image will not update. Code:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i ;
i = new ImageView(this.mContext);
AsycTask task = new AsycTask();
task.url = new URL(mImageIds.get(position));
task.iv = i;
task.execute(i);
return i;
}
public class AsycTask extends AsyncTask<ImageView, Void, Bitmap>{
public Bitmap bm2;
public ImageView iv;
public URL url;
#Override
protected Bitmap doInBackground(ImageView... arg0) {
iv = arg0[0];
try {
bm2 = BitmapFactory.decodeStream((InputStream)url.getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm2;
}
#Override
protected void onPostExecute(Bitmap result) {
// iv.setImageResource(R.drawable.sw10)
iv.setVisibility(View.VISIBLE);
iv.setBackgroundResource(R.drawable.search);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setImageBitmap(result);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Why isn't the Image updating after I set the Bitmap?
I'm using an async task to update my Image, is this possible?
Try to use UnivsersalImageLoader lib which will simplify your development.
Your code for image loading will be next:
ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used
UniversalImageLoader

Android set image as wallpaper

Please show me an example code on how to set image as wallpaper using Android WallpaperManager. I have shortened and edited my question. Hopefully you guys could understand my question. I will show some attempts I have made.
HomeActivity.class
public class HomeActivity extends BaseActivity {
String[] imageUrls;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_home);
ArrayList<String> url = new ArrayList<String>();
try {
URL url_link = new URL("http://mywebsite.net/web/thumb.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url_link.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("list");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element)node;
NodeList nameList = fstElmnt.getElementsByTagName("thumb_url");
Element nameElement = (Element)nameList.item(0);
nameList = nameElement.getChildNodes();
url.add(nameList.item(0).getNodeValue());
}
imageUrls = (String[]) url.toArray(new String[0]);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
public void onImageGridClick(View view) {
Intent intent = new Intent(this, ImageGridActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
startActivity(intent);
}
public void onImagePagerClick(View view) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
startActivity(intent);
}
}
ImagePagerActivity.class
package com.nostra13.example.universalimageloader;
import java.io.IOException;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
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);
}
public void setWallpaper() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.pager); // nothing happened
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
setWallpaper();
return true;
default:
return false;
}
}
#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 View imageLayout = 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() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
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);
}
public void onLoadingComplete(Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
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) {
}
}
}
1st Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")
public void setWallpaper(){
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
try {
ImagePagerActivity.this.setWallpaper(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Gallery Example", "Image setted.");
}
2nd Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")
public void setWallpaper() {
try {
File file = new File("/sdcard/sampleimage");
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
bitmap.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
Context context = this.getBaseContext();
context.setWallpaper(bitmap);
Toast.makeText(getApplicationContext(), "Wallpaper has been set", Toast.LENGTH_SHORT).show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.set_wallpaper:
setWallpaper();
return true;
default:
return false;
}
}
3rd Attempt (My setResource(R.id.pager) is not getting the image from the viewpager.
public void setWallpaper() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.pager);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Conclusion
If i put the below codes above my onCreate my whole project will not run.
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
final int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
Try below code in ImagePagerActivity, i tested below code and it is working.
// fetch bitmap from view
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view
.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
// if we unable to get background drawable then we will set white color as wallpaper
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
public void setWall(int i) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
// below line of code will set your current visible pager item to wallpaper
// first we have to fetch bitmap from visible view and then we can pass it to wallpaper
myWallpaperManager.setBitmap(getBitmapFromView(pager.getChildAt(1)));
// below line of code will set input stream data directly to wallpaper
// myWallpaperManager.setStream(InputStream Data);
// below line of code will set any image which is in the drawable folder
// myWallpaperManager.setResource(R.drawable.icon);
} catch (IOException e) {
e.printStackTrace();
}
}
It will set current visible pager's item view(if it is progress wheel or image).
This might help you with your setbackground method...
String imagePath = ""; // YOUR PATH HERE
FileInputStream is = new FileInputStream(new File(imagePath));
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap b = BitmapFactory.decodeStream(bis);
Bitmap bitmapToUse = Bitmap.createScaledBitmap(b, parent.getWidth(), parent.getHeight(), true);
b.recycle();
if(!("").equals(imagePath)){
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
wallpaperManager.setBitmap(bitmapToUse);
}
That should set your file to your wallpaper no problem.
Can you be more specific on what you need for the "saveImage()"? Where are you trying to save from? Is it local storage? Or a website? More details please.
[Edit]
Updated code for clarity
[Edit 2]
To save images from a URL...
File imageFile = new File("image.png"); // This is location AND file name, all i put here was the filename
URL url = new URL("http://www.whatever.com/image.png");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
FileOutputStream out = new FileOutputStream(imageFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
[Edit 3]
The 'parent' is either your parent view (generally the view for the current activity). There are other ways to set this, the parent.width/height is how you're going to define how large the wallpaper image needs to be.

Event handling from Dialog box

I am creating a dialog box on a button click. For this I have created a class that extends Dialog. I created a XML file which contains the options (all are text view [7 text view]) in this XML file for each text view I have defined a tag android:onClick="imageProcessingHandler". When I click on the button from an activity it opens a Dialog box that is fine. Now when I click on any textview I am getting an error i.e. function not defined. I defined this function in the class as public that extends Dialog. Can anyone please help?
One more thing if I want to access Imageview; in the class that extends Dialog, of the activity from which Dialog box was opened so how could I do this?
I am trying to do the following:
ImageView imgView = (ImageView) findViewById(R.id.fullphoto); but in this case imgView contains null value :(
Code:
From activity "MyActivity" on button click I am creating an object as:
ShowOptionsInDialog displayDialog = new ShowOptionsInDialog(this, passedData);
displayDialog.show();
ShowOptionsInDialog Class:
public class ShowOptionsInDialog extends Dialog{
private Context context;
public ShowOptionsInDialog(Context context, ArrayList<String> data) {
super(context);
this.context = (Context) context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageprocessingoptions);
setTitle("Try options");
}
public void imageProcessingHandler(View view){
ImageView photo = (ImageView) findViewById(R.id.fullphoto);
}
imageprocessingoptions.XML
<TextView
android:id="#+id/invertColorText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:cursorVisible="false"
android:paddingLeft="10dp"
android:paddingBottom="5dp"
android:gravity="bottom"
android:text="Invert Color"
android:textSize="15dp"
android:clickable="true"
android:onClick="imageProcessingHandler" />
Activity code:
public class PhotoHandler extends Activity {
private Bundle intentExtra;
private String photoID;
private CommomObject _commonObject;
private Facebook facebook;
private ImageView photo;
private DownloadImageTask downlaodImageTask;
private ProgressDialog progDialog;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.photohandler);
intentExtra = getIntent().getExtras();
photoID = intentExtra.getString("PHOTO_ID");
displayPhoto();
}
private void displayPhoto() {
_commonObject = CommomObject.getInstance();
facebook = _commonObject.getFacebookInstance();
String imageURL = "https://graph.facebook.com/"+photoID+"/picture?type=normal&access_token="+facebook.getAccessToken();
photo = (ImageView) findViewById(R.id.fullphoto);
photo.setTag(imageURL);
photo.setScaleType(ScaleType.FIT_CENTER);
downlaodImageTask = new DownloadImageTask();
progDialog = new ProgressDialog(this);
progDialog.setMessage("Fetching photo...");
progDialog.show();
downlaodImageTask.execute(photo);
}
public class DownloadImageTask extends AsyncTask<ImageView, Void, Bitmap>{
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews){
this.imageView = imageViews[0];
return downloadImage((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap downloadImage(String url) {
Bitmap photo = null;
try {
URL u = new URL(url);
URLConnection c = u.openConnection();
c.connect();
BufferedInputStream stream = new BufferedInputStream(c.getInputStream());
photo = BitmapFactory.decodeStream(stream);
stream.close();
} catch (MalformedURLException e) {
Log.e("PhotoHandler", "malformed url: " + url);
} catch (IOException e) {
Log.e("PhotoHandler", "An error has occurred downloading the image: " + url);
}
progDialog.dismiss();
return photo;
}
}
public void footerHandler(View view){
switch(view.getId()){
case R.id.useButton:
break;
case R.id.saveButton:
break;
case R.id.shareButton:
break;
case R.id.photoEffect:
ArrayList<String> passedData = new ArrayList<String>();
ShowOptionsInDialog displayDialog = new ShowOptionsInDialog(this, passedData);
displayDialog.show();
break;
}
}
public void imageProcessingHandler(View view){
switch(view.getId()){
case R.id.invertColorText:
Bitmap newBitmap = ImageProcessing.doInvert(photo.getDrawingCache());
photo.setImageBitmap(newBitmap);
break;
case R.id.greyScaleText:
break;
case R.id.gammaCorrectionText:
break;
case R.id.sepiaEffectText:
break;
case R.id.embossingEffectText:
break;
case R.id.reflectionEffectText:
break;
case R.id.contrastText:
break;
}
}
}
1 - You need to put your public void abcFunction(View view) at your Dialog class.
2 - use yourdialog.findViewById(R.id.fullphoto);
I implement onCliclk listener in my code as:
TextView invert = (TextView) findViewById(R.id.invertColorText);
invert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do your work here
});
and for getting ImageView on Dialog I passed it in Dailog from activity.

Categories

Resources