Tuesday 29 November 2011

Fragments in andriod

public class FragmentTestActivity extends Activity implements OnItemClickListener {
     Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        ListView l = (ListView) findViewById(R.id.number_list);
        ArrayAdapter numbers = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_list_item_1,
                new String [] {
            "one", "two", "three", "four", "five", "six", "seven","eight", "nine", "ten", "eleven", "twelve"  });
l.setAdapter(numbers);
        l.setOnItemClickListener(this);
    }   
    /**
     * Add a Fragment to our stack with n Androids in it
     */
    private void stackAFragment(int nAndroids) {
        Fragment f = new TestFragment(nAndroids);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.the_frag, f);
/*the frag is the name of fragment */
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.addToBackStack(null);
        ft.commit();
    }

    /**
     * Called when a number gets clicked
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        stackAFragment(position + 1);
    }
}




/*   TestFragment.java class  */


public class TestFragment extends Fragment {
    private int nAndroids;
   
    public TestFragment() {
       
    }

   /**
    * Constructor for being created explicitly
    */
   public TestFragment(int nAndroids) {
           this.nAndroids = nAndroids;
    }

    /**
     * If we are being created with saved state, restore our state
     */
    @Override
    public void onCreate(Bundle saved) {
        super.onCreate(saved);
        if (null != saved) {
            nAndroids = saved.getInt("nAndroids");
        }
    }
   
    /**
     * Save the number of Androids to be displayed
     */
    @Override
    public void onSaveInstanceState(Bundle toSave) {
        toSave.putInt("nAndroids", nAndroids);
    }

    /**
     * Make a grid and fill it with n Androids
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved) {
        int n;
/* here we can any widget like button, editext , layout, etc    */
        Context c = getActivity().getApplicationContext();
        LinearLayout l = new LinearLayout(c);
        Button b=new Button(getActivity());
        l.addView(b);
        b.setPadding(0, 100,0,100);
        b.setOnClickListener(new OnClickListener() {
           
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getActivity(), "karan", 20000).show();
            }
        });
      
        for (n = 0; n < nAndroids; n++) {
            ImageView i = new ImageView(c);
            i.setImageResource(R.drawable.android);
            l.addView(i);

/* padding is use to set the ui 
here 100 is use to masgin from top of the image view*/ 

            i.setPadding(0, 100, 0,0);
        }
        return l;
    }
}



/*     main.xml         */

          <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frags">

    <ListView
            android:id="@+id/number_list"
            android:layout_width="250dip"
            android:layout_height="match_parent" />
/*com.example is packafe name of project   
fragmenttest   is class name of this  fragment
testfragment is function name of this fragment  */
    <fragment class="com.example.fragmenttest.TestFragment"
            android:id="@+id/the_frag"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            />

</LinearLayout>



Wednesday 23 November 2011

saxparsing

xml is......
<posts><post><ID>1</ID><Phone_No>15555215556</Phone_No><Phone_ID>0000000000000001</Phone_ID><Unique_Code>Ac26eO1</Unique_Code><Reg_Date>November 22, 2011</Reg_Date></post><post><ID>2</ID><Phone_No>15555215554</Phone_No><Phone_ID>000000000000000</Phone_ID><Unique_Code>URSqJCi</Unique_Code><Reg_Date>November 22, 2011</Reg_Date></post><post><ID>3</ID><Phone_No>15555215558</Phone_No><Phone_ID>0000000000000002</Phone_ID><Unique_Code>6R6kJN2</Unique_Code><Reg_Date>November 24, 2011</Reg_Date></post></posts>

  

/* call this constructor for saxparsing in any class and pass your url*
   
public    Getparsing(String URLS)
    {
     try {
            /** Send URL to parse XML Tags */
        Log.i("getting data","ffffst");
       
        Log.i("getting data","0000");   
       
        URL sourceUrl = new URL(URLS);
        Log.v("name", "4.1");
        SAXParserFactory spf = SAXParserFactory.newInstance();
        Log.v("name", ".4.2");
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        Log.v("name", ".4.3");
        MyXMLHandler myXMLHandler = new MyXMLHandler();
        Log.v("name", "clicking.......4.4");
        xr.setContentHandler(myXMLHandler);
        Log.v("name", "clicking.......4.5");
        xr.parse(new InputSource(sourceUrl.openStream()));
       

     }
        catch (Exception e)
        {   
        System.out.println("XML Parsing Excpetion " + e);
        Log.i("ni chalda", "hai");
        }   
        /* getting data from webservice*/
    SitesList sitesList =new SitesList();
                    sitesList = MyXMLHandler.sitesList;
                    Log.i("size", ""+sitesList.getPhn_ID().size());
                    for (int i = 0; i < sitesList.getPhn_no().size(); i++)
                     {
                     Log.i("getting no",""+sitesList.getPhn_no().get(i));
                     }
                    for (int i = 0; i < sitesList.getPhn_ID().size(); i++)

                     {
                     Log.i("getting id",""+sitesList.getPhn_ID().get(i));
                     }
                    for (int i = 0; i < sitesList.getCode().size(); i++)
                     {
                     Log.i("getting c",""+sitesList.getCode().get(i));
                     }
    }
 




