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

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();
}
}}

Related

BitmapFactory.decodeStream leads to : D/skia: --- Failed to create image decoder with message 'unimplemented'

I'm trying to download an image from a URL by creating a Bitmap using
bitmapFactory.decodeStream(InputStream) and then imageView.setImageBitmap(bitmap) but I am always getting this error:
D/skia: --- Failed to create image decoder with message
'unimplemented'. package com.example.flickrapp;
Here is my code:
import statements will go here ...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Button b = (Button)findViewById(R.id.getanimage);
b.setOnClickListener(new GetImageOnClickListener() {
#Override
public void onClick(View v) {
super.onClick(v);
}
});
}
public class GetImageOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
AsyncFlickrJSONData imagesData = new AsyncFlickrJSONData();
imagesData.execute("https://www.flickr.com/services/feeds/photos_public.gne?tags=trees&format=json");
}
}
public class AsyncFlickrJSONData extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
String flickrUrl = strings[0];
JSONObject jsonFlickr = null;
URL url = null;
try {
url = new URL(flickrUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String s1 = readStream(in);
int lengthS = s1.length();
String s = (String) s1.subSequence(15, lengthS-1);
jsonFlickr = new JSONObject(s);
} finally {
urlConnection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonFlickr;
}
#Override
protected void onPostExecute(JSONObject jsonFlickr) {
super.onPostExecute(jsonFlickr);
try {
String firstUrl = jsonFlickr.getJSONArray("items").getJSONObject(0).getString("link");
AsyncBitmapDownloader firstAsyncImage = new AsyncBitmapDownloader();
firstAsyncImage.execute(firstUrl);
Log.i("JFL", firstUrl);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readStream(InputStream in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG, "IOException", e);
} finally {
try {
in.close();
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
return sb.toString();
}
}
public class AsyncBitmapDownloader extends AsyncTask<String, Void, Bitmap> {
ImageView firstImage = (ImageView) findViewById(R.id.image);
#Override
protected Bitmap doInBackground(String... strings) {
String imageUrl = strings[0];
Bitmap bm = null;
URL url = null;
try {
url = new URL(imageUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
bm = BitmapFactory.decodeStream(in);
} finally {
urlConnection.disconnect();
}
} catch(IOException e){
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
firstImage.setImageBitmap(bitmap);
}
}
}
Any Suggestions or Ideas are welcomed :)

Display to the image view on list view click

I am making this news application in which I m finding difficulties. here I am using list view.here I am performing background task also and even in this I am able to fetch all the news. The only thing which is not working is when I click on list item its respective image is not showing.
How can I take the image from url and when clicked on the item, the image of that respective list is opened?
public class MainActivity extends AppCompatActivity
{
ListView aboutNews;
Bitmap myImage;
ImageView newnewImage;
ArrayAdapter<String> myArrayAdapter;
ArrayList<String> newscontent , urlImageContent;
String finalUrl;
public void DisplayNews(String title, String urlToImage) {
myArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, newscontent); //i will not put this on oncreate because it will slow down my app.
aboutNews.setAdapter(myArrayAdapter);
newscontent.add(title);
urlImageContent.add(urlToImage);
}
public class downloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String news = jsonObject.getString("articles");
JSONArray arr = new JSONArray(news);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = jsonPart.getString("title");
String description = jsonPart.getString("description");
String urlToImage = jsonPart.getString("urlToImage");
String publish = jsonPart.getString("publishedAt");
String content = jsonPart.getString("content");
DisplayNews(title , urlToImage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) { //we have renamed strings to url
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in); //it adds everything to the bitmap.
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newscontent = new ArrayList<String>();
urlImageContent = new ArrayList<String>();
aboutNews = findViewById(R.id.aboutNews);
//.........................................................................
aboutNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
finalUrl = urlImageContent.get(i);
ImageDownloader task1 = new ImageDownloader();
try {
myImage = task1.execute(finalUrl).get();
newnewImage.setImageBitmap(myImage);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//.........................................................................
downloadTask task = new downloadTask();
try {
task.execute("https://newsapi.org/v2/top-headlines?country=in&apiKey=API_KEY");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Saving a URL to internal storage

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);

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" />

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