proper way to set android phone background - android

I have this codes to get Bing's photo of the day and set it as background.it works fine but I have some feelings that It's not the best way.
get json and return string :
private String GetHTTPData() {
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
stream = sb.toString();
urlConnection.disconnect();
} else {
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
if (stream != null) {
try {
JSONObject jsonObject = new JSONObject(stream);
JSONArray jArray = jsonObject.getJSONArray("images");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonobject = jArray.getJSONObject(i);
imageURL = "http://www.bing.com" + jsonobject.getString("url");
}
} catch (Exception e) {
e.printStackTrace();
}
}
//I replaced the original resolution with mine to change the image url
imageURL=imageURL.replace("1920x1080","1080x1920");
return imageURL;
}
default value for image is 1920x1080 and I was able to get more phone friendly image by replacing dimensions, but I'm not sure if 1080x1920 is the best one.
and then my AsyncTask
private class setWallpaper extends AsyncTask<Void,Void,Bitmap>{
#Override
protected Bitmap doInBackground(Void... strings) {
int response=-1;
InputStream in=null;
Bitmap bitmap=null;
String stream=GetHTTPData();
try {
URL url = new URL(stream);
URLConnection connection =url.openConnection();
HttpURLConnection urlConnection=(HttpURLConnection)connection;
urlConnection.setAllowUserInteraction(false);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
response=urlConnection.getResponseCode();
if (response==HttpURLConnection.HTTP_OK){
in=urlConnection.getInputStream();
}
bitmap= BitmapFactory.decodeStream(in);
in.close();
}catch (Exception e){
return null;
}
//I dont like to scale my bitmap but on lower resolution i cant get full width image
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Bitmap bitmapTouse=Bitmap.createScaledBitmap(bitmap,width,height,true);
bitmap.recycle();
return bitmapTouse;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
System.gc();
WallpaperManager manager=WallpaperManager.getInstance(context.getApplicationContext());
try {
manager.setBitmap(bitmap);
Log.d("SUCCESS----", "Finished");
} catch (IOException e) {
Log.d("FAILED----",e.getMessage());
}
}
}
I also don't like to scale my bitmap image but I had to.

Related

Android: Listview on fragmvent, set image from url

How to update ListViev with image from url
To download image I'm using:
downloadImage
public static Bitmap downloadImage(String iUrl) {
Bitmap bitmap = null;
HttpURLConnection conn = null;
BufferedInputStream buf_stream = null;
try {
Log.v(TAG, "Starting loading image by URL: " + iUrl);
conn = (HttpURLConnection) new URL(iUrl).openConnection();
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
buf_stream = new BufferedInputStream(conn.getInputStream(), 8192);
bitmap = BitmapFactory.decodeStream(buf_stream);
buf_stream.close();
conn.disconnect();
buf_stream = null;
conn = null;
} catch (MalformedURLException ex) {
Log.e(TAG, "Url parsing was failed: " + iUrl);
} catch (IOException ex) {
Log.d(TAG, iUrl + " does not exists");
} catch (OutOfMemoryError e) {
Log.w(TAG, "Out of memory!!!");
return null;
} finally {
if ( buf_stream != null )
try { buf_stream.close(); } catch (IOException ex) {}
if ( conn != null )
conn.disconnect();
}
return bitmap;
}
My ListView listen when button clicked, and then update ListView
try{
JSONObject jsonResponse = new JSONObject(response.toString());
JSONArray jsonMainNode = jsonResponse.getJSONArray("items");
//JSONArray Data = jsonResponse.getJSONArray("snippet");
for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("kind");
String number = jsonChildNode.optString("etag");
JSONObject item = jsonMainNode.getJSONObject(i);
JSONObject snippet = item.getJSONObject("snippet");
String title = snippet.getString("title");
String channelTitle = snippet.getString("channelTitle");
String pubDate = snippet.getString("publishedAt");
JSONObject thumbs = snippet.getJSONObject("thumbnails");
JSONObject thumb = thumbs.getJSONObject("default");
final String ico = thumb.getString("url");
new Thread(new Runnable() {
public void run() {
bmp = ImageManager.downloadImage(ico);
}
}).start();
countryList.add(createEmployee(title,channelTitle,pubDate, bmp));
}
simpleAdapter.notifyDataSetChanged();
ListView Updting, but without image. If Im using Image from #drawable all its ok.
The problem is that the bitmap hasn't finished being downloaded before you try to use it. When you call start() on a thread instance, that method returns immediately on the thread it was called on, while the new thread goes off and executes the run method (its own or that of the Runnable provided as a constructor parameter).
As start() returns immediately, you go straight on to create the employee before the bitmap has downloaded. As a result, bmp is null and there's no image to display.
You need to set up your code so that once an image is downloaded it is set on the appropriate view.