/* getter setter class SitesList*/


public class SitesList {

/** Variables */
private ArrayList<String> phn_no = new ArrayList<String>();
private ArrayList<String> phn_ID = new ArrayList<String>();
private ArrayList<String> code = new ArrayList<String>();
private ArrayList<String> DATE = new ArrayList<String>();

public ArrayList<String> getDATE() {
    return DATE;
}

public void setDATE(String DATE) {
    this.DATE.add(DATE);
}

public ArrayList<String> getPhn_no() {
    return phn_no;
}

public void setPhn_no(String phn_no) {
    this.phn_no.add(phn_no);
}

public ArrayList<String> getPhn_ID() {
    Log.i("karaval",""+phn_ID);
    return phn_ID;
}

public void setPhn_ID(String phn_ID) {
    Log.i("valuekaran",""+phn_ID);
    this.phn_ID.add(phn_ID);
}

public ArrayList<String> getCode() {
    return code;
}

public void setCode(String code) {
    this.code.add(code);
}
}


/*handler class to handle a webservice
here we put start element and end element */

public class MyXMLHandler extends DefaultHandler {
                       
                         Boolean currentElement = false;
                         String currentValue = null;  
                           
                            public static  SitesList sitesList ;
                       
                            public static SitesList getSitesList() {
                                return sitesList;
                            }
                       
                            public static void setSitesList(SitesList sitesList) {
                                MyXMLHandler.sitesList = sitesList;
                            }
                           
                           
                              @Override
                            public void startElement(String uri, String localName, String qName,
                                    org.xml.sax.Attributes attributes) throws SAXException {
                                // TODO Auto-generated method stub
                                  currentElement = true;
                                    if (localName.equals("posts"))
                                    {
                                        /** Start */
                                       
                                        sitesList = new SitesList();
                                    }
                            }
                           
                            @Override
                            public void endElement(String uri, String localName, String qName)
                               throws SAXException {
                                currentElement = false;
                               
                                if (localName.equalsIgnoreCase("Phone_No"))
                                     sitesList.setPhn_no(currentValue);
                                 else if (localName.equalsIgnoreCase("Phone_ID"))
                                         sitesList.setPhn_ID(currentValue);
                                 else if (localName.equalsIgnoreCase("Unique_Code"))
                                     sitesList.setCode(currentValue);
                                 else if (localName.equalsIgnoreCase("Reg_Date"))
                                         sitesList.setDATE(currentValue);
                                Log.i("krn",""+currentValue);
                                Log.i("krn222",""+currentElement);
                                Log.i("size222",""+sitesList.getPhn_no().size());
                            }
                           
                            @Override
                            public void characters(char[] ch, int start, int length)
                                    throws SAXException {
                       
                           if (currentElement) {
                                    currentValue = new String(ch, start, length);
                                    currentElement = false;
                                }
                       
                            }
                           
                           

                    }


put a data in json object to create a parameter for webservice

JSONObject jobj= new JSONObject();
                    try
                    {
                        jobj.put("Phone_No", ourNumber);//////// PUT DATA INO JSON OBJECT
                        jobj.put("Phone_ID",sDeviceID);
                   
                        //jobj.put("karan2", "karan");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        String  parameter= jobj.toString();
        http://192.168.3.24/phpnewebservice/phonewebservice.php?user=1
        ParsingN.postHTPPRequest("your urlllllllllllllllllllllllllllllllllllllll", parameter);

json parsing

 /* call this function to post a data on webservice*/


static public String postHTPPRequest(String URL, String paramenter)
    {
           
            Log.i("aa",""+paramenter);
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setHeader("Content-Type", "application/json");
            Log.i("aadd",""+httppost);
            try
            {
            if(paramenter != null)
            {
                StringEntity tmp = null;
               
                    tmp = new StringEntity(paramenter,"UTF-8");
                      httppost.setEntity(tmp);
            }
            HttpResponse httpResponse = null;
           
                httpResponse = httpclient.execute(httppost);
           
            int code = httpResponse.getStatusLine().getStatusCode();
            System.out.print("hello==========="+code);
            Log.i("hh", ""+code);
           /* if(code == 200)
            {*/
                HttpEntity entity = httpResponse.getEntity();
                if(entity != null)
                {
                     byte[] Data = new byte[256];
                     //int len = 0;
                     InputStream input = null;
                   
                        input = entity.getContent();
                        String res=convertStreamToString(input);
                   input.close();
                                            
                     System.out.println("****************postHTPPRequest::response =  " + new String(Data));
                     System.out.println("post=="+new String(Data));
                     return res;
                }
            //}
            }
            catch(Exception e)
            {
                Log.e("","ERROR"+ e);
            }
           
   
        return null;
    }
   
     private static String convertStreamToString(InputStream is) {
            /*
             * To convert the InputStream to String we use the BufferedReader.readLine()
             * method. We iterate until the BufferedReader return null which means
             * there's no more data to read. Each line will appended to a StringBuilder
             * and returned as String.
             */
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
   
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                Log.e("","ERROR"+e);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    Log.e("","ERROR"+e);
                }
            }
            return sb.toString();
        }

}

