Tuesday, May 31, 2011

splash screen

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.view.WindowManager;

public class SplashActivity extends Activity
{
    private static long SPLASHTIME = 2500;
    private static final int STOPSPLASH = 0;
    public static Activity mainApp;
    public static boolean shouldNavigate = true;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(1);
        mainApp = this;
        setContentView(R.layout.main);
        final Message msg = new Message();
        msg.what = STOPSPLASH;
        mHandler.sendMessageDelayed(msg, SPLASHTIME);

    }

    Handler mHandler = new Handler()
    {

        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
            case STOPSPLASH:

                if (shouldNavigate)
                {
                    Intent myIntent = new Intent();
                    /*myIntent.setClassName("mon.ctacts",
                            "mon.ctacts.LoginActivity");*/
                    myIntent.setClassName("com.traveldairy",
                    "com.traveldairy.AfterSplashActivity");
                   
                    startActivity(myIntent);
                    finish();
                }
                break;

            }

            super.handleMessage(msg);
        }
    };

    public void finishFromChild(Activity child)
    {
        // TODO Auto-generated method stub
        finish();
        super.finishFromChild(child);
    }
}

Xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/root"
    android:background="@drawable/stockquitybackground">

</LinearLayout>

intent

1.Intent DeviceReg = new Intent();
                DeviceReg.setClassName("com.examples",
                        "com.ui.DeviceRegActivity");

                startActivity(DeviceReg);

2. Intent serviceIntent = new Intent(
                             this, ServiceLogDetail.class);
                             startService(serviceIntent);
3.services:
Intent serviceIntent = new Intent(
                              getBaseContext(), ServiceLogDetail.class);
                              getBaseContext().startService(serviceIntent);

DashBoard Xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent" android:layout_width="fill_parent"
    android:background="@drawable/background">



    <TableLayout android:id="@+id/TableLayout01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_marginLeft="60dip" android:layout_marginTop="90dip">
        <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <Button android:layout_height="80dip" android:layout_width="80dip"
                android:id="@+id/btn_dairies" android:background="@drawable/icon"></Button>

            <Button android:layout_marginLeft="50dip"
                android:layout_height="80dip" android:layout_width="80dip"
                android:id="@+id/btn_locations" android:background="@drawable/icon"></Button>


        </TableRow>
       
   

<TableRow android:id="@+id/TableRow05" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dip"><Button android:layout_height="80dip" android:layout_width="80dip" android:id="@+id/btn_maps" android:background="@drawable/icon"></Button>
<ImageView android:id="@+id/ImageView01" android:layout_height="80dip" android:layout_width="80dip" android:layout_marginLeft="50dip" android:background="@drawable/icon"></ImageView>
</TableRow>

</TableLayout>

</RelativeLayout>

hasmap listview












 SimpleAdapter adapter;
inside on create:
String [] from=new String []{"text"};
        int [] to=new int []{R.id.TextView01};
   
    List<HashMap<String, String>> fillMaps = listForSimpleAdapter();// new
    adapter = new SimpleAdapter(this, fillMaps, R.layout.listems,
            from, to) {

        public View getView(int position, View convertView, ViewGroup parent) {

            View v = super.getView(position, convertView, parent);
            return v;
        }
    };
    reacharchlist.setAdapter(adapter);

outsidefunction:
private List<HashMap<String, String>> listForSimpleAdapter(){
       
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        for(int i=0;i<textarray.length;i++)
        {
            HashMap<String, String> map = new HashMap<String, String>();
            String text1=textarray[i];
            map.put("text", text1);
   
            fillMaps.add(map);
        }
        return fillMaps;
       
    }












