Monday, September 30, 2013

Passing Object Through Intent

Student.java
---------------
package com.example.passobject;

import java.io.Serializable;

public class Student implements Serializable{
/**

*/
private static final long serialVersionUID = 1L;
private String sid;
private String sname;
private String semail;
public Student(){}
public Student(String sid, String sname, String semail) {
super();
this.sid = sid;
this.sname = sname;
this.semail = semail;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSemail() {
return semail;
}
public void setSemail(String semail) {
this.semail = semail;
}


}


MainActivity.java
-------------------
package com.example.passobject;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText ed1,ed2,ed3;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText) findViewById(R.id.editText1);
ed2=(EditText) findViewById(R.id.editText2);
ed3=(EditText) findViewById(R.id.editText3);
btn1=(Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "SUCCESS", Toast.LENGTH_SHORT).show();
String id=ed1.getText().toString();
String name=ed2.getText().toString();
String email=ed3.getText().toString();
Student stud=new Student(id, name, email);
Intent intent=new Intent(MainActivity.this,Second.class);
intent.putExtra("StuObj", stud);
startActivity(intent);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


Second.java
----------------
package com.example.passobject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class Second extends Activity {
TextView tv1,tv2,tv3;
Student studobj;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tv1=(TextView) findViewById(R.id.idView);
tv2=(TextView) findViewById(R.id.nameView);
tv3=(TextView) findViewById(R.id.emailView);
try {
studobj=(Student) getIntent().getSerializableExtra("StuObj");
} catch (Exception e) {
Log.e("Error is",e.toString());
}
if(studobj!=null){
tv1.setText(studobj.getSid());
tv2.setText(studobj.getSname());
tv3.setText(studobj.getSemail());
}
}

}


activity_main.xml
--------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        
        android:ems="10"
        android:hint="Enter Student id" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:ems="10" 
        android:hint="Enter Student name"/>

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:ems="10" 
        android:hint="Enter Email"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText3"
        android:layout_below="@+id/editText3"
        android:text="SEND" />

</RelativeLayout>


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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/textView1"
            android:layout_below="@+id/textView1"
            android:layout_marginTop="28dp"
            android:text="SNAME" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/textView3"
            android:layout_below="@+id/textView3"
            android:layout_marginTop="28dp"
            android:text="SEMAIL" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="38dp"
            android:text="SID" />

        <TextView
            android:id="@+id/nameView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView5"
            android:layout_alignLeft="@+id/idView"
            android:text="TextView" />

        <TextView
            android:id="@+id/emailView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView5"
            android:layout_alignBottom="@+id/textView5"
            android:layout_alignLeft="@+id/nameView"
            android:text="TextView" />

        <TextView
            android:id="@+id/idView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView3"
            android:layout_centerHorizontal="true"
            android:text="TextView" />

    </RelativeLayout>

</LinearLayout>



Friday, September 27, 2013

Count down timer

package com.kundan.timer;

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

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
TextView tv;
int time=10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.textView);
 
        final Handler h = new Handler();
        final Runnable r = new Runnable() 
        {
@Override
public void run() 
{


                if(time==0){
                //finish();
    //android.os.Process.killProcess(android.os.Process.myPid());
            
                Toast t=Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_SHORT);
                t.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
                t.show();
               
                }else{
                time--;
                    tv.setText("Countdown time: "+time+" seconds" );
                }
}
};

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() 
{
@Override
public void run() 
{
h.post(r);
}
}, 1000, 5000 );




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Monday, September 23, 2013

URLs Hitting using Spring for Android Framework

Add the following jars in your /lib folder
------------------------------------------
spring-android-auth-1.0.0.M3.jar
spring-android-core-1.0.0.M3.jar
spring-android-rest-template-1.0.0.M3.jar

MainActivity.java
--------------------
package com.kundan.springforandroid;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
static TextView tv;
public static final String URL="http://api.androidhive.info/contacts/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser parser=new JSONParser();
parser.execute(new String[]{URL});
tv=(TextView) findViewById(R.id.springmessage);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

JSONParse.java
-------------------
package com.kundan.springforandroid;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import android.os.AsyncTask;

