Android Get Image.png from JSON - android

I have a JSON that contains strings and image.png objects.
I can get the string the usual way, but how do I get the Images? All tutorials I found use jsons with specific image URLs instead of the png. Look at the JSON and you will understand it:
{
"draw": 0,
"recordsTotal": 8,
"recordsFiltered": 8,
"data": [{
"start_date": "2017-03-08 17:45:00",
"competition_name": "Primera Divisi\u00f3n",
"competition_logo": "laliga.png",
"home_team": "Deportivo La Coru\u00f1a",
"home_team_logo": "deportivo-la-coruna-2018.png",
"home_team_slug": "deportivo-la-coruna-640",
"event_status": "",
"away_team": "Real Betis",
"away_team_logo": "real-betis-2025.png",
"away_team_slug": "real-betis-639",
"event_id": "3404",
"game_minute": ""
},
My code has the usual format to get json objects from array.
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.length() > 0) {
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray.length() > 0){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPart = jsonArray.getJSONObject(i);
String start_date= jsonPart.getString("start_date");
I want the home_team_logo and away_team_logo images to put on a ImageView.

If you have the path in which those images are, you can just download the images in asynchronous manner, like so:
import java.lang.ref.WeakReference;
public static class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0], params[1]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.potch_app_logo_icon);
imageView.setImageDrawable(placeholder);
}
}
}
}
private static Bitmap downloadBitmap(String url, String localPath) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != 200) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(localPath));
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
Then in your code:
String away_tema_logo_image_name = jsonPart.getString("away_team_logo");
new ImageDownloaderTask(yourImageView).execute(yourUrl, yourLocalPath);
This will save the image to local storage on device, so you need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

As far as you write above, you can get the PNG files name just like this:
String start_date= jsonPart.getString("home_team_logo");
May be the problem is you want show the picture in the view, I think first you want add the URL prefix where from you load the JSON result, and then pass the URL to Glide/ImageLoader like framework to show it on the imageView.

Related

Android studio Load Image url into listview

I want to fill a listview with text and images.
I receive this information by my mysql database, in JSON format.
I have a field called "FOTO" and I store into this the path to the photo like: "http://....../1.png".
I get and android.os.NetworkOnMainThreadException using this code, but I don't know how to do different.
I parse the JSON and pass the values to the listadapter. I need to pass also the icon so the bitmap value, but I need to download it from the server.
public class DisplayListView extends AppCompatActivity {
final static String TAG = "sb.dl";
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
TeamAdapter teamAdapter;
ListView listView;
Bitmap icon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
teamAdapter = new TeamAdapter(this, R.layout.row_layout);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(teamAdapter);
json_string = getIntent().getExtras().getString("json_data");
Log.d(TAG, "json_string " + json_string);
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("risposta");
int count = 0;
String nome, num, data;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
nome = JO.getString("NOME");
num = JO.getString("NUMERO");
data = JO.getString("DATA_NASCITA");
String url = JO.getString("FOTO");
icon = LoadImageFromWebOperations(url);
Team team = new Team(nome, num, data, icon);
teamAdapter.add(team);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Simone", e.toString());
Log.d("Simone", e.getMessage());
}
}
public static Bitmap LoadImageFromWebOperations() {
try {
URL url = new URL("url");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
} catch (Exception e) {
Log.d(TAG, "bitmap error: " + e.toString());
Log.d(TAG, "bitmap error: " + e.getMessage());
return null;
}
}
}
I had the same problem.
I solved with an AsyncTask that download the bitmaps.
I used this code:
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = null;
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Errore durante il download da " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
you call it by:
new ImageDownloaderTask(holder.imageView).execute(urlPhoto);
Hope this help :)
try using picasso to load in your image.
http://square.github.io/picasso/
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
this will load the image into your imageview asynchronously.
get the library using the gradle import
compile 'com.squareup.picasso:picasso:2.5.2'

Decoding a jpeg in Android