--------------------------------------------------------------------------------------------------------------
/*package mon.ctacts;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.SortedMap;

import montact.shared.token.MontactToken;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.packet.VCard;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.settingpage.SettingPage;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class TravellistActivity extends Activity implements OnClickListener

{

    int i;
    // TextView location;
    // TextView adress;
    // TextView date;
    *//** Called when the activity is first created. *//*
    public String one = "1";
    public String zero = "0";
    // public String ="1";
    private static final String LOG_KEY = "TEST";

    public String Skype = "skype";
    public String Gtalk = "gtalk";
    // public String Date = "sep 27 2010";
    public String title = "title";
    public String status;
    public String Imcode;
    Button login;
    Button upload;
    Button store;
    String Dname;
    String Dimage;
    String Ddescription;
    String Ddate;
    String Dlocation;
    String Dlatitude;
    String Dlongitude;
    String ldescription;
    String limages;
    String Imagename;
    String Imagepath;

    String locimage;
    String loclocation;
    String latlat;
    String loclong;
    String locdesp,TdairyID;

    String Location = "'India Diary'";
    String Loct;
    String Alltitles;
    TextView statusText;
    Button Delete;
    Button Bk;
    private Button btnAdd;

    String[] icon = new String[] { R.drawable.tdiconn + "" };

    private ProgressDialog progressDialog;

    String stat = "Status:";
    String statContent = "Online";
    String[] logos;
    String[] logo = new String[] { R.drawable.logogtalk + "" };
    String[] Skypelogo = new String[] { R.drawable.logoskype + "" };
    String[] yahoologo = new String[] { R.drawable.logoyahoo + "" };
    ListView travellist;
    SimpleAdapter adapter;

    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.traveldiarylist);

        Delete = (Button) findViewById(R.id.Del);
        // Bk = (Button) findViewById(R.id.Backb);

        btnAdd=(Button)findViewById(R.id.btntraveldiaryadd);
        DBAdapter db = new DBAdapter(this);
        db.open();

        db.deleteAll();

        db.close();
        Delete.setOnClickListener(this);
        btnAdd.setOnClickListener(this);

        travellist = (ListView) findViewById(R.id.traveldiarylistview);
        travellist.setItemsCanFocus(false);

        String[] from = new String[] { "icon", "buddyname", "desc", "date" };
        int[] to = new int[] { R.id.locationicon, R.id.locationname,
                R.id.traveldesc, R.id.date };

        List<HashMap<String, String>> fillMaps = TraveldairyForSimpleAdapter();// new
        // ArrayList<HashMap<String,
        // String>>();

        adapter = new SimpleAdapter(this, fillMaps, R.layout.traveldiaryitems,
                from, to) {

            public View getView(int position, View convertView, ViewGroup parent) {

                View v = super.getView(position, convertView, parent);
                return v;
            }
        };
        travellist.setAdapter(adapter);
        travellist
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
                {

                    public void onItemSelected(AdapterView<?> arg0, View arg1,
                            int arg2, long arg3)
                    {
                        // for(int i=0;i<=arg2;i++ );
                        System.out
                                .println("Item clicked1 !!!!!!!!!onItemSelected");
                    }

                    public void onNothingSelected(AdapterView<?> arg0)
                    {
                        System.out
                                .println("Item clicked2 !!!!!!!onNothingSelected!!");

                       
                         * Intent travelIntent = new Intent();
                         * travelIntent.setClassName("mon.ctacts",
                         * "mon.ctacts.TraveldairyActivity");
                         * //chatIntent.putExtras(bundle);
                         * startActivity(travelIntent);
                       

                    }

                });
        travellist.setOnItemClickListener(listClick);

    }

//    protected void progress()
//    {
//        // TODO Auto-generated method stub
//
//        progressDialog = ProgressDialog.show(this, "", "Login...");
//
//        new Thread()
//        {
//            public void run()
//            {
//
//                try
//                {
//
//                    // Thread.sleep(2000);
//
//                    /*
//                     * System.out.println("onclick Del");
//                     *
//                     * Intent myIntent = new Intent();
//                     * myIntent.setClassName("mon.ctacts",
//                     * "mon.ctacts.DelTravellistActivity");
//                     *
//                     * startActivity(myIntent);
//                   
//
//                }
//
//                catch (Exception e)
//                {
//
//                }
//
//            }// run
//
//        }.start();// new thread
//
//    }// end progrss bar brakret

    private List<HashMap<String, String>> TraveldairyForSimpleAdapter() {
        // TODO Auto-generated method stub

    String token=MontactToken.getToken();
    String userid=MontactToken.getUserId();   
    String address="http://java.greymatterindia.com/montacts/web/mnt_dev.php/api/getTravelDiary?data="  +  "%7B"     +"%22NoOfRec%22"  +     "%3A"   +   "20"  +   ","   +   "%22TokenKey%22" +    "%3A"   +   "%22"+token+"%22"  +   ","  +  "%22StartRecNo%22"   +  "%3A"  +  "%221%22"  +  ","  +  "%22UsrId%22"  +  "%3A"  +  "%22"+userid+"%22"  +  ","  +  "%22EndRecNo%22"  +  "%3A"  +  "%2220%22"  +  "%7D"  ;
    //10-15 15:33:31.804: INFO/System.out(412): urlview...........http://java.greymatterindia.com/montacts/web/mnt_dev.php/api/getTravelDiary?data=%7B%22NoOfRec%22%3A20,%22TokenKey%22%3A%22ADRWYw==%22,%22StartRecNo%22%3A%221%22,%22UsrId%22%3A%22235%22,%22EndRecNo%22%3A%2220%22%7D

        System.out.println(address);
       
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
       

        try {
            // HashMap<String, String> map = new HashMap<String, String>();
            JSONObject json = montact.gmailfriends.json.montactfriends
                    .connect(address);
            //JSONObject data = json.getJSONObject("data");
            String TotalRecord = json.getString("TotalRecord");
            System.out.println(TotalRecord);
            //http://java.greymatterindia.com/montacts/web/mnt_dev.php/api/getTravelDiary?data={%22NoOfRec%22:20,%22TokenKey%22:%22ADRWYw==%22,%22StartRecNo%22:%221%22,%22UsrId%22:%22235%22,%22EndRecNo%22:%2220%22}
       
            //String rcode = json.getString("rcode");
            //System.out.println(rcode);
            //String page = json.getString("page");
            // System.out.println(page);
            // String dataobject= json.getString("data");
        //    JSONObject dataObject = json.getJSONObject("data");
            //String totalResults = dataObject.getString("totalResults");
            // System.out.println(totalResults);

            // JSONObject sucessObject = json.getJSONObject("totalPages");
            //String totalPages = dataObject.getString("totalPages");
            // System.out.println(totalPages);

           
             * String image1 = dataObject.getString("image");
             * System.out.println(image1);
           
            // JSONObject itemObject =dataObject.getJSONObject("items");
            JSONArray arrayitems = json.getJSONArray("TravelDiary");

            for (int i = 0; i < arrayitems.length(); i++) {
                System.out.println("count");

                // String status = "";

                String name = arrayitems.getJSONObject(i).getString("TrdName")
                        .toString();
                Dname = name;
                // System.out.println(name);

                String image = arrayitems.getJSONObject(i).getString(
                        "image").toString();
                Dimage = image;
                // System.out.println(image);

                String TrdId = arrayitems.getJSONObject(i).getString(
                "TrdId").toString();
                TdairyID = TrdId;
                System.out.println(TrdId);
               
               
                String description1 = arrayitems.getJSONObject(i).getString(
                        "TrdDesciption").toString();
                Ddescription = description1;
                // System.out.println(description1);

                String Date = arrayitems.getJSONObject(i).getString(
                        "TrdCreateddate").toString();
                Ddate = Date;

                 System.out.println(Ddate);
               
                HashMap<String, String> map = new HashMap<String, String>();

                map.put("icon", icon[0]);

                if (name != null) {

                    map.put("buddyname", name);
                } else {
                    map.put("buddyname", name);

                }

               
                  if (    Ddescription != null) {
                 
                  map.put("desc",     Ddescription); }
                  else { map.put("desc",     Ddescription);
                 
                  }
                 
               
                if (Date != null) {

                    map.put("date", Date);
                } else {
                    map.put("Date", Date);

                }

                fillMaps.add(map);

                // JSONObject itemObject = json.getJSONObject("items");
                // JSONObject location =
                // arrayitems.getJSONObject(i).getJSONObject("location");
                JSONArray arraylocations = arrayitems.getJSONObject(i)
                        .getJSONArray("location");

                for (int z = 0; z < arraylocations.length(); z++) {
                    // List<HashMap<String, String>> fillLocationMap = new
                    // ArrayList<HashMap<String, String>>();

                    String lname = arraylocations.getJSONObject(z).getString(
                            "Name").toString();

                    Dlocation = lname;
                    // System.out.println(lname);

                    String locationImage = arraylocations.getJSONObject(z)
                            .getString("locationImage").toString();
                    // System.out.println(locationImage);
                    limages = locationImage;

                    String lat = arraylocations.getJSONObject(z).getString(
                            "lat").toString();
                    // System.out.println(lat);
                    Dlatitude = lat;

                    String lng = arraylocations.getJSONObject(z).getString(
                            "lng").toString();
                    Dlongitude = lng;
                    // System.out.println(lng);

                    String description = arraylocations.getJSONObject(z)
                            .getString("description").toString();
                    ldescription = description;
                    // System.out.println(description);

                    JSONArray arrayimage = arraylocations.getJSONObject(z)
                            .getJSONArray("images");
                    for (int y = 0; y < arrayimage.length(); y++) {

                        String imagename = arrayimage.getJSONObject(y)
                                .getString("Name").toString();
                        Imagename = imagename;
                        // System.out.println(imagename);

                        String imagepath = arrayimage.getJSONObject(y)
                                .getString("imagepath").toString();
                        Imagepath = imagepath;

                        // System.out.println(imagepath);

                       
                          DBAdapter db = new DBAdapter(this);
                   
                   
                          db.open();
                        long id;
                    id = db.insertTitle(Dname,
                          Dimage,Ddescription,Ddate
                          ,Dlocation,Dlatitude,Dlongitude,
                          ldescription,limages,Imagename,Imagepath);
                          db.close();
                       
                       
                        // ---get all titles---
                            db.open();
                            Cursor c = db.getAllTitles();
                            if (c.moveToFirst()) {
                                do {
                                    DisplayAllTitle(c);
                                } while (c.moveToNext());
                            }
                            db.close();
                         
                         
                         
                          // Delete all database
                       
                         db.open();
                         
                          db.deleteAll();
                         
                          db.close();
                       
                    }
                    // //---get a title---

                }
            }

            DBAdapter db = new DBAdapter(this);
           
           

            db.open();
            Cursor q = db.getdistinct();
            if (q.moveToFirst())
            {
                System.out.println("dairy location found");
                do
                {
                    // DisplayDistinct(q);
                    // System.out.print("\n"+ q.getString(0)+"\n");
                    Alltitles = q.getString(0);
                    System.out.print(" \n" + Alltitles + "\n");

                    System.out.println("particulars!!!!!!");
                    Location = "'" + Alltitles + "'";
                    Cursor c = db.getParticulardai(Location);
                    if (c.moveToFirst()) {
                        do {
                            locimage = c.getString(8);
                            loclocation = c.getString(4);
                            latlat = c.getString(5);
                            loclong = c.getString(6);
                            locdesp = c.getString(7);

                            System.out.println(locimage);
                            System.out.println(loclocation);
                            System.out.println(latlat);
                            System.out.println(loclong);
                            System.out.println(locdesp);
                            ;
                        } while (c.moveToNext());
                    }
                } while (q.moveToNext());

            } else {

                System.out.println(" no dairylocation found");
            }

            db.close();
           
           
            }
        } catch (JSONException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();
        }

        System.out.println("Size of fillMaps>>>>>>>>>>" + fillMaps.size());
        // adapter.notifyDataSetChanged();
        return fillMaps;

    }


    private void DisplayAllTitle(Cursor c)
    { // TODO Auto-generated method
        // * stub
        *//**
         * Toast.makeText( this, "id: " + c.getString(0) + "\n" + "DAIRYNAME: "
         * + c.getString(1) + "\n" + "DAIRY_IMAGE: " + c.getString(2) + "\n" +
         * "DAIRY_DISCRIPTION:  " + c.getString(3)+ "\n" + "DATE:  " +
         * c.getString(4)+ "\n" + "LOCATION_TITLE:  " + c.getString(5)+ "\n" +
         * "LATITUTE:  " + c.getString(6)+ "\n" + "LONG:  " + c.getString(7)+
         * "\n" + "LOCATION_DESCRIPTION:  " + c.getString(8)+ "\n" +
         * "LOCATON_IMAGE:  " + c.getString(9)+ "\n" + "IMAGE_NAME:  " +
         * c.getString(10)+ "\n" + "IMAGEPATH:  " + c.getString(11),
         * Toast.LENGTH_LONG) .show();
         *//*

        System.out.println("id: " + c.getString(0) + "\n" + "DAIRYNAME: "
                + c.getString(1) + "\n" + "DAIRY_IMAGE: " + c.getString(2)
                + "\n" + "DAIRY_DISCRIPTION:  " + c.getString(3) + "\n"
                + "DATE:  " + c.getString(4) + "\n" + "LOCATION_TITLE:  "
                + c.getString(5) + "\n" + "LATITUTE:  " + c.getString(6) + "\n"
                + "LONG:  " + c.getString(7) + "\n" + "LOCATION_DESCRIPTION:  "
                + c.getString(8) + "\n" + "LOCATON_IMAGE:  " + c.getString(9)
                + "\n" + "IMAGE_NAME:  " + c.getString(10) + "\n"
                + "IMAGEPATH:  " + c.getString(11));
        // Alltitles=c.getString(1);
        // System.out.println(Alltitles);

    }

    AdapterView.OnItemClickListener listClick = new OnItemClickListener()
    {

        @SuppressWarnings("unchecked")
        public void onItemClick(AdapterView parent, View view, int position,long id)
        {
            HashMap<String, String> temp = (HashMap<String, String>) parent
                    .getItemAtPosition(position);

            String username = temp.get("buddyname").toString();
            // Bundle bun=new Bundle();
            // bun.putParcelableArrayList(key, value);

            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!");
            System.out.println(username);
            Bundle bundle = new Bundle();
            bundle.putString("buddyName", username);

            Intent locIntent = new Intent();
            // chatIntent.setClassName("mon.ctacts", "mon.ctacts.StartChat");
            locIntent.setClassName("mon.ctacts",
                    "mon.ctacts.TraveldairyActivity");
            locIntent.putExtras(bundle);
            startActivity(locIntent);

        }

    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle item selection
        switch (item.getItemId())
        {
        case R.id.logout:

            return true;
        case R.id.setting:
            Intent intent = new Intent(TravellistActivity.this,
                    SettingPage.class);
            startActivity(intent);

            return true;
        case R.id.exit:

            return true;
        default:
            return super.onOptionsItemSelected(item);
        }

    }

    public void onClick(View v)
    {
        // TODO Auto-generated method stub

        if ((Button) v == Delete)
        {
            //progress();
            progressDialog = ProgressDialog.show(this, "", "Loading...");

            new Thread()
            {
                public void run()
                {

                    try
                    {

                        Thread.sleep(2000);

                        System.out.println("onclick Del");
                        progressDialog.dismiss();
                        Intent myIntent = new Intent();
                        myIntent.setClassName("mon.ctacts",
                                "mon.ctacts.DelTravellistActivity");

                        startActivity(myIntent);
                       

                    }

                    catch (Exception e)
                    {

                    }

                }// run

            }.start();// new thread
        }
        if((Button)v==btnAdd)
        {
           
            Intent myIntent = new Intent();
            myIntent.setClassName("mon.ctacts",
                    "mon.ctacts.TravelDiaryNewActivity");

            startActivity(myIntent);
        }

    }

   
     * @Override public void onClick(View v) { // TODO Auto-generated method
     * stub if ((Button) v == editBtn) {
     * System.out.println("Item clicked4 !!!!!!!!!onItemSelected");
     *
     * new Thread() { public void run() {
     *
     * try {
     *
     * Thread.sleep(2000);
     *
     * Intent Editintent = new Intent(); Editintent.setClassName("mon.ctacts",
     * "mon.ctacts.mnlogin");
     *
     * startActivity(Editintent); // progressDialog.dismiss();
     *
     * }
     *
     * catch (Exception e) {
     *
     * }
     *
     * }// run
     *
     * }.start();// new thread
     *
     * }// end progrss bar brakret
     *
     * }
   
   
     * public String download(String url) { URL ImageUrl = null ; try { ImageUrl
     * = new URL(url); URLConnection urlConnection = ImageUrl.openConnection();
     *
     * File imageFile = new File("/sdcard/icon.jpg");
     *
     * InputStream is = urlConnection.getInputStream(); BufferedInputStream bis
     * = new BufferedInputStream(is);
     *
     * FileOutputStream fos = new FileOutputStream(imageFile); int tempByte;
     * StringBuffer sb = new StringBuffer();
     *
     * while ((tempByte = bis.read()) != -1) { sb.append((char) tempByte);
     * fos.write(tempByte);
     *
     * }
     *
     * this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
     * .parse("file://" + Environment.getExternalStorageDirectory())));
     *
     * } catch (MalformedURLException e) { // TODO Auto-generated catch block
     * e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated
     * catch block e.printStackTrace();
     *
     * }
     *
     * return ImageUrl.getPath(); }
   
    // 375011049
}
*/