public class JSONParser extends AsyncTask<String, Void, String> {

String output;
@Override
protected String doInBackground(String... urls) {
for(String url:urls){
output=getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
try {
HttpHeaders headers=new HttpHeaders();
headers.setContentType(new MediaType("text","xml"));
HttpEntity<String>requestEntity=new HttpEntity<String>(headers);
RestTemplate restTemplate=new RestTemplate();
ResponseEntity<String>responseEntity=restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
String output=responseEntity.getBody();
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
@Override

protected void onPostExecute(String output) {
MainActivity.tv.setText(output);
}
}


Monday, September 9, 2013

XML Parsing using SAX Parser

raw->books.xml
------------------
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <bid>B-01</bid>
        <bname>master android</bname>
        <auther>kk</auther>
        <price>99</price>
    </book>
    <book>
        <bid>B-02</bid>
        <bname>android cook book</bname>
        <auther>kundan</auther>
        <price>900</price>
    </book>
    
</books>
avtivity_main.xml
------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/book_details"
        android:textColor="#999999"
        android:textSize="30dp" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="16dp" >
    </ListView>

</RelativeLayout>

item.xml
----------------
<?xml version="1.0" encoding="utf-8"?>


    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/rowtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

MainActivity.java
---------------------
package com.example.xmlparsing;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

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

import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {
List<String>booksinfo=new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
BooksHandler handler=new BooksHandler();
reader.setContentHandler(handler);
InputStream is=getResources().openRawResource(R.raw.books);
reader.parse(new InputSource(is));
booksinfo=handler.getBooksInfo();
}catch(Exception e){
e.printStackTrace();
}
ArrayAdapter<String>bookList=new ArrayAdapter<String>(this,R.layout.item,booksinfo);
setListAdapter(bookList);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


BooksHandler.java
----------------------
package com.example.xmlparsing;

import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;

import org.xml.sax.helpers.DefaultHandler;

public class BooksHandler extends DefaultHandler {
List<String>list=new ArrayList<String>();
public void startDocument(){
System.out.println("startDocument()");
}
public void endDocument(){
System.out.println("endDocument()");
}
public void startElement(String tns,String tn,String tln,Attributes atts){
System.out.println("startElement()");
}
public void endElement(String tns,String tn,String tln){
System.out.println("endtElement()");
}
public void characters(char ch[],int start,int total){
System.out.println("characters()");
String str=new String(ch,start,total);
list.add(str);
}
public List<String> getBooksInfo(){
return list;
}
}


Sunday, September 8, 2013

RESTFul(JAX-RS)

StudentService.java
---------------------
package com.kundan.wstest;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("student")
public class StudentService {
@GET
@Path("getallasjson")
@Produces(MediaType.APPLICATION_JSON)
public List<Student>getAllStudentAsJSON(){
List<Student>studList=new ArrayList<Student>();
Student s1=new Student(101, "kundan", "me@gmail.com", 888);
studList.add(s1);
Student s2=new Student(102, "prem", "pp@gmail.com", 999);
studList.add(s2);
return studList;

}


@GET
@Path("getall")
@Produces(MediaType.APPLICATION_XML)
public List<Student>getAllStudentAsXML(){
List<Student>studList=new ArrayList<Student>();
Student s1=new Student(101, "kundan", "me@gmail.com", 888);
studList.add(s1);
Student s2=new Student(102, "rajeev", "u@gmail.com", 999);
studList.add(s2);
return studList;

}
@GET
@Path("{sid}/getbyidasjson")
@Produces(MediaType.APPLICATION_JSON)
public Student getAllStudentAsJSON(@PathParam("sid")int sid){
Student s2=new Student(105, "kkk", "u@gmail.com", 5555);
return s2;
}

}


Student.java
---------------------
package com.kundan.wstest;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name="student")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="Student")
public class Student {
private Integer sid;
private String sname;
private String email;
private Integer phone;
public Student(){} 
public Student(Integer sid, String sname, String email, Integer phone) {
// TODO Auto-generated constructor stub
this.sid=sid;
this.sname=sname;
this.email=email;
this.phone=phone;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getPhone() {
return phone;
}
public void setPhone(Integer phone) {
this.phone = phone;
}

}

web.xml
------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>WebServiceTest</display-name>
  <servlet>
  <servlet-name>REST</servlet-name>
  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  <init-param>
  <param-name>com.sun.jersey.config.property.packages</param-name>
  <param-value>com.kundan.wstest</param-value>
  
  </init-param>
  <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>REST</servlet-name>
  <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

Add the following jar in WEB-INF->lib
------------------------------------------

/WebServiceTest/WebContent/WEB-INF/lib/activation-1.1.jar
/WebServiceTest/WebContent/WEB-INF/lib/asm-3.1.jar
/WebServiceTest/WebContent/WEB-INF/lib/commons-beanutils-1.7.jar
/WebServiceTest/WebContent/WEB-INF/lib/commons-collections.jar
/WebServiceTest/WebContent/WEB-INF/lib/commons-lang.jar
/WebServiceTest/WebContent/WEB-INF/lib/commons-logging-1.1.1.jar
/WebServiceTest/WebContent/WEB-INF/lib/ezmorph.jar
/WebServiceTest/WebContent/WEB-INF/lib/jaxb-api-2.1.jar
/WebServiceTest/WebContent/WEB-INF/lib/jaxb-impl-2.1.10.jar
/WebServiceTest/WebContent/WEB-INF/lib/jersey-core-1.0.3.1.jar
/WebServiceTest/WebContent/WEB-INF/lib/jersey-json-1.0.3.jar
/WebServiceTest/WebContent/WEB-INF/lib/jersey-server-1.0.3.1.jar
/WebServiceTest/WebContent/WEB-INF/lib/json-lib-2.2.2-jdk15.jar
/WebServiceTest/WebContent/WEB-INF/lib/jsr311-api-1.0.jar
/WebServiceTest/WebContent/WEB-INF/lib/stax-api-1.0-2.jar
/WebServiceTest/WebContent/WEB-INF/web.xml


URL:
-------
 http://localhost:8080/WebServiceTest/rest/student/getall
http://localhost:8080/WebServiceTest/rest/student/getallasjson
http://localhost:8080/WebServiceTest/rest/student/105/getbyidasjson

output
---------
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<students>
-<student>
<sid>101</sid>
<sname>kundan</sname>
<email>me@gmail.com</email>
<phone>888</phone>
</student>
-<student>
<sid>102</sid>
<sname>rajeev</sname>
<email>u@gmail.com</email>
<phone>999</phone>
</student>
</students>