How can i "update" a banner in Android? - android

I have an app where I have one banner in the top with News, when I want to put other news I need to open the code and change the resource .jpg and the Link. There is a way to change the banner and the Link (or at least the banner) without modifing the code? Idk maybe uploading it to a webpage or something like this.
thanks

My suggestion would be to upload a banner.jpg to a server that your app can access and dynamically load. This would prevent having to update your app every time you want to change the banner, and makes it cleaner (no excessive Google Play updates). To do actually load the image you can use this code:
ImageView image1 = (ImageView) findViewById(R.id.mybanner);
new Thread(new Runnable(){//create a new thread so we can do network operations
#Override
public void run() {//main thread function
try {//attempt to do network stuff
URL url = new URL("http://your-hosting-site.com/banner.jpg");//create aURL object with the path to your banner
HttpURLConnection con = (HttpURLConnection) url.openConnection();//create the connection object from the url
con.setReadTimeout(15000);
con.setConnectTimeout(15000);
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();//connect to the server
InputStream is = con.getInputStream();//get the stream so we can read the image
Drawable d = Drawable.createFromStream(is, "MyBanner");//create a drawable from the image
Bitmap bmp = ((BitmapDrawable) d).getBitmap();//create a bitmap from the drawable
final Drawable dS = new BitmapDrawable(Bitmap.createScaledBitmap(bmp, 192, 192, true));//scale it to whatever size you need
con.disconnect();//disconnect now that we're done
runOnUiThread(new Runnable(){//run UI update code on the main thread
#Override
public void run() {
image1.setImageDrawable(dS);//set the imageview to the banner we downloaded
}
});
} catch (MalformedURLException e) {//catch url error
e.printStackTrace();
} catch (IOException e) {//catch io error when downloading
e.printStackTrace();
}
}
}).start();//run the thread
Change "http://your-hosting-site.com/banner.jpg" (line 6) to wherever you uploaded the .jpg, R.id.mybanner (line 1) to the id of your ImageView, and "MyBanner" (line 14) to whatever you want to call the image.
You might want to save your banner to the phone and only check after X days/hours for an update to save data, but that is up to you.

Related

loading full image from url into image view with any image loading library

I'm downloading an image from a URL and displaying it in an ImageView. I need to download the image at its full original size. I've tried Glide, Picasso and Universal Image Loader with no success. Is there any library or mehod out there to achieve this? I even tried making my own AsyncTask to do it, something like this:
public class ImageLoader extends AsyncTask<Void, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Void... params) {
try {
URL url = new URL(bundle.getString("selectedImage"));
HttpURLConnection conn =
(HttpURLConnection)url.openConnection();
conn.setReadTimeout(6000);
conn.setConnectTimeout(6000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int respose = conn.getResponseCode();
InputStream is = conn.getInputStream();
BufferedInputStream bufferedInputStream = new
BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bufferedInputStream);
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
but no success. Anyone have anything to help me?
1) Try to use Volley library.
https://developer.android.com/training/volley/request.html#request-image
2) Use WebView instead ImageView
I'm not really sure what you mean by "its full original size". I haven't experienced any automagic scaling of images simply by downloading them.
Maybe you could double-check that you have an appropriate android:scaleType on the target ImageView. You can read more on the different values of the scale type property here: http://developer.android.com/reference/android/widget/ImageView.ScaleType.html
If you want to pan the image, like an "unscaled" web page in the browser (typically when the image is bigger than the screen), you might need to add further logic to manage this. Maybe it could be as easy as having a ScrollView wrap your ImageView (which then would wrap its content, of course).
The error was down to photo bucket giving me a scaled down URL instead I used flikr and on my device I get an image almost identical to my original (Picasso limit is 2048x2048) but on other devices I still seem to get a 1080 x 910 image, will investigate further but it seems the answer is not to use photo bucket

Android ParseFile array not loading images

