I want to download the image from server and convert it to bitmap. I tried to download the image and convert it to bitmap but it returns null. I get bitmap as null.
To convert image to bitmap I have created one asyncTask.
Passing url to Async task :
String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
Log.e("url", url);
new ImageUserTask(mContext, url, profileImage).execute();
ImageUserAsync Task:
public class ImageUserTask extends AsyncTask<Void, Void, Bitmap> {
String imageprofile;
private String url;
private Bitmap mBitmap;
private Context mContext;
public ImageUserTask(Context context, String url, String imageprofile) {
this.url = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
//Url
URL urlConnection = new URL(url);
//Conntecting httpUrlConnection
HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
//converting image to bitmap
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
result = mBitmap;
new ImageServer(mContext).save(result);
}
}
}
EDIT :
Tried to use picasso :
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
count=0;
if (response.has("message")) {
JSONObject userJson = null;
String message = null;
count++;
try {
if (response.getString("message").equalsIgnoreCase(KEY_SUCCESS)) {
Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
userJson = response.getJSONObject("user");
String userId = userJson.getString("user_id");
String userName = userJson.getString("user_name");
String profileImage = userJson.getString("profile_image");
String mobileNo = userJson.getString("mobile_no");
String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
Log.e("url", url);
User user = new User();
user.setmUserId(userId);
user.setmUserName(userName);
user.setmProfileImage(profileImage);
user.setmMobileNo(mobileNo);
SharedPreferences.Editor editor = mContext.getSharedPreferences("username",mContext.MODE_PRIVATE).edit();
editor.putString("UserUsername",userName);
editor.commit();
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File f = new File(mContext.getCacheDir(), "Profile");
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
Log.e("File",String.valueOf(f));
}
catch (IOException e)
{
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(mContext).load(url).into(target);
Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
mContext.startActivity(intent);
Picasso.with(mContext).cancelRequest(target);
}
}
What's going wrong?
Try this I am getting image by this method.
URL url1l = new URL("<Image url>");
URLConnection connection = url1l.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
The most likely reason is that you are getting an error from the server or that the data you are getting back cannot be decoded. First of all, check the response code after the connection is opened:
connection.connect();
int respCode = connection.getResponseCode();
Log.d("resp code", "response code " + respCode);
If you get anything other than 200, then something is wrong with retrieving data (wrong url, auth, or server error). If you do get 200, then the issue is with the data you are receiving. Read the data into a byte array and dump it into a file to examine.
First check with image is really exists or not as #aman grover said
if available use Picasso Lib to download image and from url.
here is sample code
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//Note : here you can get Bitmap
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
private void someMethod() {
Picasso.with(this).load("url").into(target);
}
#Override
public void onDestroy() { // could be in onPause or onStop
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}
Related
Good day everybody.
I'm trying to code an android app which should retrieve from a mysql db a blob and convert it to an imageview on android.
I can succesfully load the image to webserver (XAMPP) encode it to blob and store it in sql table.
greetings to everyone!
public class RequestHandler {
public String sendGetRequest(String uri) {
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
StringBuilder sb = new StringBuilder();
while((result = bufferedReader.readLine())!=null){
sb.append(result);
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
here the code to retrieve the image:
public class ViewImage extends AppCompatActivity implements View.OnClickListener{
private RequestHandler requestHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
RequestHandler rh = new RequestHandler();
buttonGetImage.setOnClickListener(this); }
private void getImage() {
String id = editTextId.getText().toString().trim();
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewImage.this, "Uok..", null,true,true);
}
#Override
protected void onPostExecute(Bitmap b) {
super.onPostExecute(b);
loading.dismiss();
imageView.setImageBitmap(b);
}
#Override
protected Bitmap doInBackground(String... params) {
String id = params[0];
String add = "http://192.168.1.121:8080/getImage.php?id="+id;
URL url = null;
Bitmap image = null;
try {
url = new URL(add);
rh.sendGetRequest(add);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
}
GetImage gi = new GetImage();
gi.execute(id);
}
#Override
public void onClick(View v) {
getImage();
}
}
here the php script:
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select * from image where id = '$id'";
require_once('dbConnect.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
header('content-type: image/jpeg');
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
Any thoughts on what am I doing wrong here?
Thanks!
As we know that, Image parsing we are using Bitmap, or Base64 Ecodder.
I suggest you to use library like Glide, Picasso this is official library...
You don't have to write so much code.
Avoid to use Boiler Plate Code in Development.
Picasso
Picasso.get()
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
Glide
GlideApp.with(context)
.load("http://via.placeholder.com/300.png")
.override(300, 200)
.into(ivImg);
I am trying to download the image from url and save it in a file. But it's not getting saved. So as I debug the code I found that bitmap is always null.
code:
public class ImageUserTask extends AsyncTask<Void, Void,String> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected String doInBackground(Void... params) {
Bitmap bitmap = null;
File directory = null;
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream()); //This bitmap is null always
directory = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/Profile");
if (!directory.exists() && !directory.isDirectory()) {
directory.mkdirs();
}
File mypath = new File(dir,"ProfileImage");
saveFile(mypath, bitmap);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return directory.getAbsolutePath();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
imageprofile = result;
}
}
private void saveFile(File fileName, Bitmap bmp) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 100 will be ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
EDIT:
public class ImageUserTask extends AsyncTask<Void,Void,Bitmap> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
getImageFromUrl(strURL);
return mBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
Bitmap bitmap = result;
}
}
public Bitmap getImageFromUrl(String urlString) {
try {
URL url = new URL(urlString);
try {
if(mBitmap!=null) {
mBitmap.recycle();
mBitmap=null;
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
mBitmap = BitmapFactory.decodeStream(input);
convertBitmapToFile(mBitmap, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return mBitmap;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(mContext);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
}
What can be the reason? I have added Internet permissions too. Please help. Thank you..
class DownloadFile extends AsyncTask<String, Integer, String> {
String strFolderName;
String shareType;
String downloadPath = "";
Activity mContext;
public DownloadFile(Activity mContext) {
this.mContext = mContext;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
String fileName = "your filename with ext";
Log.d("TAG", fileName);
URL url = new URL("your url");
URLConnection conexion = url.openConnection();
conexion.connect();
String PATH = "your Path you want to store" + "/";
downloadPath = PATH + fileName;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(downloadPath);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String path) {
super.onPostExecute(path);
}
}
This code is work for me
Use the below methods
public Bitmap getImageFromUrl(String urlString) {
Bitmap bmp = null;
try {
URL url = new URL(urlString);
try {
if(bmp!=null) {
bmp.recycle();
bmp=null;
}
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
convertBitmapToFile(bmp, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return bmp;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(activityRef.getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
Add android Permissions for internet and Storage
Please try this
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.
What are the correct way to convert Uri image to Base64 String before send to server ?
public void update( final String claimType, final String Amount, final String Description, final String imageUri)
{
class updateImageAndText extends AsyncTask<Void,Void,String>{
// ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
// loading = ProgressDialog.show(Edit_Staff.this,"Updating...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
try {
Intent returnIntent = new Intent();
returnIntent.putExtra("ClaimType", claimType);
returnIntent.putExtra("Amount", Amount);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("photo", imageUri);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}catch(Exception e)
{
}
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Configs.KEY_ID, String.valueOf(ID));
Log.e("ID", ID + "");
hashMap.put(Configs.KEY_TYPE, claimType);
hashMap.put(Configs.KEY_AMOUNT, Amount);
hashMap.put(Configs.KEY_DESCRIPTION, Description);
if(imageUri != null){
Log.d("log", "photo " + imageUri);
hashMap.put(Configs.KEY_IMAGE,getStringImage(imageUri)); // error
}else{
Log.d("log", "photo is null " );
}
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Configs.URL_UPDATEDE_IMAGE_TEXT,hashMap);
return s;
}
}
updateImageAndText ue = new updateImageAndText();
ue.execute();
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
Error
Error:incompatible types: String cannot be converted to Uri
In update you are passing imageUri as a String:
public void update( final String claimType, final String Amount, final String Description, final String imageUri)
hashMap.put(Configs.KEY_IMAGE,getStringImage(imageUri)); // error because imageUri is a String
But your method expect a Uri not String:
public String getStringImage(Uri imgUri){...}
I am downloading image from the server using below function. This works perfect for all android version except Android 2.2 Froyo device. Please help.
private Bitmap downloadImage(String url) {
System.out.println("Splash Ad downloadImage Url " + url);
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub", "Error getting the image from server : "
+ e.getMessage().toString());
e.printStackTrace();
}
return bm;
}
Try this code.
public class ImageDisplay extends Activity {
ImageView image;
ProgressBar spinner;
TextView message;
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_display);
image=(ImageView) findViewById(R.id.imageDisplay);
spinner=(ProgressBar)findViewById(R.id.progressBar_spinner);
message=(TextView)findViewById(R.id.textView1);
spinner.setVisibility(View.INVISIBLE);
displayImage();
}
private class DownloadImage extends AsyncTask<String, Void,Bitmap >
{
Bitmap bitmap;
String error_messsage="No error";
#Override
protected Bitmap doInBackground(String... urls) {
for(String url:urls){
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Log.e("here",""+bytes.length);
bitmap = BitmapFactory.decodeByteArray(bytes, 0,bytes.length);
Thread.sleep(1000);
}
else
{
error_messsage="Download failed, HTTP response code "+ statusCode + " - " + statusLine.getReasonPhrase();
}
} catch (Exception er) {
Log.e("Error",""+er);
}}
//image.setImageBitmap(bitmap);
return bitmap ;
}
#Override
protected void onPostExecute(Bitmap result) {
spinner.setVisibility(View.INVISIBLE);
image.setImageBitmap(result);
}
}
public void displayImage()
{
DownloadImage task = new DownloadImage();
task.execute(new String[] { "http://team-android.com/wp- content/uploads/2011/03/Android-3d_428.jpg" });
snap.setVisibility(View.VISIBLE);
}