Saturday, 24 August 2013

play video from youtube


package com.example.videodemo;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends Activity {
 
 private VideoView videoViewer;
 private ProgressBar mProgressBar;
 String videoUrl ="http://podcast.20min-tv.ch/podcast/20min/199733.mp4";
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  videoViewer=(VideoView)findViewById(R.id.videoView1);
  //videoViewer.setVideoPath("/sdcard/documentariesandyou.mp4");
 

    /* Uri uri=Uri.parse(path1);
  http://www.youtube.com/watch?v=Hxy8BZGQ5Jo
  videoViewer.setVideoURI(uri); */
   
  
  mProgressBar = (ProgressBar) findViewById(R.id.Progressbar);
        mProgressBar.setProgress(0);
        mProgressBar.setMax(100);
        mProgressBar.setVisibility(View.INVISIBLE);
        
        videoViewer.setOnCompletionListener(new OnCompletionListener() {
   
   @Override
   public void onCompletion(MediaPlayer mp) {
    
    Toast.makeText(MainActivity.this, "End Video", Toast.LENGTH_LONG).show();
   }
  });

        videoViewer.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
             
                return true;
            }
        });
       new YourAsyncTask().execute();
  
 }
 
 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  
  Toast.makeText(MainActivity.this, "Pause Video", Toast.LENGTH_LONG).show();
 
 }
 
 @Override
 protected void onStop() {
  // TODO Auto-generated method stub
  super.onStop();

  Toast.makeText(MainActivity.this, "Stop Video", Toast.LENGTH_LONG).show();
 }
 
 @Override
 protected void onDestroy() {
  super.onDestroy();
  //Toast.makeText(MainActivity.this, "Destroy Video", Toast.LENGTH_LONG).show();
  /*WifiManager wifiManager = null;
  wifiManager.disconnect();*/
  
 }
 private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "https://www.youtube.com/watch?v=SyrO83x7g-E";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            try {
    progressDialog.dismiss();
       
    videoViewer.setVideoURI(Uri.parse(videoUrl));
    MediaController mc = new MediaController(MainActivity.this);
    //videoViewer.setMediaController(mc);
    videoViewer.requestFocus();
    videoViewer.start();          
    mc.show();
   } catch (Exception e) {
    
    e.printStackTrace();
   }
        }

    }

public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            Element el = doc.getDocumentElement();
            NodeList list = el.getElementsByTagName("media:content");///media:content
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

protected static String extractYoutubeId(String url) throws MalformedURLException
    {
        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }
}

Friday, 16 August 2013

create frame by frame animation in android

Find SHA key programmatically


try {
    PackageInfo info = getPackageManager().getPackageInfo(
          "com.facebook.login", PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) 
        {
           MessageDigest md = MessageDigest.getInstance("SHA");
           md.update(signature.toByteArray());
           Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    }
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}

Tuesday, 13 August 2013

copy database from /data/data folder to sdcard

 try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//com.example.usarmy//databases//usarmy_db.sqlite";
                String backupDBPath = "backdatabase.sqlite";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch (Exception e) {
         System.out.println("error in data base copy:"+e);
        }

Monday, 12 August 2013