Monday, May 30, 2011

Android XML Parsing Tutorial

URL:http://www.blogger.com/post-create.g?blogID=7007841774175555662

 

Android XML Parsing Tutorial - Using SAXParser

Android XML Parsing Tutorial - Using DOMParser
Here we are going to see about how to parse a XML using SAX Parser.
we are going to parse XML from net not from local file.

Files Used:-
XMLParsingExample.java ( Main Activity )
SitesList.java ( Getter & Setter Method )
MyXMLHandler.java ( XML Handling )
example.xml ( XML file from net )

The output will looks similar to



example.xml ( http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml )
[sourcecode language="xml"]
<maintag>
<item>
<name>AndroidPeople</name>
<website category="android">www.androidpeople.com</website>
</item>
<item>
<name>iPhoneAppDeveloper</name>
<website category="iPhone">www.iphone-app-developer.com</website>
</item>
</maintag>
[/sourcecode]

If tag names are different, then we can use string to set & get the value. But here item,name & website tags are repeating 2 times.
So we can use ArrayList to store & get the data.

XMLParsingExample.java

This is main activity class. when App. starts this file will be called first.
This file contains how to use SAX Parser to handle XML tags.

[sourcecode language="java"]
package com.androidpeople.xml.parsing;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getName().size()];
category = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Website = "+sitesList.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+sitesList.getCategory().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}
[/sourcecode]

