Sunteți pe pagina 1din 44

MAD LAB ALL EXPERIMENTS:

Ex1:FONT
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:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="46dp"
android:text="NAME"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/radioButton1"
android:layout_alignParentRight="true"
android:text="Female" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_marginLeft="22dp"
android:layout_toRightOf="@+id/radioButton1"
android:text="Button" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignLeft="@+id/textView1"
android:layout_marginBottom="28dp"
android:text="Gender"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold"/>
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView3"
android:layout_toRightOf="@+id/button1"
android:text="Male" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/editText1"
android:ems="10"
android:inputType="date" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView2"
android:layout_marginTop="39dp"
android:text="Dept"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView5"
android:layout_alignLeft="@+id/radioButton1"
android:layout_alignRight="@+id/editText2" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_alignParentBottom="true"
android:text="Button" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/radioButton1"
android:layout_alignLeft="@+id/textView5"
android:layout_marginBottom="36dp"
android:text="Year"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold" />
<Spinner
android:id="@+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/spinner1"
android:layout_centerVertical="true" />
<Spinner
android:id="@+id/spinner3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/spinner2"
android:layout_below="@+id/spinner2" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/spinner1"
android:layout_alignLeft="@+id/textView1"
android:layout_marginBottom="15dp"
android:text="DOB"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView1"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_centerVertical="true"
android:text="Sec"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
Java:
package com.example.psnacet;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv3=(TextView) findViewById(R.id.textView3);
tv3.setText("BME_BLOCK");
tv3.setTextColor(0xffff00ff);
tv3.setTextSize(30);
}
@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;
}
}
EXP2:TOAST
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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="66dp"
android:text="Login" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView3"
android:layout_alignLeft="@+id/button1" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignLeft="@+id/textView2"
android:layout_marginBottom="65dp"
android:text="Gender"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="My profile"
android:textSize="30sp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView4"
android:layout_marginRight="16dp"
android:layout_marginTop="37dp"
android:layout_toLeftOf="@+id/editText1"
android:text="Name"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_alignLeft="@+id/textView4"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignTop="@+id/spinner1"
android:text="Dept"
android:textColor="#0f0fcd"
android:textSize="20sp"
android:textStyle="bold" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignLeft="@+id/spinner1" >
</RadioGroup>
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_alignTop="@+id/textView3"
android:checked="true"
android:text="Female" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radio0"
android:layout_below="@+id/radio0"
android:text="Male" />
</RelativeLayout>
Java:
package com.example.text;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1=(Button) findViewById(R.id.button1);
final Spinner dropdown=(Spinner) findViewById(R.id.spinner1);
String[] items=new String[]{"CSE","ECE","MECH","BME"};
ArrayAdapter<String> adaptor=new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,items);
dropdown.setAdapter(adaptor);
final EditText et1=(EditText)findViewById(R.id.editText1);
final RadioGroup radio=(RadioGroup)findViewById(R.id.radioGroup1);
final RadioButton r11=(RadioButton)findViewById(R.id.radio0);
final RadioButton r22=(RadioButton)findViewById(R.id.radio1);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
int SelectedId=radio.getCheckedRadioButtonId();
String et2=et1.getText().toString();
Toast.makeText(getApplicationContext(),et2,Toast.LENGTH_LONG).show();
String et3=dropdown.getSelectedItem().toString();
Toast.makeText(getApplicationContext(),et3,Toast.LENGTH_LONG).show();
if (SelectedId==r11.getId())
{
Toast.makeText(getApplicationContext(),r11.getText().toString(),Toast.LENGTH_SHORT).show(
);
}
else if(SelectedId==r22.getId())
{
Toast.makeText(getApplicationContext(),r22.getText().toString(),Toast.LENGTH_SHORT).show(
);
}
}
});
}
@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;
}
}
EXP3:CALCULATOR
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout1"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:layout_marginTop="3pt">
<EditText
android:id="@+id/etNum1"
android:layout_width="match_parent"
android:layout_height="39dp"
android:layout_marginRight="5pt"
android:layout_weight="0.96"
android:background="#F0fFff"
android:inputType="numberDecimal" >
</EditText></LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout1"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:layout_marginTop="3pt">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout1"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:layout_marginTop="3pt">
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5" />
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6" />
<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7" />
<Button
android:id="@+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout1"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:layout_marginTop="3pt">
<Button
android:id="@+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9" />
<Button
android:id="@+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0" />
<Button
android:id="@+id/buttonC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C" />
<Button
android:id="@+id/btnEq"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:textSize="8pt" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout2"
android:layout_marginTop="3pt"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:textSize="8pt"
android:id="@+id/btnAdd">
</Button>
<Button
android:id="@+id/btnSub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*"
android:textSize="8pt"
android:id="@+id/btnMult">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:textSize="8pt"
android:id="@+id/btnDiv">
</Button>
</LinearLayout>
</LinearLayout>
Java:
package com.example.calc;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
@SuppressWarnings("unused")
public class MainActivity extends Activity implements OnClickListener {
EditText etNum1;
// EditText et1;
Button b1;
Button b2;
Button btnAdd;
Button btnSub;
Button btnMult;
Button btnDiv;
Button btnEq;
Button b3,b4,b5,b6,b7,b8,b9,b10,bclear;
TextView tvResult;
int cplus=0;
int cminus=0;
int cmul=0;
int cdiv=0;
float num1=0;
float num2=0 ;
float result = 0;
float res=0;
private String plus;
public enum oper1
{
plus,minus,multiply,divide;
}
oper1 oper=oper1.plus;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the elements
b1=(Button) findViewById(R.id.button1);
b2=(Button) findViewById(R.id.button2);
b3=(Button) findViewById(R.id.button3);
b4=(Button) findViewById(R.id.button4);
b5=(Button) findViewById(R.id.button5);
b6=(Button) findViewById(R.id.button6);
b7=(Button) findViewById(R.id.button7);
b8=(Button) findViewById(R.id.button8);
b9=(Button) findViewById(R.id.button9);
b10=(Button) findViewById(R.id.button0);
bclear=(Button) findViewById(R.id.buttonC);
btnEq=(Button) findViewById(R.id.btnEq);
etNum1 = (EditText) findViewById(R.id.etNum1);
//et1 = (EditText) findViewById(R.id.et1);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnSub = (Button) findViewById(R.id.btnSub);
btnMult = (Button) findViewById(R.id.btnMult);
btnDiv = (Button) findViewById(R.id.btnDiv);
// set a listener
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
b7.setOnClickListener(this);
b8.setOnClickListener(this);
b9.setOnClickListener(this);
b10.setOnClickListener(this);
bclear.setOnClickListener(this);
btnEq.setOnClickListener(this);
btnAdd.setOnClickListener(this);
btnSub.setOnClickListener(this);
btnMult.setOnClickListener(this);
btnDiv.setOnClickListener(this);
etNum1.setText("");
}
public void onClick(View v)
{
switch (v.getId())
{
case R.id.buttonC:
etNum1.setText(" ");
res=0;
cplus=0;
cminus=0;
cmul=0;
cdiv=0;
break;
case R.id.btnAdd:
oper = oper1.plus;
if(cplus==0)
res=Float.parseFloat(etNum1.getText().toString());
else
res=res + Float.parseFloat(etNum1.getText().toString());
cplus++;
etNum1.setText("");
break;
case R.id.btnSub:
oper =oper1.minus;
if(cminus==0)
res=Float.parseFloat(etNum1.getText().toString());
else
res=res - Float.parseFloat(etNum1.getText().toString());
cminus++;
etNum1.setText("");
break;
case R.id.btnMult:
oper = oper1.multiply;
if(cmul==0)
res=Float.parseFloat(etNum1.getText().toString());
else
res=res * Float.parseFloat(etNum1.getText().toString());
cmul++;
etNum1.setText("");
break;
case R.id.btnDiv:
oper =oper1.divide;
if(cdiv==0)
res=Float.parseFloat(etNum1.getText().toString());
else
res=res / Float.parseFloat(etNum1.getText().toString());
cdiv++;
etNum1.setText("");
break;
case R.id.btnEq:
cplus=0;
cminus=0;
cmul=0;
cdiv=0;
switch(oper)
{
case plus:
res= res+Float.parseFloat(etNum1.getText().toString());
etNum1.setText(" "+res);
break;
case minus:
res= res-Float.parseFloat(etNum1.getText().toString());
etNum1.setText(" "+res);
break;
case multiply:
res= res * Float.parseFloat(etNum1.getText().toString());
etNum1.setText(" "+res);
break;
case divide:
res= res / Float.parseFloat(etNum1.getText().toString());
etNum1.setText(" "+res);
break;
}
Toast.makeText(getApplicationContext(), "Your BMI is " + res,Toast.LENGTH_SHORT).show();
break;
default:
String buttonPressed = ((Button) v).getText().toString();
etNum1.append(buttonPressed);
break;
}
}
}
Exp4:DRAW PRIMITIVES
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" >
<LinearLayout
android:layout_width="wrap_content"
android:id="@+id/dgm"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="56dp"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Square" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button3"
android:layout_below="@+id/button3"
android:text="Line" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:text="Circle" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_below="@+id/button2"
android:text="Rect" />
</LinearLayout>
</RelativeLayout>
Java:
package com.example.draw;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
@SuppressWarnings("unused")
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button b1,b2,b3,b4;
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
}
@SuppressWarnings("deprecation")
public void onClick(View v)
{
Paint p=new Paint();
Bitmap bm=Bitmap.createBitmap(480,800,Bitmap.Config.ARGB_8888);
LinearLayout ll=(LinearLayout)findViewById(R.id.dgm);
ll.setBackgroundDrawable(new BitmapDrawable(bm));
Canvas c=new Canvas(bm);
switch(v.getId())
{
case R.id.button4:
p.setColor(Color.MAGENTA);
c.drawRect(200,200,300,300,p);
break;
case R.id.button2:
p.setColor(Color.BLUE);
//c.drawOval(new RectF(160,260,220,380),p);
c.drawCircle(240,400,50, p);
break;
case R.id.button3:
p.setColor(Color.GREEN);
c.drawRect(260,260,300,160,p);
break;
case R.id.button1:
p.setColor(Color.RED);
p.setStrokeWidth(10);
c.drawLine(250,300,190,360,p);
//c.drawLine(300, 260, 200, 260, p);
break;
}
}
@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;
}
}
EXP5:DATABASE CONNECTIVITY
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/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="My DB" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginLeft="25dp"
android:layout_marginTop="44dp"
android:text="Reg_no" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="56dp"
android:text="Name" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView3"
android:layout_alignLeft="@+id/textView2"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText1"
android:ems="10" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/textView2"
android:ems="10" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText3"
android:layout_alignLeft="@+id/textView3"
android:text="Percent" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/textView4"
android:layout_marginTop="38dp"
android:text="Add" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/textView2"
android:text="Delete" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button1"
android:layout_marginTop="25dp"
android:text="Modify" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button3"
android:layout_centerHorizontal="true"
android:text="View" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button4"
android:layout_alignRight="@+id/editText3"
android:text="View All" />
</RelativeLayout>
Java:
package com.example.expdb;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.view.Menu;
public class MainActivity extends Activity implements OnClickListener{
EditText eroll,ename,emarks;
Button add,del,mod,bview,viewall;//btnShowInfo;
SQLiteDatabase db;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eroll=(EditText)findViewById(R.id.editText1);
ename=(EditText)findViewById(R.id.editText2);
emarks=(EditText)findViewById(R.id.editText3);
add=(Button)findViewById(R.id.button1);
del=(Button)findViewById(R.id.button2);
mod=(Button)findViewById(R.id.button3);
bview=(Button)findViewById(R.id.button4);
viewall=(Button)findViewById(R.id.button5);
add.setOnClickListener(this);
del.setOnClickListener(this);
mod.setOnClickListener(this);
bview.setOnClickListener(this);
viewall.setOnClickListener(this);
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks
VARCHAR);");
}
public void onClick(View view)
{
if(view==add)
{
if(eroll.getText().toString().trim().length()==0 ||
ename.getText().toString().trim().length()==0 ||
emarks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student VALUES('"+eroll.getText()+"','"+ename.getText()+
"','"+emarks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
if(view==del)
{
if(eroll.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+eroll.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE rollno='"+eroll.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==mod)
{
if(eroll.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+eroll.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("UPDATE student SET name='"+ename.getText()+"',marks='"+emarks.getText()
+ "' WHERE rollno='"+eroll.getText()+"'");
showMessage("Success","Record Modified");
}
else
{
showMessage("Error","Invalid Rollno");
}
clearText();
}
if(view==bview)
{
if(eroll.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+eroll.getText()+"'", null);
if(c.moveToFirst())
{
ename.setText(c.getString(1));
emarks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
if(view==viewall)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n \n");
}
showMessage("Student Details", buffer.toString());
}
/* if
(view==btnShowInfo)
{
showMessage("Student Management Application", " ");
}*/
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
eroll.setText("");
ename.setText("");
emarks.setText("");
eroll.requestFocus();
}
@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;
}
}
EXP NO-6:RSS FEED
XML HANDLER.java
package com.rssfeed.helper;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XmlHandler extends DefaultHandler {
private RssFeedStructure feedStr = new RssFeedStructure();
private List<RssFeedStructure> rssList = new ArrayList<RssFeedStructure>();
private int articlesAdded = 0;
// Number of articles to download
private static final int ARTICLES_LIMIT = 25;
StringBuffer chars = new StringBuffer();
public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();
if (qName.equalsIgnoreCase("media:content"))
{
if(!atts.getValue("url").toString().equalsIgnoreCase("null")){
feedStr.setImgLink(atts.getValue("url").toString());
}
else{
feedStr.setImgLink("");
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("title"))
{
feedStr.setTitle(chars.toString());
}
else if (localName.equalsIgnoreCase("description"))
{
feedStr.setDescription(chars.toString());
}
else if (localName.equalsIgnoreCase("pubDate"))
{
feedStr.setPubDate(chars.toString());
}
else if (localName.equalsIgnoreCase("encoded"))
{
feedStr.setEncodedContent(chars.toString());
}
else if (qName.equalsIgnoreCase("media:content"))
{
}
else if (localName.equalsIgnoreCase("link"))
{
}
if (localName.equalsIgnoreCase("item")) {
rssList.add(feedStr);
feedStr = new RssFeedStructure();
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT)
{
throw new SAXException();
}
}
}
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
public List<RssFeedStructure> getLatestArticles(String feedUrl) {
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
} catch (SAXException e) {
} catch (ParserConfigurationException e) {
}
return rssList;
}
}
SORTINGORDER.java
package com.rssfeed.helper;
import java.util.Comparator;
import org.json.JSONObject;
public class SortingOrder implements Comparator<RssFeedStructure>{
public int compare(RssFeedStructure o1, RssFeedStructure o2) {
return (o1.getTitle()).compareTo(o2.getTitle());
}
}
RSSREADERLISTADAPTER.java
package com.rssfeed.adapter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import com.rssfeed.R;
import com.rssfeed.helper.RssFeedStructure;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RssReaderListAdapter extends ArrayAdapter<RssFeedStructure> {
List<RssFeedStructure> imageAndTexts1 =null;
public RssReaderListAdapter(Activity activity, List<RssFeedStructure> imageAndTexts) {
super(activity, 0, imageAndTexts);
imageAndTexts1 = imageAndTexts;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
View rowView = inflater.inflate(R.layout.rssfeedadapter_layout, null);
TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
TextView timeFeedText = (TextView) rowView.findViewById(R.id.feed_updatetime);
ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
try {
Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: "
+imageAndTexts1.get(position).getImgLink() +" :: "
+imageAndTexts1.get(position).getTitle());
textView.setText(imageAndTexts1.get(position).getTitle());
SpannableString content = new
SpannableString(imageAndTexts1.get(position).getPubDate());
content.setSpan(new UnderlineSpan(), 0, 13, 0);
timeFeedText.setText(content);
if(imageAndTexts1.get(position).getImgLink() !=null){
URL feedImage= new URL(imageAndTexts1.get(position).getImgLink().toString());
if(!feedImage.toString().equalsIgnoreCase("null")){
HttpURLConnection conn= (HttpURLConnection)feedImage.openConnection();
InputStream is = conn.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(img);
}
else{
imageView.setBackgroundResource(R.drawable.im);
}
}
} catch (MalformedURLException e) {
}
catch (IOException e) {
}
return rowView;
}
}
RSSFEEDSTRUCTURE.java
package com.rssfeed.helper;
import java.net.URL;
public class RssFeedStructure {
private long articleId;
private long feedId;
private String title;
private String description;
private String imgLink;
private String pubDate;
private URL url;
private String encodedContent;
public long getArticleId() {
return articleId;
}
public void setArticleId(long articleId) {
this.articleId = articleId;
}
public long getFeedId() {
return feedId;
}
/**
* @param feedId the feedId to set
*/
public void setFeedId(long feedId) {
this.feedId = feedId;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the url
*/
public URL getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(URL url) {
this.url = url;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
if (description.contains("<img ")){
String img = description.substring(description.indexOf("<img "));
String cleanUp = img.substring(0, img.indexOf(">")+1);
img = img.substring(img.indexOf("src=") + 5);
int indexOf = img.indexOf("'");
if (indexOf==-1){
indexOf = img.indexOf("\"");
}
img = img.substring(0, indexOf);
//setImgLink(img);
this.description = this.description.replace(cleanUp, "");
}
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param pubDate the pubDate to set
*/
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
/**
* @return the pubDate
*/
public String getPubDate() {
return pubDate;
}
/**
* @param encodedContent the encodedContent to set
*/
public void setEncodedContent(String encodedContent) {
this.encodedContent = encodedContent;
}
/**
* @return the encodedContent
*/
public String getEncodedContent() {
return encodedContent;
}
/**
* @param imgLink the imgLink to set
*/
public void setImgLink(String imgLink) {
this.imgLink = imgLink;
}
/**
* @return the imgLink
*/
public String getImgLink() {
return imgLink;
}
}
RSSFEEDREADERDB.java
package com.rssfeed.activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class RssFeedReaderDB extends SQLiteOpenHelper{
public RssFeedReaderDB(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
RSSFEEDREADERACTIVITY.java
package com.rssfeed.activity;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;
import org.json.JSONObject;
import com.rssfeed.R;
import com.rssfeed.adapter.RssReaderListAdapter;
import com.rssfeed.helper.SortingOrder;
import com.rssfeed.helper.ReverseOrder;
import com.rssfeed.helper.RssFeedStructure;
import com.rssfeed.helper.XmlHandler;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
public class RssFeedReaderActivity extends Activity {
/** Called when the activity is first created. */
ListView _rssFeedListView;
List<JSONObject> jobs ;
List<RssFeedStructure> rssStr ;
private RssReaderListAdapter _adapter;
String sorti = "";
String mode = "";
Button sort_Btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rssfeedreaderactivity);
_rssFeedListView = (ListView)findViewById(R.id.rssfeed_listview);
sort_Btn = (Button)findViewById(R.id.sort);
sort_Btn.setText("Change Sorting Mode");
sort_Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(sorti.equalsIgnoreCase("")){
sorti = "sort";
}
if(sorti.equalsIgnoreCase("sort")){
sorti = "sort";
sort_Btn.setText("Change Reverse Mode");
RssFeedTask rssTask = new RssFeedTask();
rssTask.execute();
}
else if(sorti.equalsIgnoreCase("reverse")){
sorti = "reverse";
sort_Btn.setText("Change Normal Mode");
RssFeedTask rssTask = new RssFeedTask();
rssTask.execute();
}
else if(sorti.equalsIgnoreCase("normal")){
sort_Btn.setText("Change Sorting Mode");
RssFeedTask rssTask = new RssFeedTask();
rssTask.execute();
}
}
});
RssFeedTask rssTask = new RssFeedTask();
rssTask.execute();
}
private class RssFeedTask extends AsyncTask<String, Void, String> {
// private String Content;
private ProgressDialog Dialog;
String response = "";
@Override
protected void onPreExecute() {
Dialog = new ProgressDialog(RssFeedReaderActivity.this);
Dialog.setMessage("Rss Loading...");
Dialog.show();
}
@Override
protected String doInBackground(String... urls) {
try {
//String feed = "http://feeds.nytimes.com/nyt/rss/HomePage";
String feed = "http://feeds.feedburner.com/iamvijayakumar/androidtutorial";
XmlHandler rh = new XmlHandler();
rssStr = rh.getLatestArticles(feed);
} catch (Exception e) {
}
return response;
}
@Override
protected void onPostExecute(String result) {
if(sorti.equalsIgnoreCase("sort")){
sorti = "reverse";
Collections.sort(rssStr, new SortingOrder());
}else if(sorti.equalsIgnoreCase("reverse")){
sorti = "normal";
Comparator comp = Collections.reverseOrder();
Collections.sort(rssStr, new ReverseOrder());
}else{
sorti = "";
}
if(rssStr != null){
_adapter = new RssReaderListAdapter(RssFeedReaderActivity.this,rssStr);
_rssFeedListView.setAdapter(_adapter);
}
Dialog.dismiss();
}
}
}
REVERSEORDER.java
package com.rssfeed.helper;
import java.util.Comparator;
import org.json.JSONObject;
public class ReverseOrder implements Comparator<RssFeedStructure>{
public int compare(RssFeedStructure o1, RssFeedStructure o2) {
return (o2.getTitle()).compareTo(o1.getTitle());
}
}
EXP7:MULTITHREADING
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" >
<LinearLayout
android:id="@+id/con"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:includeFontPadding="false"
android:fontFamily="Georgia"
android:text="MULTITHREADING" />
</LinearLayout>
</RelativeLayout>
Java:
package com.example.multit;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout view;//view1;
TextView tv;//,tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
//tv1=(TextView)findViewById(R.id.textView2);
tv.setVisibility(0);
//tv1.setVisibility(0);
view=(LinearLayout)findViewById(R.id.con);
//view1=(LinearLayout)findViewById(R.id.con2);
startTimer();
}
TimerTask task=new TimerTask()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Random rnd=new Random();
int color=Color.argb(255,rnd.nextInt(256),rnd.nextInt(256),rnd.nextInt(256));
view.setBackgroundColor(color);
//view1.setBackgroundColor(color);
int color2=Color.argb(255, rnd.nextInt(256)+5, rnd.nextInt(256)+5, rnd.nextInt(256)+5);
tv.setVisibility(1);
tv.setTextColor(color2);
//tv1.setVisibility(1);
//tv1.setTextColor(color2);
}
});
}
};
private void startTimer()
{
Timer t=new Timer();
t.schedule(task,1000,1000);
}
@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;
}
}
Exp8:GPS
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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="149dp"
android:text="Button" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/button1"
android:layout_marginTop="74dp"
android:ems="10" />
</RelativeLayout>
Java:
Intent.java
package com.example.gps;