My Json array contains two images, How to download that through url/http and displays in activity

My json array contains two images, how to display that in activity? Those images are in the form of url. After and before are the imageviews, I want to know what is image download task and how can I use that.
after = (ImageView) findViewById(R.id.bfrdoogret);
before = (ImageView) findViewById(R.id.afterdogret);
}
class BackGround extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(Serialno.this, "",
"Searching. Please wait...", true);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected String doInBackground(String... params)
{
String values=getvalues();
return values;
}
#Override
protected void onPostExecute(String s)
{
dialog.hide();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
dis.setText(district);
city.setText(cit);
serialno.setText(serial_no);
gender.setText(gende);
loction.setText(latitude+ longitude);
}
}
public String getvalues()
{
String uri = "http://www.lorryguru.com/domains/dogs/retusingsno.php?district="+District+"&serialno="+SerialNo;
HttpGet httpGet = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1)
{
stringBuilder.append((char) b);
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
JSONArray arr = new JSONArray(stringBuilder.toString());
//result = jsonObj.getJSONArray(TAG_RESULT);
JSONObject c = arr.getJSONObject(0);
id = c.getString(TAG_ID);
district = c.getString(TAG_DISTRICT);
cit = c.getString(TAG_CITY);
serial_no = c.getString(TAG_SERIALNO);
gende = c.getString(TAG_GENDER);
wareno = c.getString(TAG_WARENO);
befor = c.getString(TAG_BEFORE);
afte = c.getString(TAG_AFTER);
latitude = c.getString(TAG_LATITUDE);
longitude = c.getString(TAG_LONGITUDE);
return "success";
}
catch (JSONException e)
{
return "accessproblem";
//e.printStackTrace();
}
Add this dependency in gradle compile 'com.squareup.picasso:picasso:2.5.2'
As per your getValues() method you will get url like this
String yourImageUrlHere= c.getString("whatever is your key");
Picasso.with(this)
.load(yourImageUrlHere)
.into(yourImageViewHere);
You have to add another async task after to your existing one, Code is following below.
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap>
{
private final WeakReference<ImageView> imageViewReference;
String murl;
ImageView showView;
public ImageDownloaderTask(ImageView imageView,String url) {
imageViewReference = new WeakReference<ImageView>(imageView);
murl=url;
showView=imageView;
}
#Override
protected Bitmap doInBackground(String... params) {
final Bitmap bitmap=downloadBitmap(murl);
if(murl!=null && bitmap!=null)
{
addBitmapToMemoryCache(murl, bitmap);
}
return bitmap;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
//addBitmapToMemoryCache(murl, bitmap);
}
}
}
}
}
private Bitmap downloadBitmap(String url)
{
HttpURLConnection urlConnection = null;
Bitmap bitmap;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK)
{
return null;
}
InputStream inputStream = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
catch (Exception e)
{
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
}
finally
{
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
Use Picasso to download image asynchronously from url.
You can use Picasso:
Picasso.with(this)
.load(url)
.into(imageView);

Why I am getting OutOfMemory Exception in Android? [duplicate]

I have question about this error.
I make favicon parser from URLs. I do this like:
public class GrabIconsFromWebPage {
public static String replaceUrl(String url) {
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("https?://.+\\..+?\\/");
Matcher m = p.matcher(url);
while (m.find()) {
sb.append(m.group());
}
return sb.toString();
}
public static String getFavicon(String url) throws IOException {
try {
Document doc = Jsoup.connect(url).get();
Element element = doc.head().select("link[href~=.*\\.(ico|png)]").first();
if (element != null) {
if (element.attr("href").substring(0, 2).contains("//")) {
return "http:" + element.attr("href");
} else if (element.attr("href").substring(0, 4).contains("http")) {
return element.attr("href");
} else {
return replaceUrl(url) + element.attr("href");
}
} else {
return "";
}
} catch(IllegalArgumentException ex) {
ex.printStackTrace();
} catch(OutOfMemoryError er) {
er.printStackTrace();
}
return "";
}
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);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
and how I get bitmap from url
Bitmap faviconBitmap = GrabIconsFromWebPage.getBitmapFromURL(
GrabIconsFromWebPage.getFavicon(
bookmarkData.get(position).getUrl() // url from which I want to grab favicon
)
);
And this code after uploading 20 images give me OutOfMemoryError. How can I fix this? Or optimize? Cuz in my list where I show this icons, can be more than 20 or 40 favicons...
I think, you would use universal image loader
The method as given snippet
// Load image, decode it to Bitmap and return Bitmap synchronously
ImageSize targetSize = new ImageSize(80, 50);
// result Bitmap will be fit to this size
Bitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, options);
And for out of memory bound you would add a line in manifest file
<application
...
android:largeHeap="true"
...
>
</application>
It was bad idea with parsing icons by myself. Google did it before us
http://www.google.com/s2/favicons?domain=(domain)