MyXMLHandler.java

This file is used to handle the XML tags. So we need to extends with DefaultHandler.
we need to override startElement, endElement & characters method .
startElemnt method called when the tag starts.
endElemnt method called when the tag ends
characres method to get characters inside tag.

[sourcecode language="java"]
package com.androidpeople.xml.parsing;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("maintag"))
{
/** Start */
sitesList = new SitesList();
} else if (localName.equals("website")) {
/** Get attribute value */
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}
}
/** Called when tag closing ( ex:- <name>AndroidPeople</name>
* -- </name> )*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("name"))
sitesList.setName(currentValue);
else if (localName.equalsIgnoreCase("website"))
sitesList.setWebsite(currentValue);
}
/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
* -- to get AndroidPeople Character ) */
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
[/sourcecode]

SitesList.java

Contains Getter & Setter Method

[sourcecode language="java"]
package com.androidpeople.xml.parsing;
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> website = new ArrayList<String>();
private ArrayList<String> category = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
public ArrayList<String> getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website.add(website);
}
public ArrayList<String> getCategory() {
return category;
}
public void setCategory(String category) {
this.category.add(category);
}
}
[/sourcecode]

That's it. :)

You can download the full source code from here

Android XML Parsing Tutorial - Using DOMParser

WPF MediaElement Introduction