I have JSON data that I am viewing from a URL. There are many JSON objects in the JSON array, one of which is a jpeg image.
I would like to send that image to a listview in an Android app.
Right now I have the image JSON object linked to a private static final String TAG in my Java file. However, I realize that I must decode the image or I will receive an error of: Unable to decode stream: java.io.FileNotFoundException and resolveUri failed on bad bitmap uri.
I am in a long and ongoing search to understand how to decode the JSON jpeg image, much of such research taken place by viewing posts on this website so please do not mark as a duplicate question.
public class JSONBuilderActivity extends ListActivity {
private ProgressDialog pDialog;
//URL to get JSON
private static String url = "";
//JSON Node names
private static final String TAG_CARS = "cars"; //root
private static final String TAG_CARID = "CarID";
private static final String TAG_CARVIN = "CarVIN";
private static final String TAG_IMG= "CarMainImage";
JSONArray carid = null; //Initializes JSON array
static String response = null;
//Hashmap for ListView
ArrayList<HashMap<String, Object>>caridList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lv = getListView();
//Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Gets values from selected ListItem
String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
String car_vin = ((TextView) view.findViewById(R.id.car_vin)).getText().toString();
String model_img = ((ImageView) view.findViewById(R.id.model_img)).getTag().toString();
Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
//Sends data to MainActivity
in.putExtra("TAG_CARS", cars);
in.putExtra("TAG_CARID", car_id);
in.putExtra("TAG_CarVin", car_vin);
in.putExtra("TAG_IMG", model_img);
startActivity(in);
}
});
//Calls async task to get json
new GetCars().execute();
}
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//Checks http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
//Adds post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//Appends params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, Object>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String car_vin = c.getString(TAG_CARVIN);
Log.d("car_vin", car_vin);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.model_img, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
// byte[] byteArray = Base64.decode(jsonObj.getString(TAG_IMG), Base64.DEFAULT) ;
//Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
//String model_img = c.getString(TAG_IMG);
//Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_CARVIN, car_vin);
matchGetCars.put(TAG_IMG, ); //idk
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
So any suggestions of how to decode a JSON jpeg image would be greatly appreciated. Thank you.
}
Update:
public Uri getImageUri(Context inContext, Bitmap inImage){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "CarMainImage", null);
return Uri.parse(path);
}
public void saveBmpToFile(File filename, Bitmap bmp){
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//------------------------
public boolean renameFileExtension(String source, String newExtension)
{
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals(""))
{
target = source + "." + newExtension;
}
else
{
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
//---------------------------------------------------
public String getFileExtension(String f)
{
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1)
{
ext = f.substring(i + 1);
}
return ext;
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, Object>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String car_vin = c.getString(TAG_CARVIN);
Log.d("car_vin", car_vin);
String model_img=c.getString(TAG_IMG);
// byte[] byteArray = Base64.decode(jsonObj.getString(TAG_IMG), Base64.DEFAULT) ;
//Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
// String model_img = c.getString(TAG_IMG);
//Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_CARVIN, car_vin);
matchGetCars.put(TAG_IMG, model_img);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
Logcat:
V/List parsedīš• [{CarMainImage=/images/image.php?w=200&i
Unable to decode stream: java.io.FileNotFoundException: /images/image.php?w=200....
unable to resolveUri failed on bad bitmap uri: /images/image.php?w=200....
I do not understand why the parsed list is correctly logged and then those to error pop up. However, the JSON jpeg in the URL is not fully formatted like the jpeg in the log cat because the jpeg in JSON looks like: /images/image.php?w=200... and the jpeg in logcat looks like: /images/image.php?200.. So the difference is the ..can anyone elaborate if that could why the error messages are shown and/or offer suggestions to fix the errors?
I am very willing to research and go back and forth to understand anything that you suggest. Thanks.
without thinking I will post you some conversion code:
**this is a place holder.**
required understanding:
Bitmap
Uri Provides an object representation of a "uniform resource identifier"
URL (Universal resourse loacator) reference (an address) to a resource on the Internet.
file extensions. *.png *.jpg
this will be up-dated when my brain is not without sleep ;O)
more to come as I think , my brain hurts:
//------------------------
public Uri getImageUri(Context inContext, Bitmap inImage)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public void saveBmpToFile(File filename, Bitmap bmp)
{
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//------------------------
public static boolean renameFileExtension(String source, String newExtension)
{
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals(""))
{
target = source + "." + newExtension;
}
else
{
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
//---------------------------------------------------
public static String getFileExtension(String f)
{
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1)
{
ext = f.substring(i + 1);
}
return ext;
}
//-----------------------
Any of the BitmapFactory methods suit you? There's a couple that can take a byte array and give you a Bitmap. Then you can put your Bitmap into an ImageView fairly easily.
I would suggest to use Picasso
As you just need to provide your image url and your imageView inside getView() function of your adapter. All work starting from download image from url to bitmap conversion and set to image view will be handle by Picasso.
For example : Picasso.with(context).load(url).into(view/*Your image view*/);

Image does not loaded and throwingjava.net.MalformedURLException

i am parsing a json string from which i get the url of image. then i pass that url to a method to get the image and display it in an imageview but the image does not loaded and throws an exception of java.net.MalformedURLException. when i try to pass the image url directly to the method then it gets loaded. so i dont know where is the error. Any help will be appreciated. thanks in advance. my code is below
public class CompanyDetailActivity extends Activity {
ImageView coverimage;
ImageView profileimage;
TextView fullname;
TextView tagline;
TextView industry;
TextView teamsize;
TextView about;
TextView year;
TextView location;
String Coverimage;
String Profimage;
String Fullname;
String Tagline;
String Industry;
String Teamsize;
String About;
String Year;
String Location;
// Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.companydetails);
coverimage = (ImageView) findViewById(R.id.CoverImage);
profileimage = (ImageView) findViewById(R.id.ProfileImage);
fullname = (TextView) findViewById(R.id.FullName);
tagline = (TextView) findViewById(R.id.TagLine);
industry = (TextView) findViewById(R.id.IndustryName);
teamsize = (TextView) findViewById(R.id.TeamSize);
about = (TextView) findViewById(R.id.CompanyAbout);
year = (TextView) findViewById(R.id.FoundYear);
location = (TextView) findViewById(R.id.Location);
new DetailsAsynTask()
.execute("http://www.mygmn.com/joblink/wp-admin/admin-ajax.php?action=joblink_searchcompanies&company_id=1180");
GetXMLTask task = new GetXMLTask();
task.execute(Coverimage);
}
public class DetailsAsynTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(arg0[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
// to get response
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj = new JSONObject(data);
JSONObject MainObject = jObj.getJSONObject("data");
CompanyDetailsModel company = new CompanyDetailsModel();
Coverimage = company.setCoverImage(MainObject
.getString("cove_img"));
Profimage = company.setCompanyProfPicture(MainObject
.getString("company_profile_picture"));
Fullname = company.setCompanyFullName(MainObject
.getString("company_full_name"));
Tagline = company.setComapnyTagLine(MainObject
.getString("company_tagline"));
Industry = company.setCompanyInustry(MainObject
.getString("company_industry"));
Teamsize = company.setCompanyTeamSize(MainObject
.getString("company_teamsize"));
About = company.setCompanyAbout(MainObject
.getString("company_about"));
Year = company.setCompanyFoundYear(MainObject
.getString("company_foundyear"));
Location = company.setCompanyLocation(MainObject
.getString("company location"));
return true;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result == false) {
} else {
fullname.setText(Fullname);
tagline.setText(Tagline);
industry.setText(Industry);
teamsize.setText(Teamsize);
about.setText(About);
year.setText(Year);
location.setText(Location);
}
}
}
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) {
coverimage.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;
}
}
}
java.net.MalformedURLException can come due to security reason .you have to add http:// or https:// with your url images.
You are running two asynctasks inside onCreate() method .As these are asynchronous your GetXMLTask was executed with String CoverImage as null .
So , moving this code :
GetXMLTask task = new GetXMLTask();
task.execute(Coverimage);
to the onPostExecute() Method of your Details asynctask will solve the problem .
ok, use this code
public class ImageLoading {
public enum BitmapManager {
INSTANCE;
private final Map<String, SoftReference<Bitmap>> cache;
private final ExecutorService pool;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
private Bitmap placeholder;
BitmapManager() {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5);
}
public void setPlaceholder(Bitmap bmp) {
placeholder = bmp;
}
public Bitmap getBitmapFromCache(String url) {
if (cache.containsKey(url)) {
return cache.get(url).get();
}
return null;
}
public void queueJob(final String url, final ImageView imageView,
final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
} else {
imageView.setImageBitmap(placeholder);
Log.d(null, "fail " + url);
}
}
}
};
pool.submit(new Runnable() {
#Override
public void run() {
final Bitmap bmp = downloadBitmap(url, width, height);
Message message = Message.obtain();
message.obj = bmp;
Log.d(null, "Item downloaded: " + url);
handler.sendMessage(message);
}
});
}
public void loadBitmap(final String url, final ImageView imageView,
final int width, final int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
// check in UI thread, so no concurrency issues
if (bitmap != null) {
Log.d(null, "Item loaded from cache: " + url);
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageBitmap(placeholder);
queueJob(url, imageView, width, height);
}
}
private Bitmap downloadBitmap(String url, int width, int height) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
url).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
cache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Directly use this code,and where you are using downloading code ,use this code
ImageLoading.BitmapManager.INSTANCE.loadBitmap("http://"+image, holder.img, 150, 180);
Your URL is okay from your server response. Instead of loading the image manually try Picasso Library
with this library, you will just need to do-
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

