Saving a URL to internal storage - java

So the title slightly misleading. I've put the URl in a drawable.
public Drawable getDrawableFromURL(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
I had it has a bitmap originally but kept getting nullpointers and android.os.NetworkOnMainThreadException, which I've managed to fix, but the nullpointer comes around again. So I'm stuck on how to save to internal, because I can save it to SD fine.
Thanks

try this
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
// save your bitmap here
}
}
to call this AsyncTask use below code
new DownloadImage().execute(url);

Related

How to get data from sqlite, and show it using stackwidget?

I want to retrieve url image from sqlite, then convert it to bitmap and show it into stackwidget. When insert url image manually, one by one, it works well. But when i use url image from sqlite, application is force close and my stackwidget doesn't show image.
public class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
...
StackRemoteViewsFactory(Context context) {
mContext = context;
}
#Override
public void onCreate() {
FilmHelper filmHelper = FilmHelper.getInstance(mContext);
filmHelper.open();
}
#Override
public void onDataSetChanged() {
DatabaseHelper databaseHelper;
databaseHelper = new DatabaseHelper(mContext);
SQLiteDatabase databases = databaseHelper.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(databases, "note");
ArrayList<Film> ini = new ArrayList<>();
Cursor c =FilmHelper.database.rawQuery("SELECT * FROM note" , null );
c.moveToFirst();
Film note;
int i;
if (c.getCount() > 0) {
for (i=0; i < count; i++ ) {
do {
note = new Film();
note.setId(c.getInt(c.getColumnIndexOrThrow(_ID)));
note.setPosterPath(c.getString(c.getColumnIndexOrThrow(IMAGE)));
ini.add(note);
try {
URL url = new URL("https://image.tmdb.org/t/p/w600_and_h900_bestv2/" +
ini.get(i).getPosterPath());
Bitmap image = BitmapFactory.decodeStream(url.openStream());
mWidgetItems.add(image);
} catch (IOException e) {
System.out.println(e);
}
c.moveToNext();
} while (!c.isAfterLast());
}
}
c.close();
databases.close();
...
}
you are doing network consuming task like converting url to bitmap inside forloop in main thread.
you can use Asynctask that will download bitmap from url to you in onPostExecute and from that you can add bitmap to mWidgetItems.
class ConvertUrltoBitmap extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public Bitmap doInBackground(String... urls) {
Bitmap map = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection =(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
map= BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
protected void onPostExecute(Bitmap bitmap){
try {
mWidgetItems.add(bitmap);
}catch (Exception exception){
exception.printStackTrace();
}
}}

How to create image from webService, Android

So, I have this app that is connected to a WebService and I am already retrieving data from there, now I want to retrieve a image link and make that the imageView gets that image trough the link. Is that even possible? Appreciate any help :D
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
System.out.println(jsonObject1.optString("Designacao"));
String K_PAIS = jsonObject1.getString("K_PAIS");
String Designacao = jsonObject1.getString("Designacao");
String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
String URL_IMAGEM = "http://something.something.pt" + URL_IMAGE_SMALL;
new DownloadImage(imageView6).execute(URL_IMAGEM);
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
listaPaises.add(pais);
}
}
System.out.println(jsonObject.optString("Designacao"));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
{...}
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
You can use Picasso, a wonderful image library.
Example:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Add dependency via Gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
you can use any third party library
example use Glide library
this library will help you to fetch and display image on ImageView from url.
example:
Glide.with(context).load(image_url).into(your_image_view);
here is link for that library : https://github.com/bumptech/glide
You have to set your ImageView inside your XML as you normally do. Then you can use any third party library like Picasso or Glide that will load the image from the url and set it to your ImageView in your activity/fragment.
In your app build.gradle add
compile 'com.github.bumptech.glide:glide:3.7.0'
use this code to load image from url
Glide.with(getApplicationContext()).load("image_url").into(ImageView);
try this if you dont want to use third party library
new DownloadImage(imamgeview).execute(url);
create a Async Task
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
i hope you it will work in your case
step 1: create class named DownloadImage
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Step 2: execute AsyncTask
new DownloadImage(imgUserProfile).execute(userProfileUrl);
**Json Url like this: ** https://graph.facebook.com/1220130444748799/picture?height=400&width=400&migration_overrides=%7Boctober_2012%3Atrue%7D

How to get Image from url and store it in Bitmap variable

I am new for android. I Want to get image from url and set into Bitmap variable.I tried so many code but i didn't get.
Here my code:
String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;
ImageDownloaderTask.java
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bImage;
#Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
bImage = result;
}
}
Thanks in advance...
Here is code you can use
new DownloadImage().execute("https://www.google.com/intl/en_ALL/images/logo.gif");
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// Do whatever you want to do with the bitmap
}
}
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) {
// Log exception
return null;
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
From your code,
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;
you get an empty image because your ImageDownloaderTask not yet finished downloadin the image.
Try updating image on your onPosExecute:
protected void onPostExecute(Bitmap result) {
bImage = result;
// Update image here.
}
Bitmap bmp;
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmp=result
}}
try this,
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
In my opinion its best to create an interface for this:
public interface ImageDownloaderResponse {
void downloadFinished(Bitmap bm);
}
In your ImageDownloaderTask:
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bImage;
public ImageDownloaderResponse delegate = null;
#Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
delegate.downloadFinished(result);
}
}
Then let your activity/fragment implement the interface like this:
public class MainActivity extends AppCompatActivity implements ImageDownloaderResponse {
And use your Downloadtask like this:
String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(url);
And add this to your activity/fragment:
#Override
public void downloadFinished(Bitmap bm) {
Bitmap bitmap = bm;
}
Try below code:
URL url = new URL("https://www.google.com/intl/en_ALL/images/logo.gif");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
And add this permission in manifest:
<uses-permission android:name="android.permission.INTERNET" />

Android load image from url and show imageview

i try to load image fro url and show imageview.i wrote code witch can download image and show it.but now i want to download facebook user image and show it.i know how i can check facebook user image "like this
http://graph.facebook.com/user id /picture?width=80&height=80
when i run programm i have RuntimeException
this is a my source
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#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) {
user_img.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;
}
}
new GetXMLTask().execute((new String[] { URL }));
if my url would be for example http://mywebsite./pic.jpg then program working perfect but i want show facebook user image
You should be using picasso.
Add dependency into your project. And further just a singe line of code will do the task.
Picasso.with(context).load("http://somepath/someimage.png").into(imageView);
No need of writing thread and optimizing bitmaps.
You can refer : http://square.github.io/picasso/

Downloading and displaying images from an array of URLs to multiple different ImageViews on Android

I have this code to download a photo from a URL and display it in an ImageView on Android.
I am not sure how to loop this if I had a ArrayList or Array of multiple Urls to download and display on different ImageViews. I would appreciate any help or insight on how to proceed! Thank you!
public class DisplayPhotoTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
//sets bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
ImageView imageView1 = (ImageView) findViewById(R.id.imageView);
imageView1.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;
}
}
You can for example make a result of AsyncTask as List ant write something like this
protected Bitmap doInBackground(String... urls) {
List<Bitmap> bitmaps = new ArrayList<Bitmap>;
for (String url : urls) {
bitmaps.add(downloadImage(url));
}
return bitmaps;
}
protected void onPostExecute(List<Bitmap> result) {
//...
}
But what I really would recommend you is to use Volley library written by Google, it has really easy and powerful API (here is Google I/O session about it https://developers.google.com/live/shows/474338138 and repository https://android.googlesource.com/platform/frameworks/volley/)

Categories