Image does not loaded and throwingjava.net.MalformedURLException - android

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

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'

Parsing the same tags name for child nodes using DOM Parser Android

I'm currently building an Application which reads an xml file from the following website: http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries and then displays it in a listview with an image and in a single list view. The Problem i'm facing is that once parsed using the following code :
NodeList nodeList = document.getElementsByTagName("viewentry");
it only return the first child element from the xml file. The following is a partial copy of the xml file to get an idea:
<viewentries timestamp="20141204T225826,77Z" toplevelentries="486">
<viewentry position="1" unid="76D2D8314E365A2A85257DA4004B11B7" noteid="56C06" siblings="486">
<entrydata columnnumber="0" name="EventName">
<text>Learn To Skate Lessons</text>
</entrydata>
<entrydata columnnumber="1" name="Area">
<textlist>
<text>Central East</text>
<text>Southeast</text>
</textlist>
</entrydata>
<entrydata columnnumber="2" name="CategoryList">
<textlist>
<text>Family/Children</text>
<text>Sports</text>
</textlist>
</entrydata>
<entrydata columnnumber="3" name="PresentedByOrgName">
<text/>
</entrydata>
<entrydata columnnumber="4" name="Image">
<text>
http://wx.toronto.ca/festevents.nsf/all/76D2D8314E365A2A85257DA4004B11B7/$File/learntoskate.jpg
</text>
</entrydata>
</viewentry>
The following is my Android Code...I have tested my singleListview and my imageloader than they both work.
MainActivity
public class TorontourismActivity extends Activity{
ListView listView;
ListViewAdapter adapter;
ProgressDialog progressDialog;
ArrayList<HashMap<String,String>> arrayList;
static String Event = "text";
static String Area = "text";
static String Category = "textlist";
static String Presented = "entrydata";
static String Image = "entrydata columnnumber=4 name=Image";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main); //View from the layout file in res folder
new DownloadXMLFile().execute();
}
private class DownloadXMLFile extends AsyncTask<Void,Void,Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(TorontourismActivity.this);
progressDialog.setTitle("Torontourism the know it all for Toronto Events");
progressDialog.setMessage("I'm loading....Give me a minute.");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
arrayList = new ArrayList<HashMap<String, String>>();
TorontourismParser parser = new TorontourismParser();
String xml = parser.getXMLfromURL("http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries");
Document document = parser.getElements(xml);
try
{
NodeList nodeList = document.getElementsByTagName("viewentry");
for(int i =0; i < nodeList.getLength(); i++)
{
Element element = (Element) nodeList.item(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(Event, parser.getValue(element, Event));
map.put(Area, parser.getValue(element, Area));
// map.put(Category, parser.getValue(element, Category));
map.put(Image, parser.getValue(element, Image));
/*map.put(ShowDate, parser.getValue(element, ShowDate));
map.put(BeginTime, parser.getValue(element, BeginTime));
map.put(EndShowDate, parser.getValue(element, EndShowDate));*/
System.out.println(Event);
arrayList.add(map);
}
} catch (Exception e)
{
Log.i("Error in Torontourism Activity", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arguments)
{
listView = (ListView) findViewById(R.id.listView);
adapter = new ListViewAdapter(TorontourismActivity.this, arrayList);
listView.setAdapter(adapter);
progressDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_torontourism, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DOM Parser
public class TorontourismParser {
static final String FesEventURL = "http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries";
//constructor
public TorontourismParser()
{
}
//open a HTTP Connection
public String getXMLfromURL(String urlString)
{
String xmlfile = null;
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlString);
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xmlfile = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xmlfile;
}
public Document getElements(String xml)
{
Document document = null;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource.setCharacterStream(new StringReader(xml));
document = documentBuilder.parse(inputSource);
} catch (Exception e) {
Log.e("Error in Parser file", e.getMessage());
e.printStackTrace();
}
return document;
}
public final String getElements(Node node)
{
Node element;
StringBuilder value = new StringBuilder();
if(node != null)
{
if(node.hasChildNodes())
{
for(element = node.getFirstChild(); element != null;
element = element.getNextSibling())
{
if (element.getNodeType() == Node.TEXT_NODE)
{
value.append(element.getNodeValue());
}
}
}
}
return value.toString();
}
public String getValue(Element element, String string) {
NodeList nodeList = element.getElementsByTagName(string);
return this.getElements(nodeList.item(0));
}
}
ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater layoutInflater;
ArrayList<HashMap<String,String>> xmldata;
ImageLoader imageLoader;
HashMap<String,String> hashMap = new HashMap<String, String>();
public ListViewAdapter(Context context,ArrayList<HashMap<String,String>> arrayList)
{
this.context = context;
xmldata = arrayList;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return xmldata.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) {
TextView Event;
TextView Area;
TextView Category;
TextView Presented;
ImageView Image;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.listview_item, parent, false);
hashMap = xmldata.get(position);
Event = (TextView) view.findViewById(R.id.Event);
Area = (TextView) view.findViewById(R.id.Area);
//Category = (TextView) view.findViewById(R.id.Category);
//Presented = (TextView) view.findViewById(R.id.Presented);
Image = (ImageView) view.findViewById(R.id.Image);
Event.setText(hashMap.get(TorontourismActivity.Event));
Area.setText(hashMap.get(TorontourismActivity.Area));
//Category.setText(hashMap.get(TorontourismActivity.Category));
// Presented.setText(hashMap.get(TorontourismActivity.Presented));
imageLoader.DisplayImage(hashMap.get(TorontourismActivity.Image),Image);
Log.i("Event:", hashMap.get(TorontourismActivity.Event));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
hashMap = xmldata.get(position);
Intent intent = new Intent(context,SingleItemView.class);
intent.putExtra("Event", hashMap.get(TorontourismActivity.Event));
intent.putExtra("Area", hashMap.get(TorontourismActivity.Area));
// intent.putExtra("Category", hashMap.get(TorontourismActivity.Category));
//intent.putExtra("Presented", hashMap.get(TorontourismActivity.Presented));
intent.putExtra("Image", hashMap.get(TorontourismActivity.Event));
context.startActivity(intent);
}
});
return view;
}
}
Single Item viewer
public class SingleItemView extends Activity {
String Event;
String Area;
String Presented;
String Category;
String Image;
ImageLoader imageLoader = new ImageLoader(this);
#Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.singleitemview);
Intent intent = getIntent();
Event = intent.getStringExtra("Event");
Area = intent.getStringExtra("Area");
//Presented = intent.getStringExtra("Presented");
// Category = intent.getStringExtra("Category");
Image = intent.getStringExtra("Image");
TextView textView = (TextView) findViewById(R.id.Event);
//TextView textView1 = (TextView) findViewById(R.id.Area);
//TextView textView2 = (TextView) findViewById(R.id.Presented);
//TextView textView3 = (TextView) findViewById(R.id.Category);
ImageView imageView = (ImageView) findViewById(R.id.Image);
textView.setText(Event);
//textView1.setText(Area);
//textView2.setText(Presented);
//textView3.setText(Category);
imageLoader.DisplayImage(Image, imageView);
}
}
Image Loader
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViewStringMap
= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int NoImage_Id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViewStringMap.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageView);
//imageView.setImageDrawable(getResources().getDrawable());
// imageView.setImageResource(R.drawable.temp_img);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad photoToLoad = new PhotoToLoad(url,imageView);
executorService.submit(new PhotoLoader(photoToLoad));
}
private Bitmap getBitmap(String url) {
File file = fileCache.getFile(url);
Bitmap bitmap = decodeFile(file);
if (bitmap != null)
return bitmap;
try {
Bitmap bitmap1 = null;
URL imageurl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) imageurl.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(file);
Utils.CopyStream(inputStream, outputStream);
outputStream.close();
connection.disconnect();
bitmap = decodeFile(file);
return bitmap;
} catch (Throwable ex) {
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
private Bitmap decodeFile(File file) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
FileInputStream fileInputStream = new FileInputStream(file);
BitmapFactory.decodeStream(fileInputStream, null, options);
fileInputStream.close();
final int Size = 1000;
int width_temp = options.outWidth, height_temp = options.outHeight;
int scale = 1;
while (true) {
if (width_temp / 2 < Size || height_temp / 2 < Size)
break;
width_temp /= 2;
height_temp /= 2;
scale *= 2;
}
BitmapFactory.Options options1 = new BitmapFactory.Options();
options1.inSampleSize = scale;
FileInputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options1);
inputStream.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String uri, ImageView ImView)
{
url = uri;
imageView = ImView;
}
}
class PhotoLoader implements Runnable
{
PhotoToLoad photoToLoad;
PhotoLoader(PhotoToLoad photoToLoad){
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try{
if(ImageViewReused(photoToLoad))
return;
Bitmap bitmap = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bitmap);
if(ImageViewReused(photoToLoad))
return;
BitmapDisplayer bitmapDisplayer = new BitmapDisplayer(bitmap,photoToLoad);
handler.post(bitmapDisplayer);
} catch (Throwable throwable){
throwable.printStackTrace();
}
}
}
boolean ImageViewReused(PhotoToLoad photoToLoad)
{
String string = imageViewStringMap.get(photoToLoad.imageView);
if(string == null || !string.equals(photoToLoad.url))
return true;
return false;
}
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap bitmap1, PhotoToLoad photoToLoad1)
{
bitmap = bitmap1;
photoToLoad = photoToLoad1;
}
public void run() {
if(ImageViewReused(photoToLoad))
return;
if(bitmap != null){
photoToLoad.imageView.setImageBitmap(bitmap);
}else{
//photoToLoad.imageView.setImageResource(NoImage_Id);
}
}
}
public void clearCache()
{
memoryCache.clear();
fileCache.clear();
}
}
Any help is appreciated. From what i believe the problem lies inside the parser file. Other than that please help me.
Thank you!

