Bitmap bitmap = BitmapFactory.decodeStream(result);
HERE IN LOG I AM GETTING
03-05 06:47:36.639: E/bitmap(931): android.graphics.Bitmap#417d5948
BUT THEN EXCEPTION COMES OF NULL POINTER EXCEPTION
public class DetailsActivity extends Activity {
private ImageView image;
//ASYNCTASK
class DownloadImageTask extends AsyncTask<Void, Void, InputStream> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(DetailsActivity.this);
dialog.setTitle("Please wait");
dialog.setMessage("Please wait while the application is downloading the image");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected InputStream doInBackground(Void... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
url FROM WHERE WE HAVE TO FETCH IMAGE
String stringURL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
try {
Log.e("URL TEST",""+stringURL);
stringURL=stringURL.replaceAll(" ", "%20");
URL url = new URL(stringURL);
Log.e("URL TEST",""+url);
//stringURL=stringURL.replaceAll(" ", "%20");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
Log.e("TESTING","TESTING"+ stream);
return stream;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
//Bitmap bi = BitmapFactory.
try{Bitmap bitmap = BitmapFactory.decodeStream(result);
Log.e("bitmap",""+bitmap);
ERROR AT THIS LINE==>image.setImageBitmap(bitmap);
//Log.e("final"," " + image.setImageBitmap(bitmap));
}catch(Exception e){
Log.e(" YNull" , ""+ e);//NULL POINTER EXCEPTION
}
dialog.cancel();
}
}
private void asyncDownload() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectNetwork().build());
DownloadImageTask task = new DownloadImageTask();
task.execute();
}
///////////////////////////////////////////////////////////////////////////////
Async Dowloader
/////////////////////////////////////////////////////////////////////////////
ONCREATE METHORD
IMAGE IS NOT GETTING FETCHED
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
image = (ImageView)findViewById(R.id.imageView2);
ActionBar actionBar = getActionBar();
actionBar.hide();
setContentView(R.layout.activity_details);
asyncDownload();
}
First correct this You should return InputStream stream
return stream;
Instead of
return null;
in doInBackground() in your DownloadImageTask
Don't return the input stream. Download the complete data into a byte array and return it. Then in onPostExecute, use the byte array to decode the image.
#Override
protected byte[] doInBackground(Void... params) {
....
Log.e("URL TEST",""+stringURL);
stringURL=stringURL.replaceAll(" ", "%20");
URL url = new URL(stringURL);
Log.e("URL TEST",""+url);
//stringURL=stringURL.replaceAll(" ", "%20");
URLConnection connection = url.openConnection();
DataInputStream stream = new DataInputStream(connection.getInputStream());
int len = connection.getContentLength();
byte[] data = new byte[len];
stream.readFully(data, 0, len);
Log.e("TESTING","TESTING"+ stream);
return data;
....
}
Then in onPostExecute, use this:
#Override
protected void onPostExecute(byte[] result) {
super.onPostExecute(result);
//Bitmap bi = BitmapFactory.
try{
Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
Log.e("bitmap",""+bitmap);
//Log.e("final"," " + image.setImageBitmap(bitmap));
} catch(Exception e){
Log.e(" YNull" , ""+ e);//NULL POINTER EXCEPTION
}
dialog.cancel();
}
Related
I have a problem in API 8 with AsyncTask...
Here is my code...
try{
new loadPhotos().execute(""+USER._id,"date","DESC");
}catch(Exception e){
e.printStackTrace();
}
Before you ask... YES I am desperate, so I surrounded EVERYTHING with try{}catch
public class loadPhotos extends AsyncTask<String,Object,Void>{
ProgressBar pb;
ImageView img;
TableRow.LayoutParams paramsImage;
List<String> urlsOfImages;
TableLayout tl;
TableRow tr;
LayoutParams lp;
int numberOfPhotos=0;
#Override
protected void onPreExecute(){
urlsOfImages = new ArrayList<String>(); //There is stored urls of all images ( www.example.com/image1.jpg ... etc)
try {
allUserPhotoBitmaps.clear(); //allUserPhotoBitmaps is List<Bitmap>
pb = (ProgressBar) findViewById(R.id.profile_photos_progress_bar);
pb.setVisibility(View.VISIBLE);
tl = (TableLayout) findViewById(R.id.profile_photos_table_layout);
tl.removeAllViews();
tr = new TableRow(Profile.this);
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(lp);
}catch(Exception e){
Toast.makeText(Profile.this, "Error in onPreExecute", Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(String... arg) {
try{
// This function basicaly returns List<HashMap<String,String>> with informations about photos ( web_path, latitude, longitude, city, etc...)
allUserPhotoInformations = myDb.getUrlsOfUserImages(arg[0],arg[1],arg[2]);
}catch(Exception e){
Toast.makeText(Profile.this, "Error downloading images", Toast.LENGTH_SHORT).show();
}
if ( allUserPhotoInformations != null ) {
for (int i=0 ; i < allUserPhotoInformations.size() ; i++){
try{
Bitmap bm = getBitmapFromURL(allUserPhotoInformations.get(i).get("file_path"));
allUserPhotoBitmaps.add(bm);
publishProgress(bm,i);
}
catch(Exception e){
return null;
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Object... arg){
img = new ImageView(getBaseContext());
paramsImage = new TableRow.LayoutParams( (((int)screenWidth)/2)-16 , (((((int)screenWidth)/2)-15)/16)*11 );
paramsImage.setMargins(10,10,0,0);
img.setLayoutParams(paramsImage);
img.setBackgroundColor(Color.parseColor("#FF000000"));
try{
img.setImageBitmap((Bitmap) arg[0]);
}catch(Exception e){
Toast.makeText(Profile.this,"Cannot put Bitmap into ImageView",Toast.LENGTH_LONG).show();
}
img.setVisibility(View.VISIBLE);
img.setOnClickListener(new ImageListener((Integer)arg[1])); //here I passing index to onClickListener
tr.addView(img);
if ( numberOfPhotos==1 ){
try{
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}catch(Exception e){
e.printStackTrace();
Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
}
tr = new TableRow(Profile.this);
tr.setLayoutParams(lp);
numberOfPhotos--;
}
else {
numberOfPhotos++;
}
}
#Override
protected void onPostExecute(Void arg){
pb.setVisibility(View.GONE);
userPhotos.setText("uploaded: "+allUserPhotoBitmaps.size()+" photos");
if ( numberOfPhotos==1 ){
try{
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}catch(Exception e){
e.printStackTrace();
Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
}
tr = new TableRow(Profile.this);
tr.setLayoutParams(lp);
}
}
In my device ( API > 15 ) everything works great, but in API 10 it crashes the app... I you want , I can provide also OnClickListener or some othere methods...
Yes, here ... How I download pictures :
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
double width;
double height;
width = (screenWidth)/myBitmap.getRowBytes();
if ( myBitmap.getWidth() > myBitmap.getHeight() ){
Log.w("size","landscape");
height = ((myBitmap.getRowBytes()*width)/16)*11;
width = (height/11)*16;
}
else {
Log.w("size","protrait");
height = ((myBitmap.getRowBytes()*width)/11)*16;
width = (height/16)*11;
}
Bitmap bitmap = Bitmap.createScaledBitmap(myBitmap, (int)width, (int)height, true);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Profile.this, "Error parsing image to bitmap", Toast.LENGTH_LONG).show();
return null;
}
}
Any help ?
call new loadPhotos().execute(""+USER._id,"date","DESC"); in onCreate and Use Asynctask and try to avoid load in main thread. Your application crash one of the main reason may be if you are calling the methode in main thread.
Ex:
String zoomouturl = "your url";
new ImageDownload().execute(zoomouturl);
Try
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(zoomouturl, bmOptions);
return zoomouturl;
}
protected void onPostExecute(String imageUrl) {
if (!imageUrl.equals("")) {
Constants._image.setImageBitmap(bm);
} else {
Toast.makeText(this,
"not found proper bitmap.. ", Toast.LENGTH_LONG)
.show();
}
}
}
and
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
I'm having some troubles displaying an image I am fetching from a URL into an ImageView. With the code I have at the moment, I am getting absolutely nothing. Is there a problem with this code?
Drawable img = image.LoadImageFromWeb(icon);
imageView.setImageDrawable(img);
public static Drawable LoadImageFromWeb(String iconId) {
try {
String url = "http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId + ".png";
InputStream is = (InputStream) new URL(url).getContent();
Drawable icon = Drawable.createFromStream(is, "src name");
return icon;
} catch (Exception e) {
return null;
}
}
try this function
private void downloadImage()
{
Bitmap bitmap = null;
try {
URL urlImage = new
URL("http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId +
".png");
HttpURLConnection connection = (HttpURLConnection)
urlImage.openConnection();
InputStream inputStream = connection.getInputStream();
//****bitmap is your image*****
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and use asyncTask to wait until downloading the image like this
private class Asyn_SaveData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//get the random string from prefs
if (context != null)
downloadImage();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//do what you want after the image downloaded
}
}
Note: AsyncTask must be subClassed, and after the doInBackground finish its job it calls automatically the onPostExecute
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Image not showing on image view
How to show image in android while downloading it from a server
Please can anyone share me code regarding this
Drawable drawable = LoadImage(ImageURL);
PhotoImageView.setImageDrawable(drawable);
//PhotoImageView is the ImageView in which you want to load your image from server
public Drawable LoadImage(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e)
{
System.out.println("Exc=" + e);
return null;
}
}
Please Use below code for get image from url and display into imageview.
public class image extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("http://www.gophoto.it/view.php?i=http://1.bp.blogspot.com/-2LTvCCufBKc/T3L3KgcTj2I/AAAAAAAABbQ/Ki60e1LU9sE/s1600/Sachin%2BTendulkar.png");
RelativeLayout mRlayout1 = (RelativeLayout) findViewById(R.id.mRlayout1);
Drawable d=new BitmapDrawable(bitmap);
mRlayoutLogin.setBackgroundDrawable(d);
}
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;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
Usually you show spinning ProgressBar while downloading using AsycTask :
public class Downloader extends AsyncTask<String,Integer,Bitmap> {
#Override
protected void onPreExecute() {
// show spinning progress bar
}
#Override
protected Bitmap doInBackground(String... arg0) {
// download the image
return null;
}
#Override
protected void onPostExecute(Bitmap downloadedImage) {
// hide spinning progress bar
// show downloaded image
}
}
Try this it might help you.
class DownloadImage extends AsyncTask<Void, Void, Void> {
private ProgressDialog bar;
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
bar.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
bar = new ProgressDialog(context);
bar.setIndeterminate(true);
bar.setTitle(context.getString(R.string.app_name));
bar.setMessage(context.getString(R.string.please_wait));
bar.show();
}
#Override
protected Void doInBackground(Void... arg0) {
downloadImage();
return null;
}
void downloadImage() {
//Put the logic for download image from url
}
}
or Please check here.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android image view from url
I am trying to fetch the image from url and load in imageView, but I cannot encode the url string, please let me know how to encode this.
Please find the code & url used for your reference.
URL: http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG
Code
String link=URLEncoder.encode(urlStr);
bitmap=loadBitmap(link);
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
}
return bitmap;
}
Use this Code it will fetch the image from server
String URL = "http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG";
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;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
final String msg = e1.getMessage();
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_SHORT).show();
}
});
}
return bitmap;
}
FYI, URLEncoder.encode(String) has been deprecated.
Reference:
http://developer.android.com/reference/java/net/URLEncoder.html
You can encode the url as below:
String URL = "http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG";
String encodeUrl=URLEncoder.encode(URL, "utf-8");
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
final String msg = e1.getMessage();
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_SHORT).show();
}
});
}
return bitmap;
}
I have create example for How to display image from URL. Use that example it works for me and i also check it by replace you image url.
Please Use below code for download and display image into imageview.
public class MainActivity extends Activity {
ImageView my_img;
Bitmap mybitmap;
ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView mImgView1 = (ImageView) findViewById(R.id.mImgView1);
DownloadImageFromURL mDisImgFromUrl = new DownloadImageFromURL(mImgView1);
mDisImgFromUrl.execute("http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG");
}
private class DownloadImageFromURL extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Loading...");
pd.show();
}
public DownloadImageFromURL(ImageView bmImage) {
this.bmImage = bmImage;
}
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) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
pd.dismiss();
}
}
}
I have a problem to display this image in my internet.
I have no idea how to make it work.
I am new to android.
The problem is that part ...
imView = (ImageView) findViewById(R.id.imageView1);
imView.setImageBitmap(bm); //error
Thank you.
my code
public class CarregaImagem extends AsyncTask<String, Void, String>{
String imageUrl = "http://www.cuboweb.com.br/android/images/logoconsulfarma.png";
private ProgressDialog progress;
private Activity activity;
Bitmap bmImg;
public CarregaImagem(Activity activity){
this.activity = activity;
}
protected void onPreExecute() {
progress = new ProgressDialog(activity);
progress.setTitle("Aguarde...");
progress.setMessage("Carregando...");
progress.show();
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
URL aURL = new URL(imageUrl);
final URLConnection conn = aURL.openConnection();
conn.connect();
final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
final Bitmap bm = BitmapFactory.decodeStream(bis);
BitmapFactory.decodeStream(new URL(imageUrl).openConnection().getInputStream());
bis.close();
} catch (IOException e) {
imageUrl = "";
} catch(Exception f){
imageUrl = "";
}
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
if(!imageUrl.equals("")){
imView = (ImageView) findViewById(R.id.imageView1);
imView.setImageBitmap(bm); //error
} else{
Toast.makeText(activity, "Não foi possível obter resultados", Toast.LENGTH_LONG).show();
}
progress.dismiss();
}
}
You create a bitmap in doInBackground that you never use.
Return instead the bitmap and use it in onPostExecute.
Try below code to download image from web and display in imageview.
public class MainActivity extends Activity {
ImageView mImgView1;
static Bitmap bm;
ProgressDialog pd;
String imageUrl = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
pd = ProgressDialog.show(MainActivity.this, "Aguarde...",
"Carregando...");
new ImageDownload().execute("");
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
mImgView1.setImageBitmap(bm);
} else {
Toast.makeText(MainActivity.this,
"Não foi possível obter resultados", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
}
hey i faced the same problem for showing image from url, this link was very useful. also u can refer to stackoverflow discussion
Apparently android 3 onwards network connectivity is strict hence network connection fails
Cheers!