android.os.NetworkOnMainThreadException in AsyncTask's doInBackground

Why do I get in an AsyncTask which should a android.os.NetworkOnMainThreadException? I thought that an AsyncTask is the solution to that problem. The exxeption is on line 7.
private class ImageDownloadTask extends AsyncTask<String, Integer, byte[]> {
#Override
protected byte[] doInBackground(String... params) {
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
} catch (IOException ex) {
return new byte[0];
}
}
}
I want to use it for downloading a picture.
public byte[] getProfilePicture(Context context, String id) {
String url = context.getString(R.string.facebook_picture_url_large, id);
ImageDownloadTask task = new ImageDownloadTask();
return task.doInBackground(url);
}
By calling doInBackground() directly, you are not actually using the AsyncTask functionality. Instead, you should call execute() and then use the results by overriding the AsyncTask's onPostExecute() method as explained in the Usage section of that same page.
Best way to download an image and attach it to a ImageView is passing the ImageView as the parameter in your async task and set the URL as a tag of the image view then after downloading the task in the OnPostExecute() set the image to the ImageView look at this example :
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}
And the Usage will be like this
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...someImageUrl ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The image will be attached automatically when done, for more memory optimization you could use WeakReference.
Good Luck.

Downloading many pictures from a server in android

I don't know how to get several images from a URL.
Those images come in as Bitmap; I need to convert them to drawable, but I don't know how.
Drawable icon = getResources().getDrawable(R.drawable.icon);
Am I doing it correctly calling the url(images), or is there a better way to do that?
This is the asynctask where I get the images
private class BajarImagenTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return BajarImagen(urls[0]);
}
protected void onPostExecute(Bitmap result){
Drawable icon = getResources().getDrawable(R.drawable.icon);
point.setImage(d);
}
}
This the connection:
private Bitmap BajarImagen (String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in=OpenHttpConnection(URL);
bitmap=BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1) {
}
return bitmap;
}
Here is the method with a "FOR" inside to get several URLs and calling many times the asynctask
public void datosDesdeElXML(String[][] datos) {
for(int i = 0; i < moteles.length;i++){
String motel[] = moteles[i];
double lat = Double.valueOf(motel[0].trim());
double lng = Double.valueOf(motel[1].trim());
String name = motel[2].trim();
String address = motel[3].trim();
**String urldefotoglobo = motel[4].trim();**
// here i get url from server in a xml format
String aidis = motel[5].trim();
**new BajarImagenTask().execute(urldefotoglobo);**
// Here i call the asynctask
}
}

Categories

Resources