WPF MediaElement Introduction

URL:http://blog.nelsondev.net/?m=201007

Tuesday, July 13th, 2010
WPF supports a powerful class for adding video and audio to controls and surfaces – the MediaElement.
I made a little demo program to show a few of its features. It’s still a progress bar, filename display and a whole bunch of other stuff short of a real media player.
The XAML . . .
    <Grid>
        <Button Height="32" Margin="54,32,0,0" Name="button_Open" 
                VerticalAlignment="Top" Click="button_Open_Click" 
                HorizontalAlignment="Left" Width="143">Open File</Button>
        <Button Margin="54,89,0,0" Name="button_Play" Height="32" 
                VerticalAlignment="Top" HorizontalAlignment="Left" Width="76"
                Click="button_Play_Click">Play</Button>
        <Button Margin="54,146,0,0" Name="button_Pause" HorizontalAlignment="Left"
                Width="76" Click="button_Pause_Click" Height="32" 
                VerticalAlignment="Top">Pause</Button>
        <Button Height="32" Margin="54,0,0,78" Name="button_Stop" 
                VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="76"
                Click="button_Stop_Click">Stop</Button>
        <Button Height="32" HorizontalAlignment="Right" Margin="0,89,109,0" 
                Name="button_TimePlay" VerticalAlignment="Top" Width="89" 
                Click="button_TimePlay_Click">Time Play</Button>
        <Slider Height="32" Margin="160,0,109,22" Name="slider1" 
                VerticalAlignment="Bottom" ValueChanged="slider1_ValueChanged"
                Ticks="0   0.5  1.0 " TickPlacement="BottomRight" Value="0.5"
                Minimum="0" Maximum="1" />
        <Label Height="28" HorizontalAlignment="Left" Margin="53,0,0,26"
               Name="label1" VerticalAlignment="Bottom" 
               Width="91">Volume</Label>
    </Grid>
