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);