public class intent {


public intent(String actionLocationSourceSettings)
{

}
}
MainActivity.java
package com.example.gps;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.util.Log;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
@SuppressWarnings("unused")
public class MainActivity extends Activity implements LocationListener, OnClickListener {
private EditText editTextShowLocation;
private Button buttonGetLocation;
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextShowLocation = (EditText) findViewById(R.id.editText1);
buttonGetLocation = (Button) findViewById(R.id.button1);
buttonGetLocation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonGetLocationClick();
}
});
}
private void getCurrentLocation() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mobileLocation = location;
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
private void buttonGetLocationClick() {
getCurrentLocation(); // gets the current location and update mobileLocation variable
if (mobileLocation != null) {
locManager.removeUpdates(locListener); // This needs to stop getting the location data and
save the battery power.
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude:" +mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n"+ altitiude + "\n" + accuracy
+ "\n" + time);
}
else {
editTextShowLocation.setText("Sorry,locationisnotdetermined");
}
}
@Override
public void onClick(View arg0){
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status
, Bundle extras) {
// TODO Auto-generated method stub
}
}
EX9:SDCARD
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/ed"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:lines="5" android:gravity="top|left"
android:inputType="textMultiLine"
android:scrollHorizontally="false"
android:minWidth="10.0dip"
android:maxWidth="5.0dip"
android:layout_weight="1"/>
<Button
android:id="@+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Write Data to SD" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Clear Screen" />
<Button
android:id="@+id/button4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Read Data from SD" />
</LinearLayout>
JAVA:
package com.example.sdcard;
import android.app.Activity;
import android.os.Bundle;
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 implements OnClickListener {
EditText edittext;
Button b1, b2, b3, b4;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext = (EditText)findViewById(R.id.ed);
edittext.setLines(10);
b1 = (Button)findViewById(R.id.button1);
// b2 = (Button)findViewById(R.id.button2);
b3 = (Button)findViewById(R.id.button3);
b4 = (Button)findViewById(R.id.button4);
b1.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
MyFile file = new MyFile(v.getContext());
switch(id){
case R.id.button3:
if(!edittext.getText().toString().trim().equals("")){
file.writeToSandBox(edittext.getText().toString());
Toast.makeText(v.getContext(), "Content inserted", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(v.getContext(), "Please enter some contents for the file",
Toast.LENGTH_LONG).show();
}
break;
case R.id.button1:
edittext.setText(" ");
break;
case R.id.button4:
edittext.setText(file.readFromSandBox());
Toast.makeText(v.getContext(), "FILE Content", Toast.LENGTH_LONG).show();
break;
}
}
}
MY FILE.JAVA
package com.example.sdcard;
import java.io. BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
public class MyFile {
String TAG = "MyFile";
Context context;
public MyFile(Context context){
this.context = context;
}
public Boolean writeToSD(String text){
Boolean write_successful = false;
File root=null;
try {
// check for SDcard
root = Environment.getExternalStorageDirectory();
Log.i(TAG,"path.." +root.getAbsolutePath());
//check sdcard permission
if (root.canWrite()){
File fileDir = new File(root.getAbsolutePath());
fileDir.mkdirs();
File file= new File(fileDir, "samplefile.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write(text);
out.close();
write_successful = true;
}
} catch (IOException e) {
Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());
write_successful = false;
}
return write_successful;
}
public String readFromSD(){
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"samplefile.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString();
}
@SuppressLint("WorldReadableFiles")
@SuppressWarnings("static-access")
public Boolean writeToSandBox(String text){
Boolean write_successful = false;
try{
@SuppressWarnings("deprecation")
FileOutputStream fOut =
context.openFileOutput("samplefile.txt",context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(text);
osw.flush();
osw.close();
}catch(Exception e){
write_successful = false;
}
return write_successful;
}
public String readFromSandBox(){
String str ="";
String new_str = "";
try{
FileInputStream fIn = context.openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br=new BufferedReader(isr);
while((str=br.readLine())!=null)
{
new_str +=str;
System.out.println(new_str);
}
}catch(Exception e)
{
}
return new_str;
}
}
SDCARD MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sdcard"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sdcard.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
EX10:SMS
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Number : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/mobileNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter phone number"
android:phoneNumber="true" >
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message Body: "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/smsBody"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:hint="Enter message body"
android:inputType="textMultiLine"
android:lines="5" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="10" >
<Button
android:id="@+id/sendViaIntent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="SMS Intent" />
<Button
android:id="@+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="Send" />
</LinearLayout>
</LinearLayout>
Manifest.xml(include in manifest)
<uses-permission android:name="android.permission.SEND_SMS" />
MainActivity.java
package com.example.newsms;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.telephony.SmsManager;
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 {
private Button shareIntent;
private Button send;
private EditText phoneNo;
private EditText messageBody;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNo = (EditText) findViewById(R.id.mobileNumber);
messageBody = (EditText) findViewById(R.id.smsBody);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String number = phoneNo.getText().toString();
String sms = messageBody.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
shareIntent = (Button) findViewById(R.id.sendViaIntent);
shareIntent.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", messageBody.getText().toString());
sendIntent.setType("
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
EXP11:ALARM
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"
tools:context=".MainActivity">
<TimePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/alarmTimePicker"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="" android:id="@+id/alarmText"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_below="@+id/alarmToggle" />
<ToggleButton
android:id="@+id/alarmToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/alarmTimePicker"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:onClick="onToggleClicked"
android:text="Alarm On/Off" />
</RelativeLayout>
MainActivity.java
package com.example.alarm;
import java.util.Calendar;
//import com.example.lab11alaramclock.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static MainActivity inst;
private TextView alarmTextView;
public static MainActivity instance() {
return inst;
}
@Override
public void onStart() {
super.onStart();
inst = this;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
@SuppressWarnings("unused")
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
else {
alarmManager.cancel(pendingIntent);
setAlarmText("");
Log.d("MyActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
}
AlarmService.java
package com.example.alarm;
//import com.example.lab11alaramclock.R;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
@Override
public void onHandleIntent(Intent intent) {
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this,
MainActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new
NotificationCompat.Builder(this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launch
er).setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
}
AlarmReceiver.java
package com.example.alarm;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
MainActivity inst = MainActivity.instance();
inst.setAlarmText("Hi Please! Wake up! Wake up!");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new
ComponentName(context.getPackageName(),AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Alarm Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarm"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.alarm.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".AlarmService"
android:enabled="true" />
<receiver
android:name=".AlarmReceiver" />
</application>
</manifest>

S-ar putea să vă placă și