produces this …
MediaElement demo program
The MediaElement essentially has two modes – an indepenedent mode so you can control playing, stopping, etc, “manually”, and a “clock” mode so you can put it under the control of .Net’s timeline engine.
In the constructor, we set behavior to manual to be able to Stop, Play, etc . . . The file-open, and play, pause, stop, and volume slider functionality are bare-bones in this example, and pretty self-explanatory . . .
namespace WpfMP3
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        MediaElement _MyMediaElement;
        String _sMP3PathName;
        public Window1()
        {
            _sMP3PathName = "";
            _MyMediaElement = new MediaElement();
            _MyMediaElement.LoadedBehavior = MediaState.Manual;
            _MyMediaElement.UnloadedBehavior = MediaState.Manual;
            InitializeComponent();
        }

        private void button_Open_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog FileChooser = new OpenFileDialog();
            if (FileChooser.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            _sMP3PathName = FileChooser.FileName;
            _MyMediaElement.Source = new Uri(_sMP3PathName);
        }

        private void button_Play_Click(object sender, RoutedEventArgs e)
        {
            _MyMediaElement.Play();
        }

        private void button_Pause_Click(object sender, RoutedEventArgs e)
        {
            _MyMediaElement.Pause();
        }

        private void button_Stop_Click(object sender, RoutedEventArgs e)
        {
            _MyMediaElement.Stop();
        }

        private void slider1_ValueChanged(object sender,
                 RoutedPropertyChangedEventArgs<double> e)
        {
            double value = e.NewValue;
            _MyMediaElement.Volume = value;
        }