Plist parsing


  private String getEventsFromAnPList(Activity activity,String xmlFilePath) throws XmlPullParserException, IOException
{
        
   boolean isInnnerList=false;
  StringBuffer stringBuffer = new StringBuffer();
  //Resources res = activity.getResources();
   //XmlResourceParser xpp = res.getXml(R.xml.myplist);
 File file = new File (xmlFilePath);
 FileInputStream fis = new FileInputStream(file);
 XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
 factory.setNamespaceAware(true);
 XmlPullParser xpp = factory.newPullParser();
 xpp.setInput(fis, "UTF-8");
  xpp.next();
           int eventType = xpp.getEventType();
           int flag1 = 0, flag2 = 0, flag3 = 0;
           String tagName="";
           String i_key="",i_value="";
           WordInnerLessonBean wordInnerLessonBean = null;
           while (eventType != XmlPullParser.END_DOCUMENT)
           {
               if(eventType == XmlPullParser.START_TAG)
               {
                
                tagName="<"+xpp.getName().toString()+">";
                   String mainTag = xpp.getName().toString();
                   if(mainTag.equals("dict"))
                   {
                       if(flag1==0)
                       {
                       flag1 = 1;
                       i=i+1;
                       stringBuffer.append("\n--MAIN DICTIONARY STARTS HERE---Number := "+i+"\n");
                       }
                       else
                       {
                           stringBuffer.append("\n\n------------INNER DICTIONARY STARTS HERE----------\n");
                           isInnnerList=true;
                           flag2 = 1;
                           wordInnerLessonBean = new WordInnerLessonBean();
                       }

                   }
                   
                   else if(mainTag.equals("key"))
                   {
                       flag3 = 1;
                   }
                   
                   else
                   {
                       flag3 = 2;
                   }
               }else if(eventType == XmlPullParser.END_TAG){
                   String g = xpp.getName().toString();
                   
                   if(g.equals("dict"))
                   {
                       if(flag1==1 && flag2!=1)
                       {
                          stringBuffer.append("\n\n------------MAIN DICTIONARY ENDS HERE----------\n\n\n");
                        flag1=0;
                       }
                       else
                       {   
                        //add to inner list wordInnerLessonBean;
                        wordLessonBean.setLesson(wordInnerLessonBean);
                        
                           stringBuffer.append("\n\n-----INNER DICTIONARY ENDS----------\n");
                           isInnnerList=false;
                           flag2=0;
                       }
                   }
               } else if(eventType == XmlPullParser.TEXT) {
                
                   if(flag3 == 1)
                   {
                       stringBuffer.append("\nkey:="+xpp.getText());
                       i_key=xpp.getText();
                       
                       flag3 = 0;
                   }
                   else if(flag3 == 2)
                   {
                    
                       
                       flag3 = 0;
                       //value is zero then store tag name as a value 
                       if(xpp.getText().trim().length()<=0){
                        stringBuffer.append("\nValue:="+tagName);
                        i_value = tagName;
                       }else{
                         stringBuffer.append("\nValue:="+xpp.getText());
                         i_value = xpp.getText();
                       }
                       if(i_key.equals("audioDescFile")){
                        if(i_value.equals("<string>")){
                         wordLessonBean.setAudioDescFile("");
                        }else{
                         wordLessonBean.setAudioDescFile(i_value);
                        }
                        
                       }else if(i_key.equals("captureAudio")){
                        if(i_value.equals("<true>")){
                         wordLessonBean.setCaptureAudio(true);
                        }else{
                         wordLessonBean.setCaptureAudio(false);
                        }
                        System.out.println("in adapter captureAudio"+i_value.equals("<true>"));
                       }else if(i_key.equals("desc")){
                        wordLessonBean.setDesc(i_value);
                       }else if(i_key.equals("emailOnCompletion")){
      
                       }else if(i_key.equals("lessonType")){
                        
                       }else if(i_key.equals("name")){
                           wordLessonBean.setName(i_value);
                       }else if(i_key.equals("nextWordID")){
                        
                       }else if(i_key.equals("words")){
                        
                       }
                       
                       if(isInnnerList){
                        
                        if(i_key.equals("shapeTraceImage")){
                                  if(i_value.equals("<string>")){
                              wordInnerLessonBean.setShapeTraceImage("");
                             }else{
                              wordInnerLessonBean.setShapeTraceImage(i_value);
                             }
                           }else if(i_key.equals("word")){
                            
                            if(i_value.equals("<string>")){
                             wordInnerLessonBean.setWord("");
                            }else{
                             wordInnerLessonBean.setWord(i_value);
                            }
                           }else if(i_key.equals("wordAudio")){
                            if(i_value.equals("<string>")){
                             wordInnerLessonBean.setWordAudio("");
                            }else{
                             wordInnerLessonBean.setWordAudio(i_value);
                            }
                            
                           }else if(i_key.equals("wordID")){
                            wordInnerLessonBean.setWordID(Integer.parseInt(i_value));
                           }else if(i_key.equals("wordPicture")){
                            if(i_value.equals("<string>")){
                             wordInnerLessonBean.setWordPicture("");
                            }else{
                             wordInnerLessonBean.setWordPicture(i_value);
                            }
                           
                           }else if(i_key.equals("wordText")){
                            if(i_value.equals("<string>")){
                             wordInnerLessonBean.setWordText("");
                            }else{
                             wordInnerLessonBean.setWordText(i_value);
                            }
                           }
                       }
                      // System.out.println("isInnnerList:"+isInnnerList+" i_value:"+i_value);
                   }
               }
               
                eventType = xpp.next();
             }
           stringBuffer.append("\n--- End XML ---");
           stringBuffer.append("\n--- Total Number Of Dictionaries Are ---"+i);
           
           return stringBuffer.toString();
       }

