Data Fetching in Android

This is a sample activity which shows How to get text files from the web.








public class firstpage extends Activity {

private class PhotoToLoad
{
   public String url;
   public TextView view;
   public PhotoToLoad(String u, TextView i){
       url=u;
       view=i;
   }
}

class PhotosLoader implements Runnable {
   PhotoToLoad photoToLoad;
   PhotosLoader(PhotoToLoad photoToLoad){
       this.photoToLoad=photoToLoad;
   }
   @Override
   public void run() {
     
       String bmp=getBitmap(photoToLoad.url);
         BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
       Activity a=(Activity)photoToLoad.view.getContext();
       a.runOnUiThread(bd);
         
   }
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
   String bitmap;
   PhotoToLoad photoToLoad;
   public BitmapDisplayer(String b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
   public void run()
   {            
       if(bitmap!=null)
           photoToLoad.view.setText(bitmap);
       else
           photoToLoad.view.setText("nothingto to show");         
       }
}

ExecutorService executorService;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.neww);    
     
        //=====================================
        // file url
        String dosya_url = "http://www.w3.org/2005/Atom";
     
        // Imageview to show
        TextView textview = (TextView) findViewById(R.id.text1);
     
        PhotoToLoad p = new PhotoToLoad(dosya_url,textview);      
        PhotosLoader pl = new PhotosLoader(p);    
        executorService=Executors.newFixedThreadPool(5);
        executorService.submit(pl);        
    }
@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;
}

private String getBitmap(String url)
{
   //File f=fileCache.getFile(url);
   //from web
   try {
       URL Url = new URL(url);
       HttpURLConnection conn = (HttpURLConnection)Url.openConnection();
       conn.setConnectTimeout(30000);
       conn.setReadTimeout(30000);
       conn.setInstanceFollowRedirects(true);
       InputStream is=conn.getInputStream();

       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);
     
       StringBuilder sb = new StringBuilder();
     
       String read = br.readLine();      
       while(read != null) {
        sb.append(read);
        read = br.readLine();
       }
                 
       return sb.toString();
   } catch (Exception ex){
      ex.printStackTrace();
      return null;
   }
}

}

Yorumlar

Popüler Yayınlar