Again hi. I return android parsing with JSON. Now, i can successfully parsing but i dont get a picture. We stored picture as String on database. So, i think must convert String to Image for display in ImageView. I try this function but i can't use:
public Bitmap StringToBitMap(String encodedString) {
byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap; }
And this my activiy class:
newsList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray news= jsonObj.getJSONArray("news");
JSONObject r = news.getJSONObject(0);
String Id = r.getString("Id");
String NewsDetail = r.getString("NewsDetail");
String Picture= r.getString("Picture");
HashMap<String, String> News = new HashMap<>();
News.put("Id", Id);
News.put("NewsDetail", NewsDetail);
News.put("Picture", Picture);
newsList.add(News);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
final ListAdapter adapter = new SimpleAdapter(
NewsDip.this, newsList,
R.layout.news_list, new String[]{"Picture"},
new int[]{R.id.imageView});
lv.setAdapter(adapter);
}
I think I use this function in adapter. But I can't do it. How can I solve this?
you can use Glide library to simply show your byte converted image
add this in Gradle
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
add this in your java file
Glide.with(context)
.load(encodeByte) //your byte array
.asBitmap()
.placeholder(R.drawable.ic_broken)
.into(your imageview);
Related
Here is my code.
The image space remaining empty. Not being loaded.
What is my mistake here?
what kind of code i need again.
give more definition pls.
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog progressDialog;
private ListView listView;
// JSON data url
private static String Jsonurl = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors";
ArrayList<HashMap<String, String>> contactJsonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactJsonList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listview);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HTTPHandler httpHandler = new HTTPHandler();
// request to json data url and getting response
String jsonString = httpHandler.makeServiceCall(Jsonurl);
Log.e(TAG, "Response from url: " + jsonString);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
// Getting JSON Array node
JSONArray contacts = jsonObject.getJSONArray("actors");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("name");
String country = c.getString("country");
String spouse = c.getString("spouse");
String dob = c.getString("dob");
String description = c.getString("description");
String children = c.getString("children");
String image = c.getString("image");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("name", name);
contact.put("country", country);
contact.put("spouse", spouse);
contact.put("dob", dob);
contact.put("description", description);
contact.put("children", children);
contact.put("image", image);
// adding contact to contact list
contactJsonList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Could not get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Could not get json from server.",Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing())
progressDialog.dismiss();
/** * Updating parsed JSON data into ListView * */
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactJsonList, R.layout.row,
new String[]{"name","country", "spouse", "dob", "description", "children", "image"},
new int[]{R.id.name, R.id.country, R.id.spouse, R.id.dob, R.id.description, R.id.children, R.id.imageview});
listView.setAdapter(adapter);
}
}
}
thanks for your help
If you want to load image from URL Use custom adapter and use picasso or Glide library to load image.
or
If you want to use simpleAdapter then check this link Image from URL in ListView using SimpleAdapter
you can user Glide library to load image from url look the below code it can help you in simple way
compile this library
compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
than load image like this
Glide.with(HomeClass.this)
.load(userProfileUrl)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.dontAnimate()
.into(imageview);
Do you want to load list of images from url? then
check out the link below, there is detailed example working with list of images using json with volly library.
Example
I hope this will help you.
I have JSON data that I am viewing from a URL. There are many JSON objects in the JSON array, one of which is a jpeg image.
I would like to send that image to a listview in an Android app.
Right now I have the image JSON object linked to a private static final String TAG in my Java file. However, I realize that I must decode the image or I will receive an error of: Unable to decode stream: java.io.FileNotFoundException and resolveUri failed on bad bitmap uri.
I am in a long and ongoing search to understand how to decode the JSON jpeg image, much of such research taken place by viewing posts on this website so please do not mark as a duplicate question.
public class JSONBuilderActivity extends ListActivity {
private ProgressDialog pDialog;
//URL to get JSON
private static String url = "";
//JSON Node names
private static final String TAG_CARS = "cars"; //root
private static final String TAG_CARID = "CarID";
private static final String TAG_CARVIN = "CarVIN";
private static final String TAG_IMG= "CarMainImage";
JSONArray carid = null; //Initializes JSON array
static String response = null;
//Hashmap for ListView
ArrayList<HashMap<String, Object>>caridList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lv = getListView();
//Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Gets values from selected ListItem
String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
String car_vin = ((TextView) view.findViewById(R.id.car_vin)).getText().toString();
String model_img = ((ImageView) view.findViewById(R.id.model_img)).getTag().toString();
Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
//Sends data to MainActivity
in.putExtra("TAG_CARS", cars);
in.putExtra("TAG_CARID", car_id);
in.putExtra("TAG_CarVin", car_vin);
in.putExtra("TAG_IMG", model_img);
startActivity(in);
}
});
//Calls async task to get json
new GetCars().execute();
}
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//Checks http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
//Adds post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//Appends params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, Object>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String car_vin = c.getString(TAG_CARVIN);
Log.d("car_vin", car_vin);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.model_img, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
// byte[] byteArray = Base64.decode(jsonObj.getString(TAG_IMG), Base64.DEFAULT) ;
//Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
//String model_img = c.getString(TAG_IMG);
//Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_CARVIN, car_vin);
matchGetCars.put(TAG_IMG, ); //idk
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
So any suggestions of how to decode a JSON jpeg image would be greatly appreciated. Thank you.
}
Update:
public Uri getImageUri(Context inContext, Bitmap inImage){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "CarMainImage", null);
return Uri.parse(path);
}
public void saveBmpToFile(File filename, Bitmap bmp){
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//------------------------
public boolean renameFileExtension(String source, String newExtension)
{
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals(""))
{
target = source + "." + newExtension;
}
else
{
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
//---------------------------------------------------
public String getFileExtension(String f)
{
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1)
{
ext = f.substring(i + 1);
}
return ext;
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, Object>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String car_vin = c.getString(TAG_CARVIN);
Log.d("car_vin", car_vin);
String model_img=c.getString(TAG_IMG);
// byte[] byteArray = Base64.decode(jsonObj.getString(TAG_IMG), Base64.DEFAULT) ;
//Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
// String model_img = c.getString(TAG_IMG);
//Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_CARVIN, car_vin);
matchGetCars.put(TAG_IMG, model_img);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
Logcat:
V/List parsedīš [{CarMainImage=/images/image.php?w=200&i
Unable to decode stream: java.io.FileNotFoundException: /images/image.php?w=200....
unable to resolveUri failed on bad bitmap uri: /images/image.php?w=200....
I do not understand why the parsed list is correctly logged and then those to error pop up. However, the JSON jpeg in the URL is not fully formatted like the jpeg in the log cat because the jpeg in JSON looks like: /images/image.php?w=200... and the jpeg in logcat looks like: /images/image.php?200.. So the difference is the ..can anyone elaborate if that could why the error messages are shown and/or offer suggestions to fix the errors?
I am very willing to research and go back and forth to understand anything that you suggest. Thanks.
without thinking I will post you some conversion code:
**this is a place holder.**
required understanding:
Bitmap
Uri Provides an object representation of a "uniform resource identifier"
URL (Universal resourse loacator) reference (an address) to a resource on the Internet.
file extensions. *.png *.jpg
this will be up-dated when my brain is not without sleep ;O)
more to come as I think , my brain hurts:
//------------------------
public Uri getImageUri(Context inContext, Bitmap inImage)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public void saveBmpToFile(File filename, Bitmap bmp)
{
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//------------------------
public static boolean renameFileExtension(String source, String newExtension)
{
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals(""))
{
target = source + "." + newExtension;
}
else
{
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
//---------------------------------------------------
public static String getFileExtension(String f)
{
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1)
{
ext = f.substring(i + 1);
}
return ext;
}
//-----------------------
Any of the BitmapFactory methods suit you? There's a couple that can take a byte array and give you a Bitmap. Then you can put your Bitmap into an ImageView fairly easily.
I would suggest to use Picasso
As you just need to provide your image url and your imageView inside getView() function of your adapter. All work starting from download image from url to bitmap conversion and set to image view will be handle by Picasso.
For example : Picasso.with(context).load(url).into(view/*Your image view*/);
I have an image being sent to me through a JSON string. I want to convert that string into an image in my android app and then display that image in my imageview.I have a problem, I am using Asynctask and this is my code in the doInBackground method:
protected Boolean doInBackground(final String... args){
JsonParser jsonParser = new JsonParser();
JSONArray json = jsonParser.getJSONFromUrl(url);
if(json!=null){
for (int i = 0; i < json.length(); i++){
try{
JSONObject c = json.getJSONObject(i);
String displayImageFromUrl = c.getString(imageUrl);
String clearUrl = displayImageFromUrl.substring(displayImageFromUrl.indexOf(",")+1);
byte[] decodingString = Base64.decode(clearUrl, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(decodingString, 0 , decodingString.length);
String showCreatedDate = c.getString(createdDate);
String showArticleTitle = c.getString(articleTitle);
HashMap<String, String> map = new HashMap<String, String>();
map.put(createdDate, showCreatedDate);
map.put(articleTitle, showArticleTitle);
jsonlist.add(map);
}catch (Exception e){
e.printStackTrace();
}
}
}else{
}
return null;
}
and this is my code in the onPostExecute() method:
protected void onPostExecute(final Boolean success){
if (dialog.isShowing()) {
dialog.dismiss();
}
Log.d("image please",bitmap.toString());
ImageView showImage = (ImageView) findViewById(R.id.imageShow);
showImage.setImageBitmap(bitmap);
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.activity_news,
new String[] {createdDate, articleTitle},
new int[] { R.id.createDate, R.id.articleTitle});
setListAdapter(adapter);
lv = getListView();
}
Unfortunately nothings shows up in my logcat. Can you help me?
What do I miss??
Here is a pseudocode. If you use it in project it should be working.
//my image (android logo)
private String base64 = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAACgUlEQVRIiZ2Wv4vUQBTHP2/ZBFlEFrGS44iniLCggggWh4yVoIX4F9gIFtYiFgqWNgqChfoXHBYWXuWJF05rwe0UMWE5RI7lEJUguSPPYvJjkk32xAcbvjPz8n3v++ZlZqHDYuMRG/9+bPxBt4+/LzLevdj4XS5I54olOK/oCSAUWFY4al/RSJANRY0gX4IwfdvF0Z8XQCEW5AnwCBiInUMQFE1AJqAX53F0KoiNfxp4CQSNoA4SgInA1SBMP7Tx9NrJvSHoCmgPeAhk6lCLVTEWeCZwGHQlMt7BfwoQGR+FWyDHgc/Ac9BUZsTqWNEXQApyDLjdttkzJYqNPwT9CLKojkOBCyXFfjh4U5BTQZhuz1UAGoAsdJBgt1jQolAlZkHRpSbbTBcpMhW4WY4cDQXO1WR1LBnwvcknAJHxLwncAcbAuqJP5yuwtM0n6A2QC6AnQR4cCdPVfv7yNYVlgXOgnwSpdcRsL0utp6okZAG4rogPfANWiz3o5eJn9kQ6cJvlgQqOfvkAeq78lo8Jt4/2Kl7u06sFqLJzO74tf2nxajZCtdaz02XOGZBVCtyjwWItc9QWLM7YCVCX1kZWS6LTtEZtrShRVgivcDlu4HklshVwAxQ7Ps1zSID0/0tECiT5eOoquAv6DmSi6AHq3VDDe9gmcEWQRdDXzRoAEBt/CXgFHAKGQHFE/gF+5ngA7M9xprAt6BTkchCmX12+mQ8rdzgLjBQ2nBK9sXM6UvSxU5aJwAg40ySHjiszCNMESCLjJc5pkwThzhQgMt6vwlftXbEVhDttVPPvZGDX6ZXdEtmTs/QJwrSToPXKrEzWgB/5b91ZeA+6BfwG7fxHAfAXfJIQh9RXB18AAAAASUVORK5CYII=";
//somewhere in code
imageView = (ImageView) view.findViewById(R.id.imageView);//layout params are wrap and wrap
//weak reference is for safe using imageView when app i.e will exit and task will still be running
weakReferenceImageView = new WeakReference<ImageView>(imageView);
new AsyncTask<Void, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(Void... params) {
byte[] encode = Base64.decode(base64.getBytes(), 0);
Bitmap bitmap = BitmapFactory.decodeByteArray(encode, 0, encode.length);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null) {
if (weakReferenceImageView != null) {
ImageView weak = weakReferenceImageView.get();
if (weak != null) {
weak.setImageBitmap(bitmap);
}
}
}
}
}.execute();
If decoding is wrong, returned bitmap will be null.
Please try with my image (it is very small) if it works. If it works it means something is wrong with your based64 image.
Fixed example, added weakReference as a good sample of coding.
ImageView image = (ImageView) findViewById(R.id.image);
String image_url = "http://api.androidhive.info/images/sample.jpg";
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
imgLoader.DisplayImage(image_url, loader, image);
Use the library found on the url.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
ImageLoader.java, FileCache.java, and Utils.java
Just Use Picasso
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Couldn't be easier than this.
So I'm stuck on this... I need to display images in a listview which gets its data from a json file.
I've already setup the connection, parsed the json file and displayed what i need. But somehow I can't find much information about how to turn a string (which has the URL) into an image in a listview.
The string which has the url is called "ImageLink"
Below is my MainActivity.
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get game info JSON
private static String url = "https://dl.dropboxusercontent.com/u/38379784/Upcoming%20Games/DataForUPG.js";
// JSON Node names
private static final String TAG_Games = "games";
private static final String TAG_Title = "Title";
private static final String TAG_Description = "Description";
private static final String TAG_Release = "Release";
private static final String TAG_ImageLink = "ImageLink";
// Gameinfo JSONArray
JSONArray games = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> GamesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GamesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Title = ((TextView) view.findViewById(R.id.Title))
.getText().toString();
String Description = ((TextView) view.findViewById(R.id.Description))
.getText().toString();
String Release = ((TextView) view.findViewById(R.id.Release))
.getText().toString();
String ImageLink = ((TextView) view.findViewById(R.id.ImageLink_label))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleListItem.class);
in.putExtra(TAG_Title, Title);
in.putExtra(TAG_Description, Description);
in.putExtra(TAG_Release, Release);
in.putExtra(TAG_ImageLink, ImageLink);
startActivity(in);
}
});
// Calling async task to get json
new GetGames().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetGames extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
games = jsonObj.getJSONArray(TAG_Games);
// looping through All games
for (int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
String Title = c.getString(TAG_Title);
String Description = c.getString(TAG_Description);
String Release = c.getString(TAG_Release);
String ImageLink = c.getString(TAG_ImageLink);
// tmp hashmap for single game
HashMap<String, String> games = new HashMap<String, String>();
// adding each child node to HashMap key => value
games.put(TAG_Title, Title);
games.put(TAG_Description, Description);
games.put(TAG_Release, Release);
games.put(TAG_ImageLink, ImageLink);
// adding contact to gameinfo list
GamesList.add(games);
}
} 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);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, GamesList,
R.layout.list_item, new String[] { TAG_Title, TAG_Release,
TAG_Description, TAG_ImageLink }, new int[] { R.id.Title,
R.id.Release, R.id.Description, R.id.ImageLink_label });
setListAdapter(adapter);
}
}
}
I would appreciate any help
Well, you could probably create another async task to handle downloading the image like this:
private class DownloadImg extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String TAG_ImageLink = params[0];
Bitmap bm = null;
try {
InputStream in = new java.net.URL(TAG_ImageLink).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
or you could use a 3rd party image loading library like picasso or volley's ImageRequest
I have an android code which receives images as base64 string from the server in the form of json data. The code is given below. After receiving the images I have to decode the images as bitmap. And after that I have to display that images in an image gridview. How can this acheived? please help me. Thanks in advance.
package com.example.mygallery;
//skipping the import section
public class Gallery extends Activity
{
int refresh=0;
Bitmap decodedByte;
GridView gridView;
String username,password,count1,status;
int count;
ArrayList<String>imagearraylist;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
gridView = (GridView) findViewById(R.id.grid_view);
SharedPreferences sp=getSharedPreferences("My_login", MODE_PRIVATE);
username=sp.getString("username", "");
password=sp.getString("password", "");
new serverconnection().execute();
}
public class serverconnection extends AsyncTask<Void, String, Void>
{
#Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
try
{
String link="http://tonyjoseph.site90.com/sendimage.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter (conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader (new InputStreamReader(conn.getInputStream()));
StringBuilder sb=new StringBuilder();
String line = null; // Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
String status=sb.toString();
JSONObject jsonResponse1;
try
{
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse1 = new JSONObject(status);
/***** Returns the value mapped by name if it exists and is a JSONArray. Returns null otherwise.*******/
JSONArray jsonMainNode=jsonResponse1.optJSONArray("Android");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
Log.d("Json Array Length",String.valueOf(lengthJsonArr));
for(int j1=0;j1<lengthJsonArr;j1++)
{
Context mContext;
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(j1);
/******* Fetch node values **********/
String index=jsonChildNode.optString("index").toString();
String imagename=jsonChildNode.optString("imagename").toString();
//Here I get the images from server as string one after another
byte[] decodedString = Base64.decode(imagename, Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
// At this stage I will be getting a list of bitmapsfrom the server which is converted from the received json
// i need to display these bitmaps into a image grid view ie display the images as a grid
// how can this be acheived??
}
}
catch(Exception ex)
{
System.out.print(ex);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(Gallery.this, "Loading complete", Toast.LENGTH_LONG).show();
pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd=new ProgressDialog(Gallery.this);
pd.setTitle("Loading images..");
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
}
}
At that stage use runOnUiThread to place the received Bitmap 'in the grid'. But if you do not first save or cache all received bitmaps the grid will loose them with UI updates. The actual placing in the grid will be done by getView() calls after notify dataset changed.
Actually you do not need runOnUiThread at all. Just in doInBackGround save all images to a specific folder. Then in onPostExecute do a notifyDataSetChanged. The listview knows to retrieve from that folder.