Tuesday 26 June 2012

Xml Parser in Android / Get Data from xml feed in Android



import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 


public class ReadAndPrintXMLFile{
public void read(){
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse("http://www.fundumobi.com/SMS/sms.xml");//////////(new File("book.xml"));


// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + 
doc.getDocumentElement().getNodeName());




NodeList listOfPersons = doc.getElementsByTagName("category");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);


for(int s=0; s<listOfPersons.getLength() ; s++){


Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


Element firstPersonElement = (Element)firstPersonNode;


NodeList firstNameList = firstPersonElement.getElementsByTagName("title");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " + 
((Node)textFNList.item(0)).getNodeValue().trim());


NodeList lastNameList = firstPersonElement.getElementsByTagName("path");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " + 
((Node)textLNList.item(0)).getNodeValue().trim());


}//end of if clause


}//end of for loop with s var


}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line " 
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());


}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();


}catch (Throwable t) {
t.printStackTrace ();
}


}
}

Wednesday 20 June 2012

Open Website in webview in Android Application


        WebView webview =( WebView)findViewById(R.id.webView1);
         webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("http://www.youtube.com/results?search_query=tv9+stock+market+news");

Run Specific task repeatedly after fixed time intervals


package com.test;


import java.util.Timer;
import java.util.TimerTask;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;


public class AndroidThreadActivity extends Activity {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        toCallAsynchronous();
    }
    
   


    public void toCallAsynchronous() {
        TimerTask doAsynchronousTask;
        final Handler handler = new Handler();
        Timer timer = new Timer();
       


                doAsynchronousTask = new TimerTask() {
                 int count=0;
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        handler.post(new Runnable() {
                            public void run() {


                                try {
                                 System.out.println("sdgdsfgadfgfd"+count);
                                  count++;
                                } catch (Exception e) {
                                    // TODO Auto-generated catch block




                                }


                            }
                        });


                    }


                };


                timer.schedule(doAsynchronousTask, 0,5000);//execute in every 50000 ms


            }
}

Monday 18 June 2012

Load Image From URL in ListView in android part 3

4) and Finally Create Activity for show Image on listview:-

public class Ecard extends Activity {


private Bundle ext;
private ImageButton back;
private TextView title;
private GridView grid_main;
public ListAdapter imgadp;
private AdView adView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
   getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
   ext=getIntent().getExtras();
   setContentView(R.layout.ecard);
   grid_main = (GridView)findViewById(R.id.gridView1);
   getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.header1);
        back=(ImageButton)findViewById(R.id.header_left_btn);
        //next=(ImageButton)findViewById(R.id.header_right_btn);
        title=(TextView)findViewById(R.id.header_text);
        title.setText(ext.getString("title"));
        new AddTask().execute();
        back.setOnClickListener(new OnClickListener(){


public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
       
        });
    
grid_main.setOnItemClickListener(new GridView.OnItemClickListener()
{         public void onItemClick(AdapterView<?> a, View v, int i, long l)
{          
  try
  {        
   
       Intent t = new Intent();
               t.setClass(Ecard.this,Ecardfull.class);
               Bundle b=new Bundle();
b.putString("title", "Full Wallpaper");
b.putInt("index", i);
t.putExtras(b);
                startActivity(t);


}          
catch(Exception e)
{  
e.printStackTrace();
System.out.println("Nay, cannot get the selected index");             }  
}    
});


}

class AddTask extends AsyncTask<Void,Void, Void> {


   private ProgressDialog dialog;





protected void onPreExecute() {
    dialog = new ProgressDialog(Ecard.this);
        dialog.setMessage("Retrieving data ...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
      }


   protected Void doInBackground(Void... unused) {
    ImageData.loaddata();
    imgadp=new ImageAdapter(Ecard.this,ImageData.icon,ImageData.name);
    return(null);
   }


   protected void onProgressUpdate(Void... unused) {
   // grid_main.setAdapter(imgadp);
   }


   protected void onPostExecute(Void unused) {
    dialog.dismiss();
    grid_main.setAdapter(imgadp);
   }
 }

public class ImageAdapter extends BaseAdapter{
Context mContext;
private Activity activity;
public ImageLoader imageLoader;
private LayoutInflater inflater=null;
        private ArrayList<String> text;
private ArrayList<String> urls;
//public static final int ACTIVITY_CREATE = 10;

public ImageAdapter(Activity a,ArrayList<String> ur ,ArrayList<String> tx){
activity = a;
text=tx;
urls=ur;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
// TODO Auto-generated method stub
return urls.size();
}


public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public class ViewHolder{
public ImageView image;
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

View vi=convertView;
       ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.ecardrow, null);
           holder=new ViewHolder();
       
     
           holder.image=(ImageView)vi.findViewById(R.id.imageView1);
           holder.text=(TextView)vi.findViewById(R.id.textView1);
           vi.setTag(holder);


}
else
{
holder=(ViewHolder)vi.getTag();
}