JSON POST request for download image from server in android

I need to download image and set it in to imageview . for parsing i use JSON POST request and for this i use base64 . I got base64 type data for the image tag in to log but the problem is that how t separate the value of that image and convert it in to string and then display it in to list view ??is there any alternative way without using base64 to display image then please suggest us.
For parsing of data i use JSON parser with HttpPost .
Now how to get the value of image from response JSON format that i display above that the confusion ??
Thanks in advance ..
You can do like this.
Create folder in server. put images in that folder. get the URL of the image and insert in to db.
then get the JSON value of that url
add this method and pass that url to this method.
Bitmap bitmap;
void loadImage(String image_location) {
URL imageURL = null;
try {
imageURL = new URL(image_location);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to
// bitmap
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Try below code:
JSONObject res = jsonObj.getJSONObject("root");
JSONObject data = jsonObj.getJSONObject("data");
JSONArray imgs= jsonObj.getJSONArray ("images");
for(int i=0;i<imgs.length();i++){
JSONObject Ldetails = Ldtls.getJSONObject(i);
String img= Ldetails.getString("image");
byte[] decodedString = Base64.decode(img,Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imagevw.setImageBitmap(bitmap);
}
where imagevw is your ImageView.
Use a Gson Parser and then parse the base64 image string to a byte array and apply on the image.
Your model classes will be as follows:
public class JsonWrapper
{
private Root root ;
public Root getroot()
{
return this.root;
}
public void setroot(Root root)
{
this.root = root;
}
}
public class Root
{
private Response response ;
public Response getresponse()
{
return this.response;
}
public void setresponse(Response response)
{
this.response = response;
}
}
public class Response
{
private Message message ;
public Message getmessage()
{
return this.message;
}
public void setmessage(Message message)
{
this.message = message;
}
private Data data ;
public Data getdata()
{
return this.data;
}
public void setdata(Data data)
{
this.data = data;
}
}
public class Message
{
private String type ;
public String gettype()
{
return this.type;
}
public void settype(String type)
{
this.type = type;
}
private String message ;
public String getmessage()
{
return this.message;
}
public void setmessage(String message)
{
this.message = message;
}
}
import java.util.ArrayList;
public class Data
{
private ArrayList<Image> images ;
public ArrayList<Image> getimages()
{
return this.images;
}
public void setimages(ArrayList<Image> images)
{
this.images = images;
}
private String last_synchronized_date ;
public String getlast_synchronized_date()
{
return this.last_synchronized_date;
}
public void setlast_synchronized_date(String last_synchronized_date)
{
this.last_synchronized_date = last_synchronized_date;
}
}
public class Image
{
private String web_id ;
public String getweb_id()
{
return this.web_id;
}
public void setweb_id(String web_id)
{
this.web_id = web_id;
}
private String blob_image ;
public String getblob_image()
{
return this.blob_image;
}
public void setblob_image(String blob_image)
{
this.blob_image = blob_image;
}
}
Once you have the json parse using Gson as follows:
JsonWrapper jsonWrapper = new JsonWrapper();
Gson gsonParser = new Gson();
jsonWrapper = gsonParser.fromJson(data, jsonWrapper.getClass());
Next you can iterate through all the images
ArrayList<Image> images = jsoinWrapper.getRoot().getResponse().getData().getImages();
for(Image image : images)
{
byte[] decodedString = Base64.decode(image.getblob_image(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
if (decodedString != null) {
imageViewtype.setImageBitmap(decodedByte);
}
}
public class SingleContactActivity extends Activity implements OnClickListener {
private static final String TAG_ImageList = "CatList";
private static final String TAG_ImageID = "ID";
private static final String TAG_ImageUrl = "Name";
private static String url_MultiImage;
TextView uid, pid;
JSONArray contacts = null;
private ProgressDialog pDialog;
String details;
// String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
String imagepath = "";
String imagepath2;
Bitmap bitmap;
ImageView image;
SessionManager session;
TextView myprofileId;
TextView pending;
TextView Categories, visibleTo;
int count = 0;
ImageButton btn;
// -----------------------
ArrayList<HashMap<String, String>> ImageList;
JSONArray JsonArray = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
url_MultiImage = "http://test2.sonasys.net/Android/GetpostImg?UserID=1&PostId=80";
new MultiImagePath().execute();
ImageList = new ArrayList<HashMap<String, String>>();
}
private class MultiImagePath extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url_MultiImage,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JsonArray = jsonObj.getJSONArray(TAG_ImageList);
if (JsonArray.length() != 0) {
for (int i = 0; i < JsonArray.length(); i++) {
JSONObject c = JsonArray.getJSONObject(i);
String Img_ID = c.getString(TAG_ImageID);
String Img_Url = c.getString(TAG_ImageUrl);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ImageID, Img_ID);
contact.put(TAG_ImageUrl, Img_Url);
// adding contact to contact list
ImageList.add(contact);
}
}
Log.e("JsonLength", "length is ZERO");
} 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);
AutoGenImgBtn();
}
}
#SuppressWarnings("deprecation")
public void AutoGenImgBtn() {
int count = ImageList.size();
LinearLayout llimage = (LinearLayout) findViewById(R.id.llimage);
ImageButton[] btn = new ImageButton[count];
for (int i = 0; i < count; i++) {
btn[i] = new ImageButton(this);
btn[i].setId(Integer.parseInt(ImageList.get(i).get(TAG_ImageID)));
btn[i].setOnClickListener(this);
btn[i].setTag("" + ImageList.get(i).get(TAG_ImageUrl));
btn[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
btn[i].setImageDrawable(getResources().getDrawable(drawable.di1));
btn[i].setAdjustViewBounds(true);
// btn[i].setTextColor(getResources().getColor(color.white));
llimage.addView(btn[i]);
}
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btn = (ImageButton) v;
String s = btn.getTag().toString();
new ImageDownloader().execute(s);
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return downloadBitmap(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
pDialog = new ProgressDialog(SingleContactActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.setTitle("In progress...");
// pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setIcon(android.R.drawable.stat_sys_download);
pDialog.setMax(100);
// pDialog.setTitle("Post Details");
pDialog.show();
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
if (bitmap != null) {
btn.setImageBitmap(bitmap);
}
if (pDialog.isShowing())
pDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
// forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
// check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that
// android understands
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for
// IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while"
+ " retrieving bitmap from " + url + e.toString());
}
return null;
}
}
# Add Service Handler Class#
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
*
* */
public String makeServiceCall(String url, int method,List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending 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;
}

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 using async http connection to get image bitmap