SAX parsing in android


ItemXMLHandler.java

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ItemXMLHandler extends DefaultHandler {

 Boolean currentElement = false;
 String currentValue = "";
 Bean item = null;
 private ArrayList<Bean> itemsList = new ArrayList<Bean>();

 public ArrayList<Bean> getItemsList() {
  return itemsList;
 }

 // Called when tag starts
 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {

  currentElement = true;
  currentValue = "";

  if (localName.equals("item")) {
   item = new Bean();
  }

 }

 // Called when tag closing
 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {

  currentElement = false;

  if (localName.equals("id")) {
   item.setId(currentValue);
  } else if (localName.equals("title")) {
   item.setTitle(currentValue);
  } else if (localName.equals("desc")) {
   item.setDesc(currentValue);
  } else if (localName.equals("pubDate")) {
   item.setPubDate(currentValue);
  } else if (localName.equals("link")) {
   item.setLink(currentValue);
  } else if (localName.equals("item")) {
   itemsList.add(item);
  }
 }

 // Called to get tag characters
 @Override
 public void characters(char[] ch, int start, int length)
   throws SAXException {

  if (currentElement) {
   currentValue = currentValue + new String(ch, start, length);
  }
 }

}

Bean.java



public class Bean {

 private String id;
 private String title;
 private String desc;
 private String pubDate;
 private String link;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getDesc() {
  return desc;
 }

 public void setDesc(String desc) {
  this.desc = desc;
 }

 public String getPubDate() {
  return pubDate;
 }

 public void setPubDate(String pubDate) {
  this.pubDate = pubDate;
 }

 public String getLink() {
  return link;
 }

 public void setLink(String link) {
  this.link = link;
 }

}
MainActivity.java

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
 private ProgressDialog pDialog;
 private ItemXMLHandler myXMLHandler;
 private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
    private TextView textview;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  textview =(TextView)findViewById(R.id.textView1);
 }

 public void doParsing(View v){
  
  if (isNetworkAvailable()) {
   textview.setText("Loading...Please wait...");
   new AsyncData().execute(rssFeed);
  } else {
   showToast("No Network Connection!!!");
  } 
 }
 class AsyncData extends AsyncTask<String, Void, Void> {

  @Override
  protected void onPreExecute() {
   pDialog = new ProgressDialog(MainActivity.this);
   pDialog.setTitle("Loading....");
   pDialog.setMessage("Please wait...");
   pDialog.show();
   super.onPreExecute();
  }

  @Override
  protected Void doInBackground(String... params) {

   try {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    myXMLHandler = new ItemXMLHandler();
    xr.setContentHandler(myXMLHandler);

    URL _url = new URL(params[0]);

    xr.parse(new InputSource(_url.openStream()));

   } catch (ParserConfigurationException pce) {
    Log.e("SAX XML", "sax parse error", pce);
   } catch (SAXException se) {
    Log.e("SAX XML", "sax error", se);
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;

  }

  @Override
  protected void onPostExecute(Void result) {
   super.onPostExecute(result);

   textview.setText("Done!!!");
   if (pDialog != null && pDialog.isShowing()) {
    pDialog.dismiss();
   }

   ArrayList<Bean> itemsList = myXMLHandler.getItemsList();

   if (null != itemsList && itemsList.size() != 0) {
    for (int index = 0; index < itemsList.size(); index++) {
     Bean objBean = itemsList.get(index);

     System.out.println(">>>>>>>>>>>>>>>" + index);
     System.out.println("ID :: " + objBean.getId());
     System.out.println("TITLE :: " + objBean.getTitle());
     System.out.println("DESC :: " + objBean.getDesc());
     System.out.println("PUBDATE :: " + objBean.getPubDate());
     System.out.println("LINK :: " + objBean.getLink());
    }
   }
  }
 }

 public void showToast(String msg) {
  Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
 }

 public boolean isNetworkAvailable() {
  ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  if (connectivity == null) {
   return false;
  } else {
   NetworkInfo[] info = connectivity.getAllNetworkInfo();
   if (info != null) {
    for (int i = 0; i < info.length; i++) {
     if (info[i].getState() == NetworkInfo.State.CONNECTED) {
      return true;
     }
    }
   }
  }
  return false;
 }
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.samir"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.samir.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
res/layout Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doParsing"
        android:text="Start" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>