Android: Downloading images crashing app on API 8

I have a problem in API 8 with AsyncTask...
Here is my code...
try{
new loadPhotos().execute(""+USER._id,"date","DESC");
}catch(Exception e){
e.printStackTrace();
}
Before you ask... YES I am desperate, so I surrounded EVERYTHING with try{}catch
public class loadPhotos extends AsyncTask<String,Object,Void>{
ProgressBar pb;
ImageView img;
TableRow.LayoutParams paramsImage;
List<String> urlsOfImages;
TableLayout tl;
TableRow tr;
LayoutParams lp;
int numberOfPhotos=0;
#Override
protected void onPreExecute(){
urlsOfImages = new ArrayList<String>(); //There is stored urls of all images ( www.example.com/image1.jpg ... etc)
try {
allUserPhotoBitmaps.clear(); //allUserPhotoBitmaps is List<Bitmap>
pb = (ProgressBar) findViewById(R.id.profile_photos_progress_bar);
pb.setVisibility(View.VISIBLE);
tl = (TableLayout) findViewById(R.id.profile_photos_table_layout);
tl.removeAllViews();
tr = new TableRow(Profile.this);
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(lp);
}catch(Exception e){
Toast.makeText(Profile.this, "Error in onPreExecute", Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(String... arg) {
try{
// This function basicaly returns List<HashMap<String,String>> with informations about photos ( web_path, latitude, longitude, city, etc...)
allUserPhotoInformations = myDb.getUrlsOfUserImages(arg[0],arg[1],arg[2]);
}catch(Exception e){
Toast.makeText(Profile.this, "Error downloading images", Toast.LENGTH_SHORT).show();
}
if ( allUserPhotoInformations != null ) {
for (int i=0 ; i < allUserPhotoInformations.size() ; i++){
try{
Bitmap bm = getBitmapFromURL(allUserPhotoInformations.get(i).get("file_path"));
allUserPhotoBitmaps.add(bm);
publishProgress(bm,i);
}
catch(Exception e){
return null;
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Object... arg){
img = new ImageView(getBaseContext());
paramsImage = new TableRow.LayoutParams( (((int)screenWidth)/2)-16 , (((((int)screenWidth)/2)-15)/16)*11 );
paramsImage.setMargins(10,10,0,0);
img.setLayoutParams(paramsImage);
img.setBackgroundColor(Color.parseColor("#FF000000"));
try{
img.setImageBitmap((Bitmap) arg[0]);
}catch(Exception e){
Toast.makeText(Profile.this,"Cannot put Bitmap into ImageView",Toast.LENGTH_LONG).show();
}
img.setVisibility(View.VISIBLE);
img.setOnClickListener(new ImageListener((Integer)arg[1])); //here I passing index to onClickListener
tr.addView(img);
if ( numberOfPhotos==1 ){
try{
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}catch(Exception e){
e.printStackTrace();
Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
}
tr = new TableRow(Profile.this);
tr.setLayoutParams(lp);
numberOfPhotos--;
}
else {
numberOfPhotos++;
}
}
#Override
protected void onPostExecute(Void arg){
pb.setVisibility(View.GONE);
userPhotos.setText("uploaded: "+allUserPhotoBitmaps.size()+" photos");
if ( numberOfPhotos==1 ){
try{
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}catch(Exception e){
e.printStackTrace();
Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
}
tr = new TableRow(Profile.this);
tr.setLayoutParams(lp);
}
}
In my device ( API > 15 ) everything works great, but in API 10 it crashes the app... I you want , I can provide also OnClickListener or some othere methods...
Yes, here ... How I download pictures :
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
double width;
double height;
width = (screenWidth)/myBitmap.getRowBytes();
if ( myBitmap.getWidth() > myBitmap.getHeight() ){
Log.w("size","landscape");
height = ((myBitmap.getRowBytes()*width)/16)*11;
width = (height/11)*16;
}
else {
Log.w("size","protrait");
height = ((myBitmap.getRowBytes()*width)/11)*16;
width = (height/16)*11;
}
Bitmap bitmap = Bitmap.createScaledBitmap(myBitmap, (int)width, (int)height, true);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Profile.this, "Error parsing image to bitmap", Toast.LENGTH_LONG).show();
return null;
}
}
Any help ?
call new loadPhotos().execute(""+USER._id,"date","DESC"); in onCreate and Use Asynctask and try to avoid load in main thread. Your application crash one of the main reason may be if you are calling the methode in main thread.
Ex:
String zoomouturl = "your url";
new ImageDownload().execute(zoomouturl);
Try
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(zoomouturl, bmOptions);
return zoomouturl;
}
protected void onPostExecute(String imageUrl) {
if (!imageUrl.equals("")) {
Constants._image.setImageBitmap(bm);
} else {
Toast.makeText(this,
"not found proper bitmap.. ", Toast.LENGTH_LONG)
.show();
}
}
}
and
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}

Image not showing on image view

I am trying to set image on imageview but image is not show.
I am reading image url from json data and then trying to set it on ImageView but my image is not visible. No any exception occur.
Here is my code
HotelList.class
static final String TAG_DISHIMAGEURL = "dishimageurl";
......
String imageUrl = dishResult.getString(TAG_DISHIMAGEURL);
map.put(TAG_DISHIMAGEURL, imageUrl);
.....
dishimageurl1 = hm.get(TAG_DISHIMAGEURL).toString();
intent.putExtra("background", dishimageurl1);
HotelDetails.class
......
String dishimageurl = bundle.getString("background");
Bitmap bimage= getBitmapFromURL(dishimageurl);
imageView.setImageBitmap(bimage);
....
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
Toast.makeText(this, "showing image", Toast.LENGTH_LONG).show();
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
Toast.makeText(this, "showing exception", Toast.LENGTH_LONG).show();
return null;
}
}
I don't understand what happen with this code. No any exception but my image is not visible.
Please give me any reference.
Please Use below code for get image from url and display into imageview.
public class image extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("http://www.gophoto.it/view.php?i=http://1.bp.blogspot.com/-2LTvCCufBKc/T3L3KgcTj2I/AAAAAAAABbQ/Ki60e1LU9sE/s1600/Sachin%2BTendulkar.png");
RelativeLayout mRlayout1 = (RelativeLayout) findViewById(R.id.mRlayout1);
Drawable d=new BitmapDrawable(bitmap);
mRlayoutLogin.setBackgroundDrawable(d);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
you can view image by using this code.
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It seems you are downloading the image from UI thread. this will block the UI thread and will give you not responding error. as an easy way, you can use a library like Universal Image Loader
Universal Image Loader - GitHub
this will manage the image loading for you and avoid problems like incorrect urls, Out Of Memory error.

Categories

Resources