Monday 14 November 2011

Animation in andriod

n this Post i will tell you about the simple blinking animation using apha property of android.
First create a class as follows by extending the Animation class:

BlinkAnimation,java

public class BlinkAnimation extends Animation {
    private int totalBlinks;
    private boolean finishOff;
  
    public BlinkAnimation(int totalBlinks, boolean finishOff) {
        this.totalBlinks = totalBlinks;
        this.finishOff = finishOff;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        float period = interpolatedTime * totalBlinks * 3.14f + (finishOff ? 3.14f / 2 : 0);
        t.setAlpha(Math.abs(FloatMath.cos(period)));
    }

    @Override
    public boolean willChangeBounds() {
        return false;
    }

    @Override
    public boolean willChangeTransformationMatrix() {
        return false;
    }
}


Next step is to create a avtivity to instaniate the animation as follows:

TestActivity.java


public class TestActivity extends Activity implements OnClickListener, AnimationListener {
    private ImageView image;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        image = (ImageView) findViewById(R.id.image);
        ((Button) findViewById(R.id.button)).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button) {
            Animation animation;
            if (image.getVisibility() == View.VISIBLE) {
                animation = new BlinkAnimation(3, true);
                animation.setInterpolator(new DecelerateInterpolator());
            } else {
                animation = new BlinkAnimation(3, false);
                animation.setInterpolator(new AccelerateInterpolator());
            }
            animation.setDuration(1000L);
            animation.setAnimationListener(this);
          
            image.startAnimation(animation);
        }
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        image.setVisibility(image.getVisibility() == View.VISIBLE ?
                View.INVISIBLE : View.VISIBLE);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {}

    @Override
    public void onAnimationStart(Animation animation) {}
}



and your XML file would look like this a follows:

main.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">
  <ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dip"
    android:src="@drawable/icon" />
  <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dip"
    android:text="Please click me" />
</LinearLayout>

Changning Rining MODE

Today i am going to write about changing the ringer mode of the Android phone programmitically.
Quite Simple: :-)

Step1):Make an object of Audio Manger class
                    AudioManager am;
                    am = (AudioManager)
                    context.getSystemService(Context.AUDIO_SERVICE);



Step2)Now after you have created the object of audio manager class you can at any time change the Ringer mode as follows:

For Silent Mode:
am.setRingerMode(0);        


For Vibrate mode:

am.setRingerMode(1);        


For Normal mode:

am.setRingerMode(2);     

DATABASE

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class DataBase33 {


public static final String Row_categoryID="_categoryid";
public static final String Row_CategoryName="CategoryName";
public static final String Table_Name3="CategoryTable";

private static final String DataBase_Name="foodDataBase33";
private static final int version =1;
private static final String TAG = "DBAdapter";

private static final String DATA_CREATE2="create table CategoryTable(_categoryid integer primary key autoincrement,"+ " CategoryName text not null);";

private static Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DataBase33(Context con)
{
this.context=con;
DBHelper=new DatabaseHelper(con);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
       DatabaseHelper(Context context)
       {
           super(context, DataBase_Name, null, version);
       }

   
       public void onCreate(SQLiteDatabase db)
       {
       
           db.execSQL(DATA_CREATE2);
       }
 
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
       {
           Log.w(TAG, "Upgrading dataBase from version " + oldVersion + " to "+ newVersion + ", which will destroy all old data");
           db.execSQL("DROP TABLE IF EXISTS note_table");
           onCreate(db);
       }
   }  

public DataBase33 open() throws  Exception
{
db = DBHelper.getWritableDatabase();
       return this;
}

public void close()
{
DBHelper.close();
}

public long insertcategory(String categoryname)
{
ContentValues cv1=new ContentValues();
cv1.put(Row_CategoryName, categoryname);
Log.d("karannnnnnnnnn11111111111111111", categoryname);
return db.insert(Table_Name3, null, cv1);
}

public Cursor getcategory() throws SQLException
{
return db.query( Table_Name3,  new String[]{ Row_categoryID , Row_CategoryName }, null,null,null,null,null);
}
 
public Cursor getAllcategory()
{
Cursor rt= db.rawQuery("select * from  CategoryTable",null);
return rt;
}


}

get lognitute and latitute

 LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  
   Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

double longitude = location.getLongitude();
   double       latitude = location.getLatitude();

how to find own sim no.

TelephonyManager tMgr =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);

double mPhoneNumber = tMgr.getLine1Number();

lAYOUT

<RelativeLayout android:id="@+id/relativeLayout8" android:layout_width="wrap_content" android:layout_below="@+id/relativeLayout7" android:layout_marginLeft="70dip" android:layout_marginTop="-5dip" android:layout_height="27dip">
                <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/TextView05" android:layout_alignParentLeft="true" android:background="@drawable/freak_off"></TextView>
                <Spinner android:id="@+id/spinner1" android:layout_marginLeft="165dip" android:layout_width="160dip" android:layout_height="15dip" android:layout_marginTop="8dip"></Spinner>
            </RelativeLayout>