Instead of having the MediaElement strictly under manual control, we can use a MediaTimeLine, which is a media analogue of .Net’s animation timeline. In this example we use a literal to set it to play 5 seconds and then stop . . .
        private void button_TimePlay_Click(object sender, RoutedEventArgs e)
        {
            MediaTimeline myTimeLine = new MediaTimeline();
            
            myTimeLine.Source = _MyMediaElement.Source;
            myTimeLine.Duration = (TimeSpan.FromMilliseconds(5000));
            MediaClock mc = myTimeLine.CreateClock();
            _MyMediaElement.Clock = mc;
            _MyMediaElement.Play();
         }
    }
}

Sunday, May 29, 2011

test to speech with text finish listner

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Locale;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.widget.Toast;

public class SpeakerService extends Service implements OnInitListener, OnUtteranceCompletedListener {

    public static TextToSpeech mtts;
    float rate = (float) 1.0;
    Context context;
    SpeakerService SpeakerService;
    HashMap<String, String> mHashMap;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        Log.d("SpeakerService", "on create Service created successfully!");
        mtts = new TextToSpeech(getApplicationContext(), this);
        mtts.setLanguage(Locale.ENGLISH);
       
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Log.d("SpeakerService", "Service started successfully!"+startid);
       
       
        //new TextToSpeech(getApplicationContext(), this);
       
       
       
   
        /*mtts.speak(StarttabActivity.speetchText,
                TextToSpeech.QUEUE_FLUSH, null);*/
       
         mHashMap = new HashMap<String, String>();

        // tts.speak("Incoming call from", TextToSpeech.QUEUE_FLUSH, mHashMap);

        mHashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, ""+StarttabActivity.counter);
        mtts.speak(StarttabActivity.speetchText, TextToSpeech.QUEUE_ADD, mHashMap);
       
       
       
    }

   

    @Override
    public void onDestroy() {
        if (mtts != null) {
            mtts.stop();
            Toast.makeText(getApplicationContext(),
                    "The service has been destroyed!", Toast.LENGTH_SHORT)
                    .show();
        }

    }

    @Override
    public void onInit(int status) {
        Log.i("status", "status===========" + status);
        if (status == TextToSpeech.SUCCESS) {
            mtts.setLanguage(Locale.ENGLISH);
            mtts.setSpeechRate(rate);
            mtts.setOnUtteranceCompletedListener(this);

           
            Log.i("status", "=========Text-To-Speech engine is initialized");
           
        } else if (status == TextToSpeech.ERROR) {

            Log
                    .i("status",
                            "=========Error occurred while initializing Text-To-Speech engine");

            /*
             * Toast.makeText(BackgroundProcessforTimecheck.this,
             * "Error occurred while initializing Text-To-Speech engine",
             * Toast.LENGTH_LONG).show();
             */
        }

    }

    @Override
    public void onUtteranceCompleted(String utteranceId) {
        // TODO Auto-generated method stub
        Log.i("tag======", "===========on finished"+utteranceId);
   
          System.out.println("onUtteranceCompleted============="+utteranceId);
    }
}
------------------------------------------------------------------------------------------------------------
In the Activity
1.@Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
        stopService(intent);
    }
2.
    @Override public void onResume() {
      super.onResume();
     startService(intent);
     registerReceiver(broadcastReceiver, new
     IntentFilter(SpeakerService.BROADCAST_ACTION)); }
    

TEXT to speech service demo



Text to speech service call by function:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.widget.Toast;