I am trying to use async requests to fetch the images from urls, to prevent the url from hanging. This is the piece of code i am using for this
private void setImg(final ImageView im, String url){
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler(){
public void onSuccess(String response){
try{
byte[] imageAsBytes = response.getBytes();
im.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
im.refreshDrawableState();
} catch(Throwable e){
e.printStackTrace();
}
}
});
}
This is always showing this warning in logcat
12-29 01:55:33.043: D/skia(14414): --- SkImageDecoder::Factory returned null
I cannot find a proper reason for this. Any help?
Now that a binary response handler has been added to AsyncHttp you can simply use androids BitmapFactory.decodeByeArray function:
AsyncHttpClient client = new AsyncHttpClient();
client.get(image_url, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(byte[] fileData) {
Bitmap image = BitmapFactory.decodeByteArray(fileData, 0, fileData.length);
//Do whatever you want with the image variable
}
});
I've been using lately the following library: UrlImageViewHelper. It uses an AsyncTask to download the image. Your code would be something like this:
private void setImg(final ImageView im, String url){
UrlImageViewHelper.setUrlDrawable(im, url) ;
}
Very simple now, am I right?
If anyone is still working on this, here's how I am doing it
public static void setImg(final ImageView im, final String url){
AsyncTask<Void, Void, Bitmap> t = new AsyncTask<Void, Void, Bitmap>(){
protected Bitmap doInBackground(Void... p) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.setUseCaches(true);
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
protected void onPostExecute(Bitmap bm){
Bitmap output = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bm.getWidth(), bm.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 5;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bm, rect, rect, paint);
im.setImageBitmap(output);
}
};
t.execute();
}
[UPDATE]
Image (and any binary data) response handling has been added to loopj's android-async-http library. Use the BinaryHttpResponseHandler
[old post]
loopj's AsyncHttpClient does not yet support handling of byte[] responses. There's a fork that does, but it's a mess. So the answer is one of these:
A1) You don't.
A2) You use the fork provided via link via this link: https://github.com/loopj/android-async-http/issues/8
A3) You fork AsyncHttpClient, add byte[] handling (without tearing out String response handling, jesus!), and commit it back to the project. By doing this you will also receive open-source karma credits.
Android using async http connection to get image and text and show in a listView
public class MainActivity extends Activity {
ListView list;
public String IPadd = "http://api.gifts.com/v2/search/product.json?category=Nur&api_key=fd2ut5evb9jgzerjkeph54pz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView) findViewById(R.id.listView1);
new AsyTask().execute(IPadd);
}
private class AsyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url[0]);
// HttpPost httpPost=new HttpPost(url[0]);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet);
text = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result);
JSONArray jarray = jObject.getJSONArray("products");
for (int i = 0; i < jarray.length(); i++) {
ProductInfo p=new ProductInfo();
JSONObject jObj = jarray.getJSONObject(i);
p.setTitle(jObj.getString("title"));
p.setId(jObj.getString("price"));
p.setImage(jObj.getString("largeProductImageUrl"));
ProductInfo.arrayList.add(p);
}
ArrAdapter adapter=new ArrAdapter(getApplicationContext(),ProductInfo.arrayList);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public class ArrAdapter extends BaseAdapter{
TextView id,title;
ImageView img;
Context context;
static ArrayList<ProductInfo> listitem=new ArrayList<ProductInfo>();
public ArrAdapter(Context applicationContext,ArrayList<ProductInfo> arrayList) {
this.context=applicationContext;
listitem=arrayList;
}
#Override
public int getCount() {
return listitem.size();
}
#Override
public Object getItem(int position) {
return listitem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ProductInfo p=listitem.get(position);
if(convertView==null)
{
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.custom, null);
}
id=(TextView) convertView.findViewById(R.id.textView1);
id.setText(p.getId());
title=(TextView) convertView.findViewById(R.id.textView2);
title.setText(p.getTitle());
img=(ImageView) convertView.findViewById(R.id.imageView1);
ImageLoader imageloader=new ImageLoader(img);
imageloader.execute(p.getImage());
return convertView;
}
}
public class ProductInfo {
String ID,title,image;
static ArrayList<ProductInfo> arrayList=new ArrayList<ProductInfo>();
public void setId(String id)
{
this.ID=id;
}
public String getId()
{
return ID;
}
public void setTitle(String tit)
{
this.title=tit;
}
public String getTitle()
{
return title;
}
public void setImage(String img)
{
this.image=img;
}
public String getImage()
{
return image;
}
}
class ImageLoader extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public ImageLoader(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
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) {
}
return mIcon11;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
bmImage.setImageBitmap(result);
}
}

Categories

Resources