This project I've done with image in my drawable but now I want to get image url from JSON by using Asynctask and display it. and I make php that provide a json string like below.
I want to get path of image(url) by using AsyncTask from JSON.
I want to use data from json instead of public mThumbId = {...};
{"count":"28","data":
[{"id":"1",
"first_name":"man",
"last_name":"woman",
"username":"man",
"password":"4f70432e636970de9929bcc6f1b72412",
"email":"man#gmail.com",
"url":"http://vulcan.wr.usgs.gov/Imgs/Jpg/MSH/Images/MSH64_aerial_view_st_helens_from_NE_09-64_med.jpg"},
{"id":"2",
"first_name":"first",
"last_name":"Last Name",
"username":"user",
"password":"1a1dc91c907325c69271ddf0c944bc72",
"email":"first#gmail.com",
"url":"http://www.danheller.com/images/California/Marin/Scenics/bird-view-big.jpg"},
{"id":"3",
"first_name":"first",
"last_name":"Last Name",
"username":"user",
"password":"1a1dc91c907325c69271ddf0c944bc72",
"email":"0",
"url":"http://www.hermes.net.au/bodhi/images/view/large/view_03.jpg"}]}
AndroidGridLayoutActivity
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
R.drawable.pic_5, R.drawable.pic_6,
R.drawable.pic_7, R.drawable.pic_8,
R.drawable.pic_9, R.drawable.pic_10,
R.drawable.pic_11, R.drawable.pic_12,
R.drawable.pic_13, R.drawable.pic_14,
R.drawable.pic_15
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
FullImageActivity
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
I think that this simple link will totally answer your question:
https://github.com/novoda/ImageLoader
And my own implementation:
https://github.com/iRail/BeTrains-for-Android/blob/master/src/tof/cv/mpp/adapter/TweetItemAdapter.java
EDIT
What you really need to do:
1) Parse JSON: there are thousands of tutorials on the web, or use the awesome GSON library.
2) Once JSON is parsed, you will get an array of objects.
3) In your Adapter, you will maybe need to extend ArrayAdapter.
4) in the getView() method, analyse my 2 above links and use something like:
imageLoader.DisplayImage(tweet.profile_image_url, activity, holder.image);
You have to first extract the urls from json in a array and then use below code to load image as bitmap dynamically using Async Task.
Bitmap bm[]=new Bitmap[3];
ImageAdapter img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bm[0]=null;
bm[1]=null;
bm[2]=null;
InputStream is= getDataFromServer();
String asd=getResponseFromStream(is);
try {
JSONObject jsn=new JSONObject(asd);
JSONArray jd=jsn.getJSONArray("data");
for(int i=0;i<jd.length();i++)
{
JSONObject j_object=jd.getJSONObject(i);
String url=j_object.getString("url");
urls.add(url);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
img=new ImageAdapter(this);
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(img);
new ImageDownloader().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
ProgressDialog prg;
private class ImageDownloader extends AsyncTask<Integer, Integer, String>
{
#Override
public void onPreExecute()
{
prg=ProgressDialog.show(LazyLoadActivity.this, null,
"Loading...");
}
protected void onPostExecute(String result)
{
prg.hide();
}
protected void onProgressUpdate(Integer... progress) {
img.notifyDataSetChanged();
}
protected String doInBackground(Integer... a)
{
for(int i=0;i<3;i++)
{
bm[i]=downloadBitmap(urls[i]);
this.publishProgress(i);
}
return "";
}
}
public Integer[] mThumbIds = {
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher
};
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
if(bm[position]==null)
imageView.setImageResource(mThumbIds[position]);
else
imageView.setImageBitmap(bm[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
Bitmap downloadBitmap(String url) {
final HttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
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 {
inputStream = entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.e("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
//client.
}
}
return null;
}
Related
I'm trying to display images in gridview, I fetched images from remote server by soap service "in ImageAdapter1 class, method:set_mThumbIds()" and get these images to display in class "collection_Items"
it doesn't work at all!
can any one please help me!
I want to fetch images from soap service and view them in girdview
ImageAdapter1 class is:
public class Image_Adapter1 extends BaseAdapter {
private Context mContext;
Handler handler = new String[30];
public String[] mThumbIds = new String[30];
// Constructor
public Image_Adapter1(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
public void set_mThumbIds(){
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String NAMESPACE = "http://tempuri.org/";
String ACTION="http://tempuri.org/getImages";
String URL="http://10.0.2.2:50284/WebSite2/Service.asmx";
String METHOD="getImages";
SoapObject Req = new SoapObject(NAMESPACE,METHOD);
SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
env.dotNet=true;
env.setOutputSoapObject(Req);
HttpTransportSE androidhttp = new HttpTransportSE(URL);
SoapObject Result = null;
try
{
androidhttp.call(ACTION,env);
Result = (SoapObject) env.getResponse();
}
catch (final Exception c)
{
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(mContext, c.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
if (Result != null)
{
for (int i=0; i<mThumbIds.length; i++)
{
mThumbIds[i] = Result.getPropertyAsString(i);
}
}
else
Toast.makeText(mContext, "there are no images",Toast.LENGTH_LONG).show();
}
}).start();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
set_mThumbIds();
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(150, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageURI(Uri.parse(mThumbIds[position]));
return imageView;
}
}
and collection_Items class is:
public class Collection_Items extends Activity{
Image_Adapter1 imgadptr = new Image_Adapter1(this);
//___________________________________________________________
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collection_items);
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(imgadptr);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent i = new Intent(getApplicationContext(), Collection_Item_Details.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
public void logout(View view){
startActivity(new Intent(Collection_Items.this, Main.class));
}
}
i'm working on wallpaper app
i implemented this code in order to load my pictures from assets
loading-images-from-assets-folder
it's working great but i have issue with getting itemid from the list to use the id to display one of these images in fullscreenactivity or setting wallpaper
public long getItemId(int position) {
return position ;
}
here is my code
public class ImageAdapter extends BaseAdapter{
private Context mContext;
private List<String> list;
private AssetManager assetManager;
public ImageAdapter(Context c, List<String> list) {
mContext = c;
this.list = list;
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
try {
InputStream is = mContext.getAssets().open(list.get(position));
Bitmap bm = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bm);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
} catch (IOException e) {
e.printStackTrace();
}
// TODO Auto-generated method stub
return imageView;
}
public class Gs3Wallpaper extends Activity {
private ImageButton Gs3Button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.GridView1);
try {
gridView.setAdapter(new ImageAdapter(this ,getImage()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public List<String> getImage()throws IOException {
AssetManager assetManager = getAssets();
String[] files = assetManager.list("gallary");
List<String> list = new ArrayList<String>();
for (String it : files) {
list.add("gallary"+File.separator + it);
}
return list;
i don't know how to get the id from the list i tried to use list.get(position) but it returns string not int so i can't pass that to setImageResource for example
any suggestions?
What you can do is set the image or a path to the image, depending on how you are doing it, in a HashMap in getView() when you set the list item. Use the position for the key and the image as the value
public class MyClass
{
HashMap<String, Bitmap> imageMap = new HashMap<String, Bitmap>();
...
then set it in your getView()
public View getView(int position, View view, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
try {
InputStream is = mContext.getAssets().open(list.get(position));
Bitmap bm = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bm);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
String posString = String.valueOf(position);
imageMap.put(posString, bm);
} catch (IOException e) {
....
}
Something like this should work for you. Then just use the position to get that bitmap out of the HashMap
I have been trying to pass bitmap array to another Activity for a week but I still can't do it
public class HomePage extends Activity {
private GridView gridView;
public Bitmap[] mBitArray;
public Bitmap[] mBitArray5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
gridView = (GridView) findViewById(R.id.GridView1);
mBitArray = new Bitmap[7];
try
{
//these images are stored in the root of "assets"
mBitArray[0] = getBitmapFromAsset("Gallary/g1p1.jpg");
mBitArray[1] = getBitmapFromAsset("Gallary/g1p2.jpg");
mBitArray[2] = getBitmapFromAsset("Gallary/g1p3.jpg");
mBitArray[3] = getBitmapFromAsset("Gallary/g1p4.jpg");
mBitArray[4] = getBitmapFromAsset("Gallary/g1p5.jpg");
mBitArray[5] = getBitmapFromAsset("Gallary/g1p6.jpg");
mBitArray[6] = getBitmapFromAsset("Gallary/g2p1.jpg");
mBitArray[7] = getBitmapFromAsset("g2p2.jpg");
mBitArray[8] = getBitmapFromAsset("hd-01.jpg");
mBitArray[9] = getBitmapFromAsset("hd-02.jpg");
mBitArray[10] = getBitmapFromAsset("hd-03.jpg");
mBitArray[11] = getBitmapFromAsset("hd-04.jpg");
}
catch (IOException e)
{
e.printStackTrace();
}
gridView.setAdapter(new ImageAdapter(this, mBitArray));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
// TODO Auto-generated method stub
}
});
}
public Bitmap getBitmapFromAsset(String strName) throws IOException {
AssetManager assetManager = getAssets();
InputStream istr = assetManager.open(strName);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
istr.close();
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home_page, menu);
return true;
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Bitmap[] mImageArray;
public ImageAdapter(Context context, Bitmap[] imgArray)
{
mContext = context;
mImageArray = imgArray;
}
public int getCount() {
return mImageArray.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return mImageArray[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(mImageArray[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(153, 150));
return imageView;
}
public Bitmap getView1(int position) throws IOException {
AssetManager am = mContext.getAssets();
String[] list = am.list("Gallary");
BufferedInputStream buf = new BufferedInputStream(am.open(list[position]));
Bitmap bitmap = BitmapFactory.decodeStream(buf);
buf.close();
return bitmap;
}
}
public class FullImageActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fullimage);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this , null);
//imageView.setImageBitmap(mBitArray[position]);
trying to get mBitarray to fullscreenactivity to display a certain picture from the bitmap array
so I want to pass MbitArray variable to Fullactivity class I tried to do it by Intent but I can't send Bitmap array maybe via constructor or inner class?
Since Bitmap implements Parcelable, and you have an array of Bitmap, you should be able to pass them off:
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("bitmaps", mBitArray);
startActivity(i);
Then retrieve via getParcelableArrayExtra():
Intent i = getIntent();
Bitmap [] bitmaps = (Bitmap[]) i.getParcelableArrayExtra ("bitmaps");
You can also pass off the paths in a String array to FullImageActivity, then just remake them there, much like you did in your first Activity. To save code, if you choose this approach, making the method shared by making it static would be a good idea, just remember to pass off a Context instance so getAssets() can still be used:
public static Bitmap getBitmapFromAsset(Context context, String strName) throws IOException {
AssetManager assetManager = context.getAssets();
InputStream istr = assetManager.open(strName);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
istr.close();
return bitmap;
}
Then to call, from HomePage
mBitArray[0] = getBitmapFromAsset(this,"Gallary/g1p1.jpg");
and from FullImageActivity
otherBitmapArray[0] = HomePage.getBitmapFromAsset(this, bitmapPaths[0]);
I am trying to add Loading dialog in following code to fetch image from server and display it in Gallery view. it shows blank screen untill image comes. please help me how do i show Loading dialog while getting image from server.
Here is the code, pls help.
public class ImagedisplaytestActivity extends Activity {
private ImageView leftArrowImageView;
private ImageView rightArrowImageView;
private Gallery gallery;
public int selectedImagePosition;
private GalleryImageAdapter galImageAdapter;
private String bitmapImg = "";
Bitmap bitmap = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupUI();
}
private void setupUI() {
Intent i = getIntent();
Bundle extras=i.getExtras();
bitmapImg = extras.getString("BitmapImage");
selectedImagePosition = extras.getInt("Pos");
leftArrowImageView = (ImageView) findViewById(R.id.left_arrow_imageview);
rightArrowImageView = (ImageView) findViewById(R.id.right_arrow_imageview);
gallery = (Gallery) findViewById(R.id.gallery);
leftArrowImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (selectedImagePosition > 0) {
--selectedImagePosition;
}
gallery.setSelection(selectedImagePosition, false);
}
});
rightArrowImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (selectedImagePosition < DetailView.bitmapURL.size() - 1) {
++selectedImagePosition;
}
gallery.setSelection(selectedImagePosition, false);
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selectedImagePosition = pos;
if (selectedImagePosition > 0 && selectedImagePosition < DetailView.bitmapURL.size() - 1) {
leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_disabled));
rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
} else if (selectedImagePosition == 0) {
leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_enabled));
} else if (selectedImagePosition == DetailView.bitmapURL.size() - 1) {
rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_enabled));
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
galImageAdapter = new GalleryImageAdapter(this, DetailView.bitmapURL);
gallery.setAdapter(galImageAdapter);
if (DetailView.bitmapURL.size() > 0) {
gallery.setSelection(selectedImagePosition, false);
}
if (DetailView.bitmapURL.size() == 1) {
rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
}
}
public class GalleryImageAdapter extends BaseAdapter {
private Activity context;
private ImageView imageView;
private List<String> plotsImages;
private ViewHolder holder;
public GalleryImageAdapter(Activity context, List<String> plotsImages) {
this.context = context;
this.plotsImages = plotsImages;
}
#Override
public int getCount() {
return plotsImages.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
imageView = new ImageView(this.context);
imageView.setPadding(3, 3, 3, 3);
convertView = imageView;
holder.imageView = imageView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
holder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
try {
bitmap = DownloadImage(plotsImages.get(position));
holder.imageView.setImageBitmap(bitmap);
bitmap = null;
} catch (Exception e) {
e.printStackTrace();
}
return imageView;
}
private class ViewHolder {
ImageView imageView;
}
private Bitmap DownloadImage(String URL){
Bitmap bitmap = null;
try {
InputStream in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String urlString) throws IOException{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
throw new IOException("Not an HTTP connection");
}
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex){
throw new IOException("Error connecting");
}
return in;
}
}
#Override
public void onBackPressed() {
DetailView.bundleID = DetailView.idList.get(selectedImagePosition);
super.onBackPressed();
}
}
You should use AsyncTask!
See this also!
& in Vogella Example will clear your doubt .
see this for the lazy image Loading DEMO! on github.
use assynctask,
in that assynctask method you can write your getting images from server in doinbackground(),
in that time you can display alert dialogue using preexectue(), after loading from server just dismiss the alert dialogue in postexectue().
This code work for me
private class LoadGlobalDataSearch extends AsyncTask<String, Void, Void>
{
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected Void doInBackground(String... params)
{
//Load your images this task
setupUI();
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressdialog = ProgressDialog.show(MainActivity.this, "",getString(R.string.inprogress));
}
}
call this class in your oncreate method
new loadImages().execute(0);
You can use a progress dialoge until the image is downloaded then remove the dialog.
In OpenHttpConnection add this --
dialog = ProgressDialog.show(DutyRotaActivity.this, "",
"Please wait for few seconds...", true);
in DownloadImage dissmiss the dialog.
dialog.dismiss();
Or you can use asynchronous task too. cause network operation should always do on other thread
not in the main thread. In that case in preExecute add the dialog and in postExecute dissmiss the dialog. And in doinbackground call your downloadimage function that will also do the tricks.
Edit
Here is a complete source code and a library to load image lazily in the listView. I think its also can help you to solve your issue.Thanks
https://github.com/nostra13/Android-Universal-Image-Loader
I have an application which allow to download 3 images and show them into a gallery
In order to do this , i use a thread in order to download the images and a handler in order to put the images into the gallery
The problem is that the images are not displayed(imageviews are empty) into the gallery (even if i see 3 imageview for my 3 images)
I do not know if this is because the connection is very slow (I develop on a mobile) or if it's because the ui is displayed before images are downloaded
Thank you very much for your help
public class ChoiceLanguage extends Activity {
private TextView nomLangue;
private ArrayList<Language> listeLangues;
private ArrayList<String> listImages;
private Gallery gallery;
private String URL="******************";
private Drawable mNoImage;
Bitmap bitmap;
ImageView imgView = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choice_language);
listeLangues= getIntent().getParcelableArrayListExtra("listeLangues");
listImages=buildListImages();
gallery = (Gallery) findViewById(R.id.galleryImg);
gallery.setAdapter(new AddImgAdp(this));
gallery.setSpacing(10);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
System.out.println("URL "+ listImages.get(position) );
}
});
}
private InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
in=conn.getInputStream();
return in;
}
private Bitmap downloadImage( ImageView iView, String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedInputStream bis ;
try {
in = openHttpConnection(url);
bis= new BufferedInputStream(in, 8192);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
private ArrayList<String> buildListImages() {
ArrayList<String> listImg = new ArrayList<String>();
for(Language l : listeLangues) {
listImg.add(URL+l.getImagePath());
}
return listImg;
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return listImages.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imgView = new ImageView(cont);
} else {
imgView = (ImageView)convertView;
}
ThreadDownload progressDl= new ThreadDownload(position);
progressDl.start();
imgView.setLayoutParams(new Gallery.LayoutParams(150, 150));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
private class SetImg extends Handler {
public void handleMessage(Message msg) {
imgView.setImageBitmap(bitmap);
}
}
private class ThreadDownload extends Thread {
SetImg img= new SetImg();
int position ;
public ThreadDownload(int position)
{
super();
this.position=position;
}
public void run() {
bitmap = downloadImage(imgView,listImages.get(position));
img.sendEmptyMessage(0);
}
}
}
You can make use of SmartImageView, it is a drop-in replacement for Android’s standard ImageView which additionally allows images to be loaded from URLs or the user’s contact address book. Images are cached to memory and to disk for super fast loading.
https://github.com/loopj/android-smart-image-view