public class SpeakerServices extends Service implements
        OnUtteranceCompletedListener {
   
    private static TextToSpeech myTts;
    static HashMap<String, String> mHashMap;
    static OnUtteranceCompletedListener context;
    Intent intent;
    public static final String BROADCAST_ACTION = "com.stockQuity.TabFirstActivity.displayevent";

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        intent = new Intent(BROADCAST_ACTION);
        myTts = new TextToSpeech(this, ttsInitListener);       
        System.out.println("start services===========");
      
   
        context=this;
    }

   

    private TextToSpeech.OnInitListener ttsInitListener = new TextToSpeech.OnInitListener() {
        public void onInit(int version) {
        }
    };
    public static void speakSMS(String sms,String viewId) {

        myTts.setOnUtteranceCompletedListener(context);
        mHashMap = new HashMap<String, String>();
        mHashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, viewId);

        System.out.println("message========" + sms);
        myTts.speak(sms, TextToSpeech.QUEUE_ADD, mHashMap);

        // myTts.synthesizeToFile(sms, null, "/sdcard/myappsounds/mysms.wav");
    }
   
   
    @Override
    public void onStart(Intent intent, int startid) {
        System.out.println("onini22222t========");
         myTts.setOnUtteranceCompletedListener(this);
    }

    @Override
    public void onDestroy() {
       
   
        if (myTts != null) {
            myTts.stop();
       
            //TabFirstActivity.scaleanimation.cancel();
               
       
            //com.stockQuity.variable.setStartAnimation(false);
            Toast.makeText(getApplicationContext(),
                    "The speech has been destroyed!", Toast.LENGTH_SHORT)
                    .show();
        }
        super.onDestroy();
    }

   

    @Override
    public void onUtteranceCompleted(String utteranceId) {
       
        if(utteranceId.equals("Tab1View1"))
        {
           
            System.out.println("end speech==="+utteranceId);
            intent.putExtra("view", "finishTab1View1");
           
            sendBroadcast(intent);
           
        }
   
        else    if(utteranceId.equals("Tab1View2"))
        {
           
            System.out.println("end speech==="+utteranceId);
            intent.putExtra("view", "finishTab1View2");
           
            sendBroadcast(intent);
           
        }
   
        else    if(utteranceId.equals("Tab1View3"))
        {
           
            System.out.println("end speech==="+utteranceId);
            intent.putExtra("view", "finishTab1View3");
           
            sendBroadcast(intent);
           
        }
   
    }

}


--------------------------------------------------------------------------------------------------------------
URL:http://pastebin.com/sw0TvnYi
http://code.google.com/p/mytracks/source/browse/MyTracksTest/src/com/google/android/apps/mytracks/services/StatusAnnouncerTaskTest.java?spec=svn628b9865aff4cf3e4fa68d2ab8bbaa59f9a0e729&r=628b9865aff4cf3e4fa68d2ab8bbaa59f9a0e729

public class TextToSpeechService extends Service implements OnInitListener, OnUtteranceCompletedListener {
   
    private int ringVolume, mediaVolume;
   
    private AudioManager mAudioManager;
    private TextToSpeech tts;
   
    @Override
    public void onCreate() {
        tts = new TextToSpeech(getApplicationContext(), this);
    }
   
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        HashMap<String, String> mHashMap = new HashMap<String, String>();
       
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        ringVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
        mediaVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
       
        mAudioManager.setStreamVolume(AudioManager.STREAM_RING, ringVolume / 2, AudioManager.FLAG_ALLOW_RINGER_MODES);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, ringVolume, AudioManager.FLAG_ALLOW_RINGER_MODES);
       
        tts.speak("Incoming call from", TextToSpeech.QUEUE_FLUSH, mHashMap);
       
        mHashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "finished id");
        tts.speak(intent.getExtras().getString("incomingNumber"), TextToSpeech.QUEUE_ADD, mHashMap);
       
        return START_STICKY;
    }
   
    public void onInit(int status) {
        tts.setLanguage(Locale.US);
        tts.setOnUtteranceCompletedListener(this);
    }
   
    public void onUtteranceCompleted(String uttId) {
        if (uttId.equals("finished id")) {
            mAudioManager.setStreamVolume(AudioManager.STREAM_RING, ringVolume, AudioManager.FLAG_ALLOW_RINGER_MODES);
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mediaVolume, AudioManager.FLAG_ALLOW_RINGER_MODES);
        }
    }
   
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
   
    @Override
    public void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
    }
}