       holder.text.setText(text.get(position));
      // holder.image.setTag(urls.get(position));
       imageLoader.DisplayImage(urls.get(position), activity, holder.image);
       return vi;
}
}





}

Load Image From URL in ListView in android part 2

2) Now Create ImageData Class for store and fatch image url from webpage:-


public class ImageData {


public static ArrayList<String> icon=new ArrayList<String>();
public static ArrayList<String> fullimage=new ArrayList<String>();
public static ArrayList<String> name=new ArrayList<String>();

public static  void loaddata()
{
try {
Document doc = Jsoup.connect("http://www.fundumobi.com/RakhiSpecial/mypage.html").get();
System.out.println("jj"+doc.text());
StringTokenizer st1 = new StringTokenizer(doc.text(), "#");
int count=0;
while(st1.hasMoreTokens()){
String str=st1.nextToken();
StringTokenizer st = new StringTokenizer(str, "|");
int cont=0;
while(st.hasMoreTokens())
{
String s=st.nextToken();
System.out.println("jj"+s);
if(cont==0)
{
icon.add(s);
}
else if (cont==1)
{
fullimage.add(s);
}
else if (cont==2)
{
name.add(s);
}
cont++;
if(cont>2)
cont=0;
}


}
} catch (IOException e) {
e.printStackTrace();
}
}


}


3) Also create



public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        int buffer_size;
try {
buffer_size = is.available();

        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
        
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//1024;
    }
}


Load Image From URL in ListView in android part 1

First create ImageLoader Class which load image and save in sdcard :-




import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;


public class ImageLoader {
    
    //the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
    private HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();
    
    private File cacheDir;
    
    public ImageLoader(Context context){
        //Make the background thead low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
        
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Ganesh");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
    
    final int stub_id=R.drawable.ic_launcher;
    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {
        if(cache.containsKey(url))
            imageView.setImageBitmap(cache.get(url));
        else
        {
            queuePhoto(url, activity, imageView);
            imageView.setImageResource(stub_id);
        }    
    }
        
    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. 
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }
        System.out.println("queuesize"+photosQueue.photosToLoad.size());
        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }
    
    public Bitmap getBitmap(String url) 
    {
    try {
    System.out.println("url"+url);
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        File f=new File(cacheDir, filename);
        
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
        
        //from web
        
            Bitmap bitmap=null;
            InputStream is=new URL(url).openStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }


    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
            
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
            
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
    
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u; 
            imageView=i;
        }
    }
    
    PhotosQueue photosQueue=new PhotosQueue();
    
    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }
    
    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();
        
        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }
    
    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                System.out.println("queuesize"+photosQueue.photosToLoad.size());
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.url);
                        cache.put(photoToLoad.url, bmp);
                        Object tag=photoToLoad.imageView.getTag();
                        if(tag!=null && ((String)tag).equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }
    
    PhotosLoader photoLoaderThread=new PhotosLoader();
    
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
                imageView.setImageBitmap(bitmap);
            else
                imageView.setImageResource(stub_id);
        }
    }


    public void clearCache() {
        //clear memory cache
        cache.clear();
        
        //clear SD cache
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }


}



Read Webpage in android


URL url = new URL("http://192.168.1.12:80/select.php?table="+Table+"&count="+Count+"&row="+Rows+"&con="+Condition);
System.out.println("http://192.168.1.12:80/select.php?table="+Table+"&count="+Count+"&row="+Rows+"&con="+Condition);
HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet("http://192.168.1.12:80/select.php?table="+Table+"&count="+Count+"&row="+Rows+"&con="+Condition);
                // Get the response
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String st = client.execute(request, responseHandler);

MySql Database Connectivity in android

For Mysql database connection we have to use PHP  script on server side code:-

PHP Code:-