I have an array of ParseObjects that are being displayed in a list view. Three text views are loaded into my custom cell, and then there's an image in a ParseFile that should also be loaded. The code I have gets the first cell to load correctly, but in every other cell the image doesn't load. Here's my code:
this.origImage = (ParseFile) posts.get(position).get("image");
try {
Log.d("MyMessage", "Gonna convert image");
this.imageData = this.origImage.getData();
this.options = new BitmapFactory.Options();
this.options.inDither = true;
this.options.inPreferredConfig = Bitmap.Config.ARGB_8888;
this.options.inSampleSize = 8;
this.notConvertedYet = BitmapFactory.decodeByteArray(this.imageData, 0, this.imageData.length, this.options);
if (this.notConvertedYet != null)
this.myBitmap = rotateImage(90, this.notConvertedYet);
else
this.myBitmap = this.notConvertedYet;
mHolder.picImageView.setImageBitmap(this.myBitmap);
Log.d("MyMessage", "Converted image");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What is happening that's messing it up?
when its bound to a list adapter, what does the
posts.get(position).get("image");
do actually? Is the parse SDK calling a series of AsyncTasks for the network Http GET on the actual URL in parse's file CDN?
You may have to find out more about what its doing because , as is, it may not be very efficient as used by the Adapter.getView()...
Any image loader framework like Volley, like Universal Image Loader, like AQuery will work like an api where you make a call providing the ImageView and the CDN URL for the image as parms. The framework will handle multithreading, pooled Parse.com connections , memCache and fileCache for all images. When using parse to store bitmaps in the file CDN you can still use any of the image loading frameworks.
AQuery sample in an adapter...
ImageView thumbnail=(ImageView)vi.findViewById(R.id.imageView1); // thumb image
mAquery.id(thumbnail).width(110).image($thumbUrl_CDN,
true, true, 0, R.drawable.default_video, null, 0, mAspectRatio);
Your code looks ok.. maybe the reason all the imageViews are black is that the adapter did not have time to get the files loaded across the network and the loop statement did not block the UI thread??

Image load in webview or not?

I'm using a webview to show image. I used the webview.loadUrl("imagepath"); these code to show image but the webview failed to load the image then i want to show my default image in the webview.
You have to add file:/// before your image Path.
Did you try with something like
// Exemple from asset folder
webview.loadUrl("file:///android_asset/mu_image.jpg");
// From external storage
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file://"+ base + "/YOUR_FILE.jpg";
webview.loadUrl(base);
EDIT (after understanding the question ...)
You have to check if your web file exist
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
Then 2 choices :
- The file exists, show it
- Or, show your default image
Source : Check if file exists on remote server using its URL
It is not a good practice to load image in a webview.
The solution is to use some kind of image loader and the best one for your case is VOLLEY. It provides cache and image loading functionality better then any other image loader.
Here is the link.

Set ImageView using URL

I have an Image on my server. The URL for the image is something like:
http://www.mydomain.com/123456uploaded_image.jpg
I am trying to set this image to my ImageView. Here is the code that I tried:
try{
String url1 = myeventimagearray[position];
URL ulrn = new URL(url1);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = (InputStream) con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
iveventimg.setImageBitmap(bmp);
else
Log.i("Image","Not set");
} catch(Exception e) {
e.printStackTrace();
}
When I try this, my imageview is empty, i.e., it doesn't set the image view and i get this System err in my logcat:
java.lang.ClassCastException: libcore.net.http.FixedLengthInputStream cannot be cast to com.example.eventnotifier.Base64$InputStream
Base46.java is a file I found from the internet that Encodes and decodes to and from Base64 notation.
Any idea why I'm getting this System.error?
Thank you
Use URlImageViewHelper, it will take care of loading url into imageview.
Refer this
It will take care of caching, loading in background etc. by itself.
This is not an easy answer but you should use a caching system.
See https://github.com/chrisbanes/Android-BitmapCache for an excellent one!
Simply swap the ImageView for NetworkCacheableImageView and then use loadImage( "http://....", true );
You are likely getting an exception because you are trying to do network io on the main thread. Consider using a loader or an AsyncTask to load your image.
Check your logs, I bet you are printing a stack trace in the auto generated catch block.
new Thread(new Runnable() {
public void run() {
final Bitmap b = bitmap = BitmapFactory.decodeStream((InputStream)new URL(myeventimagearray[position]).getContent());
iveventimg.post(new Runnable() {
public void run() {
iveventimg.setImageBitmap(b);
}
});
}
}).start();
Use Picasso to fetch image from url. Implement 'com.squareup.picasso:picasso:2.71828' in build.gradle and in java
Picasso.get()
.load(url) // http://www.example.com/123456uploaded_image.jpg
.resize(50, 50)
.centerCrop()
.into(imageView)

Display image from URL - sizing and screen orientation problems

I am trying to display an image from a URL, which may be larger than the screen dimensions. I have it kind of working, but I would like it to scale to fit the screen, and I also have problems when the screen orientation changes. The image is tiny, and I would like it to scale its width to the screen as well. (In both cases, I would like the image to fill the screen width with scrollbars (if necessary for height).
Here is my ImageView:
<ImageView android:id="#+id/ImageView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true">
</ImageView>
Here is the java code which loads the image: (some error handling code removed for simplicity)
Object content = null;
try{
URL url = new URL("http://farm1.static.flickr.com/150/399390737_7a3d508730_b.jpg");
content = url.getContent();
}
catch(Exception ex)
{
ex.printStackTrace();
}
InputStream is = (InputStream)content;
Drawable image = Drawable.createFromStream(is, "src");
Image01.setImageDrawable(image);
I have tried different settings for android:scaleType. I'm sorry if this question has been asked before. I've gone through a number of tutorials on the subject, but they don't seem to work for me. Not sure if it has anything to do with the way the image is loaded. (from the web instead of a local resource)
Another issue is that sometimes the image doesn't even load. There are no runtime errors, I just get nothing in the ImageView.
Please let me know if you need more information or clarification.
the issue about that "sometimes the image doesn't even load" is related to the context so I used this functions to solve that issue
public Object fetch(String address) throws MalformedURLException,
IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private Drawable ImageOperations(Context ctx, String url) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
so to fill the screen width with your image you must have a code like this
try{
String url = "http://farm1.static.flickr.com/150/399390737_7a3d508730_b.jpg";
Drawable image =ImageOperations(this,url);
Image01.setImageDrawable(image);
}
catch(Exception ex)
{
ex.printStackTrace();
}
Image01.setMinimumWidth(width);
Image01.setMinimumHeight(height);
Image01.setMaxWidth(width);
Image01.setMaxHeight(height);
UPDATE::
if you load a big size image obviously you will have to wait more time, and download problems could be caused for UnknowHostException.
yes you are right you will save your image locally, the local access is faster than the download.
to avoid problems on rotation change set your configChanges="keyboardHidden|orientation" property inside your Manifest.xml
<activity android:name=".myActivity"
...
android:configChanges="keyboardHidden|orientation" >
...
/>

Categories

Resources