I am trying to download an image from the internet. Right now the app downloads only part of the image, but then it stops. I am using AsyncTask. Any suggestions on what to do?
The error I get is:
android.os.NetworkOnMainThreadException
at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:74)
W/System.err: at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:30)
This is the code I have:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View view){
DownloadAsyncTask task = new DownloadAsyncTask();
task.execute(new String[] {"http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg" });
}
private class DownloadAsyncTask extends AsyncTask<String, Void, String> {
Bitmap bitmap = null;
InputStream in = null;
#Override
protected String doInBackground(String... urls){
int response = -1;
URL url;
try {
url = new URL("http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg");
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
System.out.println("This is wrong");
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();
return "success";
}
}
catch (IOException e) {
System.out.println("IOException");
}
return "Download failed";
}
#Override
protected void onPostExecute(String result) {
//try {
bitmap = BitmapFactory.decodeStream(in);
/* in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
ImageView img = (ImageView) findViewById(R.id.image);
img.setImageBitmap(bitmap);
}
}
}
try this if you dont want to use third party library
new DownloadImage(Imageview).execute(YourUrl);
Create a AsyncTask Class
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) 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.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Related
i am trying to fetch an immage from url and setting it into a imageview
the image is small in size and i m using asynctask.
here is the main activity code.
i have tried multiple code from diff site but nothing seems to work.
plz don't suggest volly library.
package com.example.jsonimage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
Thread t;
Bitmap bitmap;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView)findViewById(R.id.imageView1);
//runthread();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class loadimage extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://wptrafficanalyzer.in//p//demo1//india.png");
InputStream is=url.openStream();
bitmap= BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//HttpURLConnection huc =(HttpURLConnection)url.openConnection();
//huc.connect();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
iv.setImageBitmap(bitmap);
}
}
}
You are not calling the Async task. On your MainActivity try:
new loadimage().execute();
Also you can use this function to get a bitmap from an URL if yours isn't working:
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;
}
}
guys. I have this code:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class MyPicGetTask extends AsyncTask<URL , Void, Bitmap>{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
#Override
protected Bitmap doInBackground(URL... urls) {
// TODO Auto-generated method stub
URL url = urls[0];
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return bmp;
}
}
it fails, but if i use AsyncTask and describe this class as inner in my activity - it's ok . I can not say the reason because i can not debug, i can see that debug tab opens when it fails but it is not informative for me. Any ideas? Sorry for my noob question
that's my Activity:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class PicActivity extends Activity implements OnClickListener{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
private URL url;
//"http://192.168.0.30/03.jpg";
/*
private class getPicTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... s) {
// TODO Auto-generated method stub
try {
url = new URL("http://192.168.0.93/image.php");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return null;
}
};
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
///////////
try {
url = new URL("http://192.168.0.30/03.jpg");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyPicGetTask().execute(url);
image.setImageBitmap(bmp);
}
});
////////////////
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pic, menu);
////////////////
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("httpProgress", "Onclick()");
}
}
Add Log.d() code to doInBackground(...) to print out all exceptions that occur. That should tell you what's going wrong, e.g.
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (Exception e) {
Log.d("Async","EXCEPTION",e);
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
Log.d("Close","EXCEPTION",e);
}
}
When the MyPicGetTask is an inner class it has access to the bmp field. When you pulled it out of your activity it lost access to the bmp class field.
I would suggest reading Google's documentation and following their examples for AsyncTasks.
The bitmap you return from doInBackground should then be used to update your UI in onPostExecute.
protected void onPostExecute(Bitmap bitmap) {
image.setImageBitmap(bitmap);
}
Your asyncTask subclass needs access to image in order to update the UI, so having it as a inner class is one way to make sure it can do this.
Your AsyncTask if you're using it as a public class outside the activity in which you are calling it needs to recieve the context of that activity. There are a number of posts here, here and here that explain how to set this up.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loading remote images
I am developing an application where I have a list in which each row has an image,
this image is loaded from a web URL.
below is my code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/list_row_img"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<TextView
android:id="#+id/list_row_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
and this is the activity code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img= (ImageView) findViewById(R.id.list_row_img);
Bitmap bm = null;
try {
URL aURL = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
img.setImageBitmap(bm);
bis.close();
is.close();
} catch (Exception e) {
Log.v("EXCEPTION", "Error getting bitmap", e);
}
}
when I run i get nothing on the device. only a gray screen and no exception happens.
note that i added this permission in the manifest file
<uses-permission android:name="android.permission.INTERNET" />
can anyone help me please ?
try this
you can exeecute it by
new DownloadImageTask((ImageView) im1).execute(url here);
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(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;
}
/* #Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showProgressDialog();
}*/
protected void onPostExecute(Bitmap result) {
//pDlg.dismiss();
bmImage.setImageBitmap(result);
}}
Use below code for download image from url and display image into imageview, this will solve your problem.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView mImgView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
String url = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
mImgView1.setImageBitmap(bm);
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
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;
}
}
The link for your image is invalid. Try to access it with your browser, you will find out. thats your problem.
I want to load an image from url on a button click & to show it on activity imageview.
how to do it?
I try the following code but it shows the system error like java.net.UnknownHostException Host is on resolved.
package com.v3.thread.fetchImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpException;
import org.apache.http.conn.HttpHostConnectException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainThreadActivity extends Activity {
ImageView img_downloaded;
Button btn_download;
String fileurl = "http://variable3.com/files/images/email-sig.jpg";
Bitmap bmImg;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//new MainThreadActivity().onPreExecute();
img_downloaded = (ImageView) findViewById(R.id.imageView1);
btn_download = (Button) findViewById(R.id.btnLoad);
btn_download.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
downloadfile(fileurl);
} catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void AbstractProgressTask() {
dialog = new ProgressDialog(this);
}
protected void onPreExecute() {new MainThreadActivity().onPreExecute();
this.dialog.setMessage("Loading. Please wait...");
this.dialog.show();
}
/**
* method is called after the work is done.
*
* #param success result of #doInBackground method.
*/
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {
// here is your code
return true;
}
void downloadfile(String fileurl) throws HttpException,HttpHostConnectException {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileurl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
if(length>0)
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
//img.setImageBitmap(bmImg);
}
else
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
please tell me where i hav to change
That seems like a lot of code just to show on an ImageView. Try this instead:
URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
img_downloaded.setImageBitmap(bmp);
Use the following code for that, it will help you
Drawable drawable = LoadImageFromWebOperations(backImgUrl);
bagImgBtn.setBackgroundDrawable(drawable);
private Drawable LoadImageFromWebOperations(String url) {
// TODO Auto-generated method stub
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
if (LogD) {
Log.d(TAG, e.toString());
e.printStackTrace();
}
return null;
}
}
Create a new onClick method called downloadButton.
public void downloadButton(View view){
Log.i("Button Status", "Button Pressed");
downloadImage imagedownload = new downloadImage();
Bitmap image;
try {
image = imagedownload.execute("Paste URL address of an image").get();
imageView.setImageBitmap(image);
}catch (Exception e){
e.printStackTrace();
}
}
Create a class called downloadImage which extends AysncTask.
public class downloadImage extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
Just call the following method on Button Click:
Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException
{
return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
}
where url is the url to pass and src_name is any String(say "src")
Hope this will help you
I want to load an image from url on a button click & to show it on activity imageview
You have to do something like below within onPageFinished:
public void onPageFinished (WebView view, String url) {
wv.loadUrl(javascript);
view.getSettings().setLoadsImagesAutomatically(true);
wv.setVisibility(View.VISIBLE);
}
Hi I am making a app that fetches a xml file and displays the results with a button labeled get it. I need help with when the button is clicked it will take the .pkg file url in the xml file and download it with some sort of progress reporting. Any help would be awesome thanks in advance. Here is what I have so far it has a error in the download code I tried maybe someone can fix this for me. I am stumped also the links are to .pkg files
package com.mypackagename;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.util.Log;
public class MainActivity extends ListActivity {
String XML_URL = "http://www.mysite.com/book.xml";
private DocumentBuilder docBuilder;
private Document doc;
private DocumentBuilderFactory docBuilderFactory;
private String bookImageUrl;
private int nodeListbooksLength;
private String bookId;
private String bookUrl;
private String bookDescription;
private String bookTitle;
ButtonListMenuAdapter notes;
ArrayList<Book> list;
TextView tv_title;
ImageView iv_logo;
private String Title;
Drawable booksImagesList[];
/** Called when the activity is first created. 1 */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv_title = (TextView) findViewById(R.id.TextView01);
iv_logo = (ImageView) findViewById(R.id.ImageView01);
list = new ArrayList<Book>();
parseXML();
notes = new ButtonListMenuAdapter(
this,
R.layout.book_row,
list );
setListAdapter( notes );
}
private void parseXML()
{
try{
Log.d("MainActivity", "Connecting Server");
InputStream inStream =openHttpConnection(XML_URL);
Log.d("MainActivity", "Fetching Data Completed");
if(inStream!=null){
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setCoalescing(true);
docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
doc = docBuilder.parse(inStream);
NodeList nodeListbookTitle = doc.getDocumentElement().getElementsByTagName("Title1");
if(nodeListbookTitle.getLength()>0){
Element elementbooktitile = (Element) nodeListbookTitle.item(0);
NodeList nodeListElementbooktitle = elementbooktitile.getChildNodes();
if(nodeListElementbooktitle.getLength()>0)
{
Title = ((Node) nodeListElementbooktitle.item(0)).getNodeValue();
Log.d("MainActivity", "Title:"+Title);
tv_title.setText(Title);
}
}
NodeList nodeListbookBanner = doc.getDocumentElement().getElementsByTagName("logo");
if(nodeListbookBanner.getLength()>0){
Element elementTeamBanner = (Element) nodeListbookBanner.item(0);
NodeList nodeListElementTeamBanner = elementTeamBanner.getChildNodes();
if(nodeListElementTeamBanner.getLength()>0)
{
bookImageUrl = ((Node) nodeListElementTeamBanner.item(0)).getNodeValue();
try {
DownloadFilesTask d = new DownloadFilesTask();
d.execute(new URL(bookImageUrl));
d.sendObjectImageView(iv_logo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ERROR getView", "EX::"+e);
}
Log.d("MainActivity", "bookImageUrl:"+bookImageUrl);
Log.d("MainActivity", "");
}
}
NodeList nodeListbook = doc.getDocumentElement().getElementsByTagName("Book");
Log.d("MainActivity","nodeListbook Length--"+nodeListbook.getLength());
nodeListbooksLength=nodeListbook.getLength();
booksImagesList = new Drawable[nodeListbooksLength+1];
if(nodeListbooksLength>0){
for(int v=0;v<nodeListbooksLength;v++){
Node nodebook = nodeListbook.item(v);
if (nodebook.getNodeType() == Node.ELEMENT_NODE){
Element elementbookResult = (Element) nodebook;
bookId=elementbookResult.getAttribute("bid");
Log.d("MainActivity","----in bookId- ->"+v+" "+bookId);
bookImageUrl=elementbookResult.getAttribute("bimg");
Log.d("MainActivity","--bookImageUrl--->"+bookImageUrl);
bookTitle=elementbookResult.getAttribute("bte");
Log.d("MainActivity","--bookTitle--->"+bookTitle);
bookDescription=elementbookResult.getAttribute("bsd");
Log.d("MainActivity","--bookDescription--->"+bookDescription);
bookUrl=elementbookResult.getAttribute("bph");
Log.d("MainActivity","--bookUrl:--->"+bookUrl);
list.add( new Book( bookId, bookImageUrl,bookTitle,bookDescription,bookUrl) );
}
}
}
}
}catch(Exception e){
Log.d("MainActivity", "parseXML:"+e);
}
}
private InputStream openHttpConnection(String urlStr) {
InputStream in = null;
int resCode = -1;
try {
Log.d("openHttpConnection", "URL:"+urlStr);
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException ("URL is not an Http URL");
}
Log.d("openHttpConnection", "httpConn:1");
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux "+"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Log.d("openHttpConnection", "setting requests and properties");
httpConn.connect();
Log.d("openHttpConnection", "Connected successfully");
resCode = httpConn.getResponseCode();
Log.d("openHttpConnection", "resCode"+resCode);
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("openHttpConnection", "Fetchinf data done");
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d("openHttpConnection", "1"+e);
} catch (IOException e) {
e.printStackTrace();
Log.d("openHttpConnection", ""+e);
}
return in;
}
private HttpClient httpClient;
private HttpPost httpPost;
private HttpResponse response;
private HttpContext localContext;
private String ret;
private InputStream postPage(String url, String data) {
InputStream is = null;
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
HttpEntity he = response.getEntity();
try {
InputStream inStream = he.getContent();
is = inStream;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return is;
}
class Book
{
public String getBookId() {
return bookId;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public String getBookTitle() {
return bookTitle;
}
public String getBookDescription() {
return bookDescription;
}
public String getBookUrl() {
return bookUrl;
}
private String bookId;
private String bookImageUrl;
private String bookTitle;
private String bookDescription;
private String bookUrl;
public Book(String bookId, String bookImageUrl, String bookTitle,String bookDescription, String bookUrl) {
this.bookId = bookId;
this.bookImageUrl = bookImageUrl;
this.bookTitle = bookTitle;
this.bookDescription = bookDescription;
this.bookUrl = bookUrl;
}
}
public class ButtonListMenuAdapter extends BaseAdapter {
public static final String LOG_TAG = "ButtonListAdapter";
private Context context;
private List<Book> menuList;
private int rowResID;
public ButtonListMenuAdapter(MainActivity context, int rowResID,
ArrayList<Book> menuList) {
// TODO Auto-generated constructor stub
this.context = context;
this.rowResID = rowResID;
this.menuList = menuList;
}
public int getCount() {
return menuList.size();
}
public Object getItem(int position) {
return menuList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final Book row = menuList.get(position);
LayoutInflater inflater = LayoutInflater.from( context );
View v = inflater.inflate( rowResID, parent, false );
TextView tv_title = (TextView)v.findViewById(R.id.Text_book_title);
tv_title.setText(row.getBookTitle());
TextView tv_desc = (TextView)v.findViewById(R.id.Text_Book_Desc);
tv_desc.setText(row.getBookDescription());
ImageView iv_book_img = (ImageView)v.findViewById(R.id.Image_book);
if(booksImagesList[position]==null)
{
try {
DownloadFilesTask d = new DownloadFilesTask();
d.execute(new URL(row.getBookImageUrl()));
d.sendObjectImageView(iv_book_img,position);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ERROR getView", "EX::"+e);
}
}
else
{
iv_book_img.setImageDrawable(booksImagesList[position]);
Log.d("Not","Reloaded");
}
Button b_get_book = (Button)v.findViewById(R.id.Button01);
b_get_book.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View v) {
private final String PATH = "/mnt/sdcard/"; //put the downloaded file here
public void DownloadFromUrl(String bookUrl, String fileName) { //this is the downloader method
try {
URL url = new URL("http://mysite.com/" + bookUrl); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(PATH+file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
}
});
return v;
}
}
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
ImageView iv;
int id;
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
downloadDrawable(urls[0].toString());
return totalSize;
}
public void sendObjectImageView(ImageView ivLogo) {
// TODO Auto-generated method stub
this.iv = ivLogo;
id = -1;
}
public void sendObjectImageView(ImageView iv,int id) {
// TODO Auto-generated method stub
this.iv = iv;
this.id = id;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("DownloadFilesTask", "onProgressUpdate"+progress[0]);
}
protected void onPostExecute(Long result) {
Log.d("DownloadFilesTask", "onPostExecute"+result);
if(d!=null && iv!=null)
{
iv.setImageDrawable(d);
if(id!=-1)
booksImagesList[id] = d;
}
}
private Drawable d;
public Drawable downloadDrawable(String imageUrl) {
try {
Log.d("downloadDrawable", "Starting Connection");
URL url = new URL(imageUrl);
URLConnection conn = url.openConnection();
conn.connect();
Log.d("downloadDrawable", "Connection Created Successfully");
InputStream is = conn.getInputStream();
Log.d("downloadDrawable", "InputStream created Successfully");
d = Drawable.createFromStream(is, url.toString());
Log.d("downloadDrawable", "Drawable created Successfully");
is.close();
} catch (IOException e) {
Log.d("ERROR3", "Ex::"+e);
}
return d;
}
}
}
this is a typical http connection.
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
InputStream is = urlConn.getInputStream();
final int MAX_LENGTH = 10000;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close();
String result = new String(buf, 0, total);
urlConn.disconnect();