I'm trying to use WallpaperManager in a ViewPager. I've got a button which is supposed to set the current image in the ViewPager to wallpaper. My problem comes with the line of code wallpManager.setResource(newInt);... the integer it comes up with is always 0 (zero), and so the app crashes and LogCat says there's no Resource at ID #0x0. As a test to see if I'm getting the correct image URL I've done this:
String newStr = images[position];
CharSequence cs = newStr;
Toast.makeText(UILPager.this, cs, Toast.LENGTH_SHORT).show();
And the resulting Toast shows the correct image URL. I can't figure out how to convert the URL which is in the form of "http://www.example.com/image.jpg" to an Integer so that the WallpaperManager can use it. Here's what the whole button code looks like:
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
WallpaperManager wallpManager = WallpaperManager.getInstance(getApplicationContext());
String newStr = images[position];
int newInt = 0;
try{
newInt = Integer.parseInt(newStr);
} catch(NumberFormatException nfe) {
}
CharSequence cs = newStr;
try {
wallpManager.setResource(newInt);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(UILPager.this, cs, Toast.LENGTH_SHORT).show();
}
});
Set wallpaper from URL
try {
URL url = new URL("http://developer.android.com/assets/images/dac_logo.png");
Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
wallpaperManager.setBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Enjoy =)
A method wallpaperManager.setResource() requires resource id from your application. Example: I've ImageView with id "myImage" then call the method will look like as wallpaperManager.setResource(R.id.myImage).
In your case your id not valid.
Instead of wallpManager.setResource(0) you should use the wallpManager.setResource(R.drawable.yourimage) since it's expecting a drawable and there is none in your app with id = 0.
In your code
String newStr = images[position];
int newInt = 0;
try{
newInt = Integer.parseInt(newStr);
} catch(NumberFormatException nfe) {
}
Since newStr is never a number, always a url so NumberFormatException is caught always. Hence the value of newInt is always initialized to 0. Hence the error.
I realized that I have to download the image before I can set it as wallpaper! Thanks for your help AndroidWarrior and Owl. When I get the download code worked out, I'll post it. Owl showed me how to download the wallpaper:
//--- Wallpaper button
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
vpURL = new URL(images[position]);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
WallpaperManager wallpManager = WallpaperManager.getInstance(getApplicationContext());
try {
Bitmap bitmap = BitmapFactory.decodeStream(vpURL.openStream());
wallpManager.setBitmap(bitmap);
Toast.makeText(UILPager.this, "The wallpaper has been set!", Toast.LENGTH_LONG).show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
//--- END Wallpaper button
... and I also figured out how to download the ViewPager image as well (I need to do both in different areas of my app):
//--- Wallpaper button
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String vpURLStr = images[position];
GetVPImageTask downloadVPImageTask = new GetVPImageTask();
downloadVPImageTask.execute(new String[] { vpURLStr });
}
});
//--- END Wallpaper button
//--- Download ViewPager Image AsyncTask
private class GetVPImageTask extends AsyncTask<String, Void, Bitmap> {
ProgressDialog getVPImageDia;
#Override
protected void onPreExecute() {
super.onPreExecute();
getVPImageDia = new ProgressDialog(UILNPPager.this);
getVPImageDia.setMessage("Grabbing the image...");
getVPImageDia.setIndeterminate(false);
getVPImageDia.show();
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
try {
getVPImageDia.dismiss();
getVPImageDia = null;
} catch (Exception e) {
// nothing
}
Toast.makeText(UILNPPager.this, "The image be Downloaded!", Toast.LENGTH_SHORT).show();
//downloaded_iv.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
//--- END Download ViewPager Image AsyncTask
Related
I want to show a default picture when the result is null and here is my try:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
connection.disconnect();
return myBitmap;
} catch (IOException e) {
// tasvirdimg.setImageResource(R.drawable.p3_books);
e.printStackTrace();
return null;
}
}
}
a class to use getBitmapFromURL:
class RetrievePic extends AsyncTask<String, String, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
return JSONCommands.getBitmapFromURL(url);
}
}
execute RetrievePic class in ListAdapter:
RetrievePic retPic = new RetrievePic();
retPic.execute(JSONCommands.firstURL + MainActivity.books_array.get(position).tasvir);
Bitmap img = null;
try {
img = retPic.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
tasvirlimg.setImageResource(R.drawable.p3_books);
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
tasvirlimg.setImageResource(R.drawable.p3_books);
e.printStackTrace();
}
tasvirlimg.setImageBitmap(img);
when the picture is null it doesn't show any thing but it should show the default picture which is R.drawable.p3_books. thanks to your helps.
what you want to do is in your implementation of your adapter's getView() method, something like this,
...
final imageView = ...;
imageView.setImageBitmap(defaultBitmap);
new AsyncTask<Void,Void,Bitmap>() {
public Bitmap doInBackground(Void... params) {
// get bitmap from `net, or return null if failure
}
public void onPostExecute(Bitmap result) {
if (result != null) {
imageView.setBitmap(result);
}
}
}.execute();
this way, the default is set. if you happen to get the network result, change the default.
You could try this:
if(img == null)
{
tasvirlimg.setImageDrawable(R.drawable.p3_books);
}
else
{
tasvirlimg.setImageBitmap(img);
}
Why not set the default pic of item in xml and then the default pic would be replaced when result is not null
<ImageView
...
android:src="#drawable/p3_books"
/>
EDIT:
class RetrievePic extends AsyncTask<String, String, Bitmap>{
final image = (ImageView) findViewById(R.id.limg_tasvir);
#Override
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
return JSONCommands.getBitmapFromURL(url);
}
#Override
protected void onPreExecute() {
runOnUiThread(new Runnable() {
#Override
public void run() {
image.setBackgroundResource(R.drawable.p3_books);
}
});
}
}
I'm having some troubles displaying an image I am fetching from a URL into an ImageView. With the code I have at the moment, I am getting absolutely nothing. Is there a problem with this code?
Drawable img = image.LoadImageFromWeb(icon);
imageView.setImageDrawable(img);
public static Drawable LoadImageFromWeb(String iconId) {
try {
String url = "http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId + ".png";
InputStream is = (InputStream) new URL(url).getContent();
Drawable icon = Drawable.createFromStream(is, "src name");
return icon;
} catch (Exception e) {
return null;
}
}
try this function
private void downloadImage()
{
Bitmap bitmap = null;
try {
URL urlImage = new
URL("http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId +
".png");
HttpURLConnection connection = (HttpURLConnection)
urlImage.openConnection();
InputStream inputStream = connection.getInputStream();
//****bitmap is your image*****
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and use asyncTask to wait until downloading the image like this
private class Asyn_SaveData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//get the random string from prefs
if (context != null)
downloadImage();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//do what you want after the image downloaded
}
}
Note: AsyncTask must be subClassed, and after the doInBackground finish its job it calls automatically the onPostExecute
protected Bitmap doInBackground(String...params) {
// TODO Auto-generated method stub
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(params[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
b1=bm;
bis.close();
is.close();
} catch (IOException e)
{
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
return null;
}
// TODO Auto-generated method stub
super.onPostExecute(result);
i1.setImageBitmap(b1);
Animation rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
i1.startAnimation(rotation);
//System.out.println("imageview is working");
try {
System.out.println("thread going to sleep");
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i1.setImageBitmap(b1);
}
i am showing an image from the internet in an imageview through a bitmap now i am having another image this bitmap in by updating the url but i am not able to show the this image only previous image is showing,and if i run this in a loop only the last image is shwoing?any suggestions
Call this from your OnCreate or from where ever you want to initial the download of code from network
new Thread(new Runnable() {
public void run() {
Drawable drawable = createDrawableFromURL(_mDrawingURL);
Message msgURL = new Message();
msgURL.arg2 = URL_CONSTANT;
msgURL.obj = drawable;
_handler_url.sendMessage(msgURL);
}
}).start();
} catch (JSONException e) {
e.printStackTrace();
}
}
This method will be used to download the image from internet:
private Drawable createDrawableFromURL(String urlString) {
Drawable image = null;
try
{
InputStream inputStream = new URL(urlString).openStream();
image = Drawable.createFromStream(inputStream, null);
inputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
image = null;
} catch (IOException e) {
e.printStackTrace();
image = null;
}
return image;
}
After downloading the image, the imageview will be update with the image.:
private Handler _handler_url = new Handler(){
public void dispatchMessage(Message msg) {
switch (msg.arg2) {
case URL_CONSTANT:
Drawable drawable = (Drawable) msg.obj;
if(drawable!=null)
_mImageView.setImageDrawable(drawable);
break;
default:
break;
}
};
};
I want to set ImageView bitmap from our network drive. But i getting Unable to connect to server: Unable to log in to server (PASS): 141.11.11.247 error.
Here is my download ant setBitmap code for this :
public class ResimCek implements Runnable {
int resimID = 0;
public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;
}
public void run() {
try {
ImageView resim = (ImageView) findViewById(resimID);
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(
"file://141.11.11.247/foto_metod/Parca/"
+ Integer.toString(resimID) + ".jpg")
.getContent());
resim.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my last code :
public class ResimCek implements Runnable {
int resimID = 0;
public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;
}
public void run() {
int resID = getResources().getIdentifier(Integer.toString(resimID) , "tag", getPackageName());
ImageView resim = (ImageView) findViewById(resID);
Drawable image = ImageOperations(getBaseContext(),"http://141.11.11.206/parca/" + Integer.toString(resimID) + ".jpg" ,"I" + Integer.toString(resimID) + ".jpg");
// ******************************************************
resim.setImageDrawable(image); // I GOT THE ERROR HERE!!!
}
}
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(new URL(url).openConnection().getInputStream(),saveFilename);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
Thanks for your help.
may be you forgot to declare internet permission in your manifest file, check it please.
Download FtpClient
And use username and password to login.
Look at this documentation, hope it will help you.
I used the code below to fetch the image from a url but it doesn't working for large images.
Am I missing something when fetching that type of image?
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageBitmap(loadBitmap("http://www.360technosoft.com/mx4.jpg"));
//imgView.setImageBitmap(loadBitmap("http://sugardaddydiaries.com/wp-content/uploads/2010/12/how_do_i_get_sugar_daddy.jpg"));
//setImageDrawable("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg");
//Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
//imgView.setImageDrawable(drawable);
/* try {
ImageView i = (ImageView)findViewById(R.id.ImageView01);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
System.out.println("hello");
} catch (IOException e) {
System.out.println("hello");
}*/
}
protected Drawable ImageOperations(Context context, String string,
String string2) {
// TODO Auto-generated method stub
try {
InputStream is = (InputStream) this.fetch(string);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
You're trying to download the Large Image from within the UI Thread....This will cause an ANR (Application not Responding)
Use AsyncTask to download the images, that way, a seperate thread will be used for the download and your UI Thread wont lock up.
see this good example that loads image from server.
blog.sptechnolab.com/2011/03/04/android/android-load-image-from-url/.
If you want to download the image very quickly then you can use AQuery which is similar to JQuery just download the android-query.0.15.7.jar
Import the jar file and add the following snippet
AQuery aq = new AQuery(this);
aq.id(R.id.image).image("http://4.bp.blogspot.com/_Q95xppgGoeo/TJzGNaeO8zI/AAAAAAAAADE/kez1bBRmQTk/s1600/Sri-Ram.jpg");
// Here R.id.image is id of your ImageView
// This method will not give any exception
// Dont forgot to add Internet Permission
public class MyImageActivity extends Activity
{
private String image_URL= "http://home.austarnet.com.au/~caroline/Slideshows/Butterfly_Bitmap_Download/slbutfly.bmp";
private ProgressDialog pd;
private Bitmap bitmap;
private ImageView bmImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bmImage = (ImageView)findViewById(R.id.imageview);
pd = ProgressDialog.show(this, "Please Wait", "Downloading Image");
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { image_URL });
// You can also give more images in string array
}
private class DownloadWebPageTask extends AsyncTask<String, Void, Bitmap>
{
// String --> parameter in execute
// Bitmap --> return type of doInBackground and parameter of onPostExecute
#Override
protected Bitmap doInBackground(String...urls) {
String response = "";
for (String url : urls)
{
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
// Only for Drawable Image
// try
// {
// URL url = new URL(image_URL);
// InputStream is = url.openStream();
// Drawable d = Drawable.createFromStream(is, "kk.jpg");
// bmImage.setImageDrawable(d);
// }
// catch (Exception e) {
// // TODO: handle exception
// }
// THE ABOVE CODE IN COMMENTS WILL NOT WORK FOR BITMAP IMAGE
try
{
URL m = new URL(image_URL);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i, 1024*8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[4096];
while((len = bis.read(buffer)) != -1)
{
out.write(buffer, 0, len);
}
out.close();
bis.close();
byte[] data = out.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
catch (Exception e)
{
e.printStackTrace();
}
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result)
{
if(result!=null)
bmImage.setImageBitmap(result);
pd.dismiss();
}
}
}