Android studio Load Image url into listview - android

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'

Related

Android Get Image.png from JSON

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.

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

How to display image in ImageView from Bitmap... ImageView variable returns null

I have a problem with displaying the image from bitmap.
I'm getting the base64 encoded string from JsonObject and decoded to get byte array and bitmap after.
I was unlucky with this so I'm trying now with the same image from drawable.
Now the problem is i'm getting the null pointer exceptions when setting image bitmap in imageView
and have no idea why...
Have read this : ImageView variable returning null even after defined; Android
The code for whole class is: `package com.statsports.subjectiveandroid;
public class PlayersListActivity extends Activity {
// URL to make request
private static String URL = "http://000.000.00.0/index.php";
private static int userID;
ArrayList<HashMap<String, Object>> playersList;
ListView playerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list_view);
Bundle extras = getIntent().getExtras();
userID = extras.getInt("id");
initLayout();
}
private void initLayout() {
playerView = (ListView) findViewById(R.id.list);
playersList = new ArrayList<HashMap<String, Object>>();
playerView.setAdapter(new SimpleAdapter(PlayersListActivity.this,
playersList, R.layout.activity_players_list, null, null));
//playerView.setDividerHeight(0);
}
#Override
protected void onResume() {
if (!ConnectivityStatus.isNetworkAvailable(getApplicationContext())) {
Toast.makeText(PlayersListActivity.this, R.string.network_failed,
Toast.LENGTH_SHORT).show();
} else {
playerView.setAdapter(null);
new PlayersLoadTask().execute();
}
super.onResume();
}
ProgressDialog pDialog;
class PlayersLoadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PlayersListActivity.this);
pDialog.setMessage("Reading data");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
playersList.clear();
}
#Override
protected String doInBackground(String... arg0) {
try {
ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("request", "getPlayers"));
parameters.add(new BasicNameValuePair("clubid", Integer
.toString(userID)));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PlayersListActivity.URL);
httpPost.setEntity(new UrlEncodedFormEntity(parameters,
("ISO-8859-1")));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// if this is null the web service returned an empty page
if (httpEntity == null) // response is empty so exit out
return null;
String jsonString = EntityUtils.toString(httpEntity);
// again some simple validation around the returned string
if (jsonString != null && jsonString.length() != 0) // checking
// string
// returned
// from
// service
// to grab
// id
{
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
String base64 = jsonObject.getString("image");
map.put("id", id);
map.put("name", name);
if (name == null || name.trim().length() == 0) {
name = "Player unknown";
} else {
map.put("image", (R.drawable.baboon));
}
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.walcott);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(bmp1);
//ByteArrayOutputStream stream = new ByteArrayOutputStream();
//byte[] decodedString = Base64.decode(
// base64.getBytes("UTF-8"), Base64.NO_PADDING);
/*
* InputStream is = new
* ByteArrayInputStream(decodedString); Bitmap bitmap =
* BitmapFactory.decodeStream(is);
* bitmap.compress(Bitmap.CompressFormat.PNG, 100,
* stream);
*
* if(bitmap != null){ //Drawable drawableImg = new
* BitmapDrawable(getResources(), bitmap); ImageView
* imgView = (ImageView) findViewById(R.id.image);
* imgView.setImageBitmap(bitmap); map.put("image",
* bitmap); }
*/
//String images = new String(decodedString);
//Bitmap decodedByte = BitmapFactory.decodeByteArray(
// decodedString, 0, decodedString.length);
//decodedByte.compress(Bitmap.CompressFormat.PNG, 100,
// stream);
//Log.d("DECODEDBYTE IS: ", decodedByte.toString());
//LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View view = inflater.inflate(R.layout.activity_players_list, null);
//setContentView(view);
//ImageView imgView = (ImageView) findViewById(R.id.image);
//imgView.setImageBitmap(decodedByte);
playersList.add(map);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e("ERROR SOMEWHERE!!!! ", e.toString());
}
return null;
}
protected void onPostExecute(String file_url) {
if (playersList.size() == 0) {
Toast.makeText(PlayersListActivity.this,
"No players in a list", Toast.LENGTH_SHORT).show();
} else {
playerView.setAdapter(new PlayerListAdapter(
PlayersListActivity.this, playersList,
R.layout.activity_players_list, new String[] { "id",
"image", "name" }, new int[] {
R.id.player_list_id, R.id.image, R.id.name, }));
}
pDialog.dismiss();
}
}
}

Parsing an image in android when we receive a relative path from server

I have the JSON:: http://54.218.73.244:7002/
"restaurants": [
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney",
"restaurantIMAGE": "http://54.218.73.244:7002/CopperChimney.png",
"restaurantDISTANCE": 5,
"restaurantTYPE": "Indian",
"restaurantRATING": 3,
"restaurantPrice": 20,
"restaurantTime": "8pm to 11pm"
},
{
"restaurantID": 2,
"restaurantNAME": "Aroy",
"restaurantIMAGE": "http://54.218.73.244:7002/Aroy.png",
"restaurantDISTANCE": 10,
"restaurantTYPE": "Thai",
"restaurantRATING": 4,
"restaurantPrice": 8,
"restaurantTime": "10pm to 12pm"
}
I have used image loader to load the image in JSON and the classes i have used are listed below
FileCache.java
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"JsonParseTutorialCache");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
String filename = String.valueOf(url.hashCode());
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}
ImageLoader.java
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.NAME));
country.setText(resultp.get(MainActivity.TYPE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("name", resultp.get(MainActivity.NAME));
// Pass all data country
intent.putExtra("type", resultp.get(MainActivity.TYPE));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
MemoryCache.java
public class MemoryCache {
private static final String TAG = "MemoryCache";
// Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
// Current allocated size
private long size = 0;
// Max memory in bytes
private long limit = 1000000;
public MemoryCache() {
// Use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
// Least recently accessed item will be the first one iterated
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
try {
cache.clear();
size = 0;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
SingleItemView.java
public class SingleItemView extends Activity {
// Declare Variables
String name;
String type;
String flag;
String position;
ImageLoader imageLoader = new ImageLoader(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.singleitemview);
Intent i = getIntent();
// Get the result of rank
name = i.getStringExtra("name");
// Get the result of country
type = i.getStringExtra("type");
// Get the result of flag
flag = i.getStringExtra("flag");
// Locate the TextViews in singleitemview.xml
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
// Locate the ImageView in singleitemview.xml
ImageView imgflag = (ImageView) findViewById(R.id.flag);
// Set results to the TextViews
txtrank.setText(name);
txtcountry.setText(type);
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(flag, imgflag);
}
}
MainActivity.java
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String FLAG = "flag";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7002/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("restaurantIMAGE"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Now suppose i have a JSON like below
"restaurants": [
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney",
"restaurantIMAGE": "CopperChimney.png",
"restaurantDISTANCE": 5,
"restaurantTYPE": "Indian",
"restaurantRATING": 3,
"restaurantPrice": 20,
"restaurantTime": "8pm to 11pm"
},
{
"restaurantID": 2,
"restaurantNAME": "Aroy",
"restaurantIMAGE": "Aroy.png",
"restaurantDISTANCE": 10,
"restaurantTYPE": "Thai",
"restaurantRATING": 4,
"restaurantPrice": 8,
"restaurantTime": "10pm to 12pm"
}
I need to append the below
http://54.218.73.244:7002/
for restaurantIMAGE on the android client part so when I receive the relative path from server i can use it ..... how to perform this process and make changes in code
Any ideas
Hope I am clear
try this, Instead of this
imageLoader.DisplayImage(flag, imgflag);
Use this one it will help you.
imageLoader.DisplayImage("http://54.218.73.244:7002/"+flag, imgflag);
Loop through the arraylist and append the imagename to the URL. Add URl="http://54.218.73.244:7002" in your constant class( if you have any )So you dont need to edit the code everywhere if the url changes. And you can also use
http://loopj.com/android-smart-image-view/ for automatic image caching

Android: Custom ListView and Threading problem

I'm working on a small project on Android and have a serious problem with implementing some multi-threading into my solution. Below is a class that is an activity inside the tab of the main interface, which displays a custom list with pictures and data downloaded from YouTube API.
The class works fine, but it completely blocks the UI when, first the data, and then the images are being loaded from the Internet. I know I need to implement some threading and I have tried various things, but I'm not quite sure which parts of the code I have to launch as separate threads. There's also a chance there is something fundamentally wrong with my code structure.
Ideally I'd like to have the UI shown to the user immediately after the application is launched with a progress dialog on top of it, while the textual data is being loaded from YouTube. Then the user should get control of the UI, while images are being loaded in another thread in the background.
public class VodsActivity extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
//private Handler mHandler;
private ProgressDialog dialog;
//Generic names of custom ListView elements
private static String[] title;
private Vector<String> detail;
private Vector<String> status;
private Vector<String> imgurl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_list);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
title = getResources().getStringArray(R.array.yt_channels);
detail = new Vector<String>();
status = new Vector<String>();
imgurl = new Vector<String>();
//mHandler = new Handler();
//dialog = ProgressDialog.show(VodsActivity.this, "","Loading. Please wait...", true);
loadData();
displayData();
//dialog.dismiss();
}
private void loadData() {
String[] values = {"error", "error", "http://www.ephotobay.com/thumb/message-error.jpg" };
for (int i = 0; i < title.length; i++) {
values = getData(title[i]);
values[1] = getTodaysUploads(title[i]);
detail.add(i, values[0]);
status.add(i, values[1]);
imgurl.add(i, values[2]);
}
}
/*** This function gets total number of uploads and thumbnail url for the user from a single feed ***/
private String[] getData (String username) {
String[] result = new String[3];
String ytFeedUrl = "http://gdata.youtube.com/feeds/api/users/" + username + "?v=2";
InputStream inStream = null;
try {
inStream = OpenHttpConnection(ytFeedUrl);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(inStream);
Element docEle = dom.getDocumentElement();
inStream.close();
NodeList nl = docEle.getElementsByTagName("entry");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element entry = (Element) nl.item(i);
Element thumbnail = (Element) entry.getElementsByTagName("media:thumbnail").item(0);
String thumbUrl = thumbnail.getAttribute("url");
Element feedLink = (Element) entry.getElementsByTagName("gd:feedLink").item(5);
String uploads = feedLink.getAttribute("countHint");
result[0] = uploads + " videos";
result[1] = ""; //not used here
result[2] = thumbUrl;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
finally {
//
}
return result;
}
/*** This function gets a number of today's uploads of the user ***/
private String getTodaysUploads (String username) {
String result = null;
String ytFeedUrl = "http://gdata.youtube.com/feeds/api/videos?author=" + username + "&time=today&v=2";
InputStream inStream = null;
try {
inStream = OpenHttpConnection(ytFeedUrl);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(inStream);
Element docEle = dom.getDocumentElement();
inStream.close();
NodeList nl = docEle.getElementsByTagName("feed");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element entry = (Element) nl.item(i);
Element title = (Element)entry.getElementsByTagName("openSearch:totalResults").item(0);
result = title.getFirstChild().getNodeValue();
result += " new today";
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
finally {
//
}
return result;
}
private void displayData () {
//Use vector instead of ArrayList for safe threading
data = new Vector<RowData>();
for (int i = 0; i < title.length; i++) { //Loop needs to be changed based on results
try {
rd = new RowData(i, title[i], detail.get(i), status.get(i));
} catch (Exception e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter (this, R.layout.custom_list_item, R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
private InputStream OpenHttpConnection(String strUrl) throws IOException {
InputStream inStream = 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) {
inStream = httpConn.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return inStream;
}
//This is temporary
public void onListItemClick(ListView parent, View v, int position, long id) {
CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
RowData row = adapter.getItem(position);
Builder builder = new AlertDialog.Builder(this);
builder.setTitle(row.mTitle);
builder.setMessage(row.mDetail + " -> " + position );
builder.setPositiveButton("ok", null);
builder.show();
}
//Private class RowData - holds details of CustomAdapter item
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
protected String mStatus;
RowData (int id, String title, String detail, String status) {
mId = id;
mTitle = title;
mDetail = detail;
mStatus = status;
}
#Override
public String toString() {
return mId + " " + mTitle + " " + mDetail + " " + mStatus;
}
}
//Custom Adapter for the custom list, overrides onView() method
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super (context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
TextView status = null;
ImageView image = null;
RowData rowData = getItem(position);
//Reuse existing row views
if(convertView == null) {
convertView = mInflater.inflate(R.layout.custom_list_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.getTitle();
title.setText (rowData.mTitle);
detail = holder.getDetail();
detail.setText(rowData.mDetail);
status = holder.getStatus();
status.setText(rowData.mStatus);
//add if statements here for colors
image = holder.getImage();
/**** This loads the pictures ****/
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
String imageUrl = imgurl.get(rowData.mId);
Bitmap bm = LoadImage(imageUrl, bmOptions);
image.setImageBitmap(bm);
return convertView;
}
//Load image from the URL
private Bitmap LoadImage(String url, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream inStream = null;
try {
inStream = OpenHttpConnection(url);
bitmap = BitmapFactory.decodeStream(inStream, null, options);
inStream.close();
} catch (IOException ioex) {
ioex.printStackTrace();
}
return bitmap;
}
}
/*** Wrapper for row data ***/
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private TextView status = null;
private ImageView image = null;
public ViewHolder (View row) {
mRow = row;
}
public TextView getTitle() {
if (title == null) {
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getDetail() {
if (detail == null) {
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public TextView getStatus() {
if (status == null) {
status = (TextView) mRow.findViewById(R.id.status);
}
return status;
}
public ImageView getImage() {
if (image == null) {
image = (ImageView) mRow.findViewById(R.id.thumbnail);
}
return image;
}
}
}
Thanks a lot for any pointers.
Check out the AsyncTask. This will let you background your long-running processes while showing the UI.
Also, you can find good/official tutorial on Android threading here.
I ended up using standard java Thread to load the data from API in the background and created a separate class for loading images in separate threads as well. In case you're wondering it now looks like this, and seem to work fine.
Loading the data:
public void onCreate(...) {
//...
mHandler = new Handler();
dialog = ProgressDialog.show(VodsActivity.this, "","Loading. Please wait...", true);
getData.start();
}
private Thread getData = new Thread() {
public void run() {
try {
loadData();
mHandler.post(showData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
private Runnable showData = new Runnable() {
public void run() {
try {
displayData();
dialog.dismiss();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
Loading images (in CustomAdapter):
String imageUrl = imgurl.get(rowData.mId);
final ImageView image = holder.getImage();
//Reuse downloaded images or download new in separate thread
image.setTag(imageUrl);
Drawable cachedImage = imageLoader.loadDrawable(imageUrl, new ImageCallback() {
public void imageLoaded(Drawable imageDrawable, String imageUrl) {
ImageView imageViewByTag = (ImageView) image.findViewWithTag(imageUrl);
if (imageViewByTag != null) {
imageViewByTag.setImageDrawable(imageDrawable);
}
}
});
image.setImageDrawable(cachedImage);
ImageLoader class:
public class ImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache;
private static final String TAG = "ImageLoader";
public ImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
//Loads image from the cache if it exists or launches new thread to download it
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
Log.d(TAG, "loadDrawable(" + imageUrl + ")");
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};
new Thread() {
#Override
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
//Downloads image from the url
public static Drawable loadImageFromUrl(String url) {
Log.d(TAG, "loadImageFromUrl(" + url + ")");
InputStream inputStream;
try {
inputStream = new URL(url).openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
return Drawable.createFromStream(inputStream, "src");
}
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}

Categories

Resources