<?php
      
     /**
      *  IMPORTANT: Please before execution of this file run SQL.sql on your MySQL server.
      *  Example database will be made with simple table and some data
      */                 
     $table =htmlspecialchars($_GET["table"]);
$rowcount =htmlspecialchars($_GET["count"]);
$rowname= htmlspecialchars($_GET["row"]);
$condition= htmlspecialchars($_GET["con"]);
 
     // Require MySQL class file
     require_once "classes/mysql.class.php";
     
     // As explained in article, connection info is needed
     // in order to object connects server
     // Server name is in 95% cases localhost, but only if 
     // script is ran localy on server. For remote access contact your
     // host provider.
     $data["Server"] = "server name";
     // This is database user. As i used WampServer to develope this example
     // default user, set during instalation is 'root'. If you use other type of server
     // please check it's doucmentation on make new user and grant him all privileges
     $data["User"] = "user ";
     // By default, password is not set on WampServer, If you use other server,
     // please check it's doucmentation on make new user with all privileges, and custom password
     $data["Password"] = "password";
     
     // Here is MySQL object being instantated and $data array is being
     // injected into clas constructor
     $mysql = new MySQL( $data );
     // This method is used to connect onto server, and as database name is being injected throuh
     // method parameter, database will be selected if database name is valid
     $mysql -> connect("database name");
     // Simple MySQL SELECT query is being executed with this method
     // MYSQL query string is passed through parameter
//echo("SELECT ".$rowname." FROM ".$table."  ".$condition);
     $mysql -> query("SELECT ".$rowname." FROM ".$table."  ".$condition);
     $in =1;
     // This while loop, outputs all data that is fethced with query
     while( $data = $mysql -> fetchArray() ){
     for($i=0;$i<$rowcount;$i++)
 {
           echo $data[$i] . "#";
 }
 echo "||";
  
     }
     
     // Use this method to disconnect from database server
     $mysql -> disconnect();
     // You may output all errors that occured during process
     // Use of this method is adviced only during development period
     //echo $mysql -> getErrors(). "<br />";
?>
Android Code For access code in android:-



public class FatchData {


public Vector<String[]> GetSelect(String Table,String Rows,String Condition,int Count)
{
Vector<String[]> v=new Vector<String[]>();
String[] str;
StringTokenizer st1 = new StringTokenizer(GET_SELECT_DATA(Table,Rows,Condition,Count), "||");
int count=0;
try{
while(st1.hasMoreTokens()){
String str1=st1.nextToken();
str=new String[Count];
StringTokenizer st2 = new StringTokenizer(str1, "#");
// while(st1.hasMoreTokens()){
for(int i=0;i<Count;i++)
{
String str2=st2.nextToken();
System.out.println(str2);
str[i]=str2;
}
// }


}
}
catch(Exception e){}

return v;
}

public String GET_SELECT_DATA(String Table,String Rows,String Condition,int Count)
{


try{
Document doc = Jsoup.connect("http://192.168.1.12:80/select.php?table="+Table+"&count="+Count+"&row="+Rows+"&con="+Condition).get();
System.out.println("jj"+doc.text());
return doc.text();



} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}






Friday 15 June 2012

How to use Hindi or Other Font in Android


TextView text_view = new TextView(this);


 Typeface font = Typeface.createFromAsset(getAssets(), "saral.TTF");


 text_view.setTypeface(font);


 text_view.setText("हिंदी");

Monday 11 June 2012

How to open menu default in android


Here is Process for open menu default on activity. just put this code in onCreate method of activity:-
new Handler().postDelayed(new Runnable() { 
        @Override 
        public void run() { 
                openOptionsMenu(); 
        } 
}, 500); 

Friday 8 June 2012

How to execute Async task repeatedly after fixed time intervals


public void toCallAsynchronous() {
    TimerTask doAsynchronousTask;
    final Handler handler = new Handler();
    Timer timer = new Timer();


            doAsynchronousTask = new TimerTask() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    handler.post(new Runnable() {
                        public void run() {

                            try {
                              PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
//PerformBackgroundTask this class is the class that extends AsynchTask
         performBackgroundTask.execute();


                            } catch (Exception e) {
                                // TODO Auto-generated catch block


                            }

                        }
                    });

                }

            };

            timer.schedule(doAsynchronousTask, 0,50000);//execute in every 50000 ms

        }

Thursday 7 June 2012

Create Thread for do work in every 2 minute in Android

You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event.





private final static int INTERVAL = 1000 * 60 * 2; //2 minutes
Handle m_handler;


Runnable m_handlerTask = new Runnable()
{
     @Override 
     public void run() {
          doSomething();
          m_handler.postDelayed(m_handlerTask, INTERVAL);
     }
}


void startRepeatingTask()
{
    m_handlerTask.run(); 
}


void stopRepeatingTask()
{
    m_handler.removeCallback(m_handlerTask);
}

Tuesday 5 June 2012

ViewSwitcher Example in android

How to use ViewSwitcher in android for view animation

first create layout and put below code:-

<ViewSwitcher
    android:id="@+id/viewSwitcher1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
     android:inAnimation="@android:anim/slide_in_left"
 android:outAnimation="@android:anim/slide_out_right">


    <LinearLayout
        android:id="@+id/view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <TextView
android:id="@+id/text"
android:text="This is simplezdscsdc text"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
        
        </LinearLayout>


    <LinearLayout
        android:id="@+id/view2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <TextView
android:id="@+id/text"
android:text="This issdsdsds simplezdscsdc text"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
        
        </LinearLayout>


</ViewSwitcher>


Code Behind code:-



  viewSwitcher =   (ViewSwitcher)findViewById(R.id.viewSwitcher1);
   myFirstView= findViewById(R.id.view1);
   mySecondView = findViewById(R.id.view2);

for show first view use this code:-

if (viewSwitcher.getCurrentView() != myFirstView)
     viewSwitcher.showPrevious();  
for show second  view use this code:-   
  if (viewSwitcher.getCurrentView() != mySecondView)
    viewSwitcher.showNext();





Friday 1 June 2012

Download a file from URL to external Card in android


 void downloadFile(String fileUrl)
    {  
    URL myFileUrl = null;
    try
    {  
    myFileUrl = new URL(fileUrl);
    }
    catch (MalformedURLException e)
    {      
    e.printStackTrace();  
    }  
    Bitmap bmImg = null;
try {  
    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();  
    conn.setDoInput(true);  
    conn.connect();    
    int length = conn.getContentLength();
    InputStream is = conn.getInputStream();
    bmImg = BitmapFactory.decodeStream(is);
    }
      catch (IOException e)
    {      
    e.printStackTrace();  
    }  
    try {      
    String filepath=Environment.getExternalStorageDirectory().getAbsolutePath();
    FileOutputStream fos = new FileOutputStream(filepath + "/" + "abc.jpg");
    bmImg.compress(CompressFormat.JPEG, 75, fos);  
    fos.flush();    
    fos.close();
    MessageBox("Image Download Sucessfull");
    }
    catch (Exception e)
    {  
    e.printStackTrace();  
    }
    }

Set a image as Wallpaper from URL in android


void downloadFile(String fileUrl)
    {  
    URL myFileUrl = null;
    try
    {  
    myFileUrl = new URL(fileUrl);
    }
    catch (MalformedURLException e)
    {      
    e.printStackTrace();  
    }  
    Bitmap bmImg = null;
try {  
    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();  
    conn.setDoInput(true);  
    conn.connect();    
    int length = conn.getContentLength();
    InputStream is = conn.getInputStream();
    bmImg = BitmapFactory.decodeStream(is);
    }
      catch (IOException e)
    {      
    e.printStackTrace();  
    }  
    try {      
    String filepath=Environment.getExternalStorageDirectory().getAbsolutePath();
    FileOutputStream fos = new FileOutputStream(filepath + "/" + "output.jpg");
    bmImg.compress(CompressFormat.JPEG, 75, fos);  
    fos.flush();    
    fos.close();      
    Context context = this.getBaseContext();
    context.setWallpaper(bmImg);
    MessageBox("Image set as Wallpaper");
    }
    catch (Exception e)
    e.printStackTrace();  
    }
    }

Set Bitmap as Wallpaper in android


void SetWallpaper(Bitmap b)
   {  
    Bitmap bmImg = b;  
    try {      
    String filepath=Environment.getExternalStorageDirectory().getAbsolutePath();
    FileOutputStream fos = new FileOutputStream(filepath + "/" + "output.jpg");
    bmImg.compress(CompressFormat.JPEG, 75, fos);  
    fos.flush();    
    fos.close();      
    Context context = this.getBaseContext();
    context.setWallpaper(bmImg);
    MessageBox("Image set as Wallpaper");
    }
    catch (Exception e)
    {      
    e.printStackTrace();  
    }
   }