This is android Tutorial Blog. Learn Here Android Application Development with Shivendra Srivastwa.
Thursday, 18 December 2014
Tuesday, 14 October 2014
android-database-example
Android Data Base
In Android Device sqlite database is use to store information. i am going to give very example to maintain all crucial operation on database like database creation table creation record insertion, deletion, updation and view.
Code for activity_main.xml file
- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1"
android:layout_width="fill_parent" android:layout_height="fill_parent">
- <LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<TextView android:id="@+id/textView1" android:layout_width="195dp"
android:layout_height="wrap_content" android:text="Plz
Fill This Form"
android:textAppearance="?android:attr/textAppearanceLarge" />
- <EditText android:id="@+id/editText1"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:ems="10" android:hint="name" android:inputType="textPersonName">
<requestFocus />
</EditText>
<EditText android:id="@+id/editText2" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10"
android:hint="phno" android:inputType="phone" />
<EditText android:id="@+id/editText3" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10"
android:hint="emailid" android:inputType="textEmailAddress"
android:text="" />
<EditText android:id="@+id/editText4" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10"
android:hint="add" android:inputType="textPostalAddress"
/>
<Button android:id="@+id/button1" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Register New Record"
/>
<Button android:id="@+id/button2" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="View
All Record" />
<Button android:id="@+id/button5" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="UPDATE YOUR EXisting Record" />
- <TableRow android:id="@+id/tableRow1"
android:layout_width="match_parent" android:layout_height="wrap_content">
<Button android:id="@+id/button3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Delete By ID"
/>
<EditText android:id="@+id/editText5" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:ems="10"
android:hint="Enter Id to Update and Delete
Record" android:inputType="number" />
</TableRow>
<Button android:id="@+id/button4" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Get
By Id" />
</LinearLayout>
</ScrollView>
Source code for MainActivity.java file:
package com.apsmind.ddbconnect;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.InputFilter.LengthFilter;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText n1,phno,e1,add,edit;
Button b1,b2,b3,b4,b5;
TextView t1;
Record record=new Record(MainActivity.this);;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.textView1);
n1=(EditText)findViewById(R.id.editText1);
phno=(EditText)findViewById(R.id.editText2);
e1=(EditText)findViewById(R.id.editText3);
add=(EditText)findViewById(R.id.editText4);
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);
edit=(EditText)findViewById(R.id.editText5);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name=n1.getText().toString();
String phone=phno.getText().toString();
String email=e1.getText().toString();
String address=add.getText().toString();
SQLiteDatabase db=record.getWritableDatabase();/*to open database in writable format*/
ContentValues values= new ContentValues();/*a class whoese object helps to insert values in table*/
values.put(Record.Col1_name, name);
values.put(Record.Col3_password, phone);
values.put(Record.Col2_email,email );
values.put(Record.Col4_address, address);
db.insert(Record.Table_name, null, values);//null stands for null hacker(insert null for not defined positions
n1.setText("");
phno.setText("");
e1.setText("");
add.setText("");
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,Activity1.class);
startActivity(i);
}
});
//get by id
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
SQLiteDatabase db=record.getWritableDatabase();
try{
db.delete(Record.Table_name, BaseColumns._ID+"="+id, null);
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
Toast.makeText(MainActivity.this,"deleted", Toast.LENGTH_SHORT).show();
}
});
b5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
String name=n1.getText().toString();
String phone=phno.getText().toString();
String email=e1.getText().toString();
String address=add.getText().toString();
try{
SQLiteDatabase db=record.getWritableDatabase();/*to open database in writable format*/
ContentValues values= new ContentValues();/*a class whoese object helps to insert values in table*/
values.put(Record.Col1_name, name);
values.put(Record.Col3_password, phone);
values.put(Record.Col2_email,email );
values.put(Record.Col4_address, address);
db.update(Record.Table_name, values, BaseColumns._ID+"="+id, null);
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
});
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
try{
SQLiteDatabase db=record.getReadableDatabase();
Cursor mCursor =
db.query( Record.Table_name,null, BaseColumns._ID+"="+id, null,
null, null, null, null);
if (mCursor != null) {
while(mCursor.moveToNext())
{
n1.setText(mCursor.getString(1));
phno.setText(mCursor.getString(2));
e1.setText(mCursor.getString(3));
add.setText(mCursor.getString(4));
}
}
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).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;
}
}
Create another Record.java file.
package com.apsmind.ddbconnect;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.provider.OpenableColumns;
import android.util.Log;
public class Record extends SQLiteOpenHelper
{
public static final String DB_name = "Student.db";
public static final int DB_version =2;
public static final String Table_name ="Info";
public static final String Col1_name = "Name";
public static final String Col2_email ="Email";
public static final String Col3_password ="Password";
public static final String Col4_address = "Address";
String query;
public Record(Context context)
{
super(context, DB_name, null, DB_version);/*null being cursor position*/
}
@Override
public void onCreate(SQLiteDatabase db)
{
query = "CREATE TABLE " + Table_name + "( " + BaseColumns._ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Col1_name + " TEXT, "
+ Col2_email + " TEXT," +Col3_password+ " not null," +Col4_address+ " text not null );";
Log.d("Eventsdata", "onCreate" +query);
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
{
if (oldVersion >= newVersion)
return;/*code to apply if database is sent from one version to another*/
String sql = null;
if (oldVersion == 1)
sql = "alter table " + Table_name + " add note text;";
if (oldVersion == 2)
sql = "";
Log.d("EventsData", "onUpgrade : " + sql);
if (sql != null)
db.execSQL(sql);
}
}
}
Create Another Activity for view all record:-
source code for .xml file:
- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1"
android:layout_width="fill_parent" android:layout_height="fill_parent">
- <LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<TextView android:id="@+id/textView1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</ScrollView>
package com.apsmind.ddbconnect;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.widget.TextView;
public class Activity1 extends Activity {
TextView t1;
Record eventsdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity1);
t1=(TextView)findViewById(R.id.textView1);
eventsdata =new Record(this);
SQLiteDatabase db=eventsdata.getReadableDatabase();//event is an entry of database table
Cursor cursor=db.query(Record.Table_name, null, null, null, null, null, null);
StringBuilder stb=new StringBuilder("Saved Events :\n\n");
while(cursor.moveToNext())
{
long id=cursor.getLong(0);
String name=cursor.getString(1);
String email=cursor.getString(2);
String password=cursor.getString(3);
String address=cursor.getString(4);
stb.append(id +": name--: " + name +",\n"+ " email--:" + email +",\n"+ " password--:" + password +",\n"+ " address--:" + address + "\n\n");
}
t1.setText(stb);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity1, menu);
return true;
}
}
Saturday, 24 May 2014
Image-Gallery-Android-Example
ANDROID IMAGE GALLERY
ImageGallery : image gallery is use to show images in sequence. it found in transition.
Create an android project.
step 1 :
open res/layout/activity_main.xml and write following code.
Layout xml file code:
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="vertical"
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" >
android:id="@+id/gallery1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Step 2: create attrs.xml file under res/values folder.
Step 3: paste some images under res/drawable folder.
Now your application directory structure like this.
step 4:- java source code
package com.example.imgproject;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
int imglist[] = {R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e};
Gallery gal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gal = (Gallery)findViewById(R.id.gallery1);
ImgAdp iadp = new ImgAdp(MainActivity.this);
gal.setAdapter(iadp);
gal.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView arg0, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "img "+pos+"click", Toast.LENGTH_LONG).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;
}
class ImgAdp extends BaseAdapter
{
Context mcon;
int itemBackground;
public ImgAdp(Context cont)
{
mcon =cont;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return imglist.length;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mcon);
imageView.setImageResource(imglist[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
}
else
{
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
Monday, 3 March 2014
android-live-wallpaper
Android Live Wallpaper Example
In Android Live Wallpaper Creation we have to use WallpaperService class.
WallpaperService :
A wallpaper service is responsible for showing a live
wallpaper behind applications that would like to sit on top of it. This service
object itself does very little -- its only purpose is to generate instances of
But WallpaperService have several instance to maintain each instance We use Engine class.
WallpaperService.Engine
as needed. Implementing a wallpaper thus involves subclassing from this,
subclassing an Engine implementation, and implementing onCreateEngine()
to return a new instance of your engine.But WallpaperService have several instance to maintain each instance We use Engine class.
WallpaperService.Engine :
The actual implementation of a wallpaper. A wallpaper service may have multiple
instances running (for example as a real wallpaper and as a preview), each of
which is represented by its own Engine instance. You must implement
onCreateEngine()
to return your concrete Engine implementation.
Now Create an Android project name Android-Live-Wallpaper. Your application directory is shown below.
put two image named background.png and fish.png in drawable folder.
Now Source Code for Activity java file:
package com.example.livewallpaper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.view.SurfaceHolder;
public class LiveWallpaperService extends WallpaperService
{
int x,y;
public void onCreate()
{
super.onCreate();
}
public void onDestroy()
{
super.onDestroy();
}
public Engine onCreateEngine()
{
return new MyWallpaperEngine();
}
class MyWallpaperEngine extends Engine
{
private final Handler handler = new Handler();
private final Runnable drawRunner = new Runnable() {
@Override
public void run() {
draw();
}
};
private boolean visible = true;
public Bitmap image1,backgroundImage;
MyWallpaperEngine()
{
// get the fish and background image references
image1 = BitmapFactory.decodeResource(getResources(),R.drawable.fish);
backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
x=-130; // initialize x position
y=200; // initialize y position
}
public void onCreate(SurfaceHolder surfaceHolder)
{
super.onCreate(surfaceHolder);
}
@Override
public void onVisibilityChanged(boolean visible)
{
this.visible = visible;
// if screen wallpaper is visible then draw the image otherwise do not draw
if (visible)
{
handler.post(drawRunner);
}
else
{
handler.removeCallbacks(drawRunner);
}
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder)
{
super.onSurfaceDestroyed(holder);
this.visible = false;
handler.removeCallbacks(drawRunner);
}
public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels)
{
draw();
}
void draw()
{
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try
{
c = holder.lockCanvas();
// clear the canvas
c.drawColor(Color.BLACK);
if (c != null)
{
// draw the background image
c.drawBitmap(backgroundImage,0,150, null);
// draw the fish
c.drawBitmap(image1, x,y, null);
// get the width of canvas
int width=c.getWidth();
// if x crosses the width means x has reached to right edge
if(x>width+100)
{
// assign initial value to start with
x=-130;
}
// change the x position/value by 1 pixel
x=x+1;
}
}
finally
{
if (c != null)
holder.unlockCanvasAndPost(c);
}
handler.removeCallbacks(drawRunner);
if (visible)
{
handler.postDelayed(drawRunner, 10); // delay 10 mileseconds
}
}
}
}
Create a xml file named mywallpaper.xml with in xml folder under resource folder.
Code for mywallpaper.xml file:-
xmlns:android="http://schemas.android.com/apk/res/android"
android:thumbnail="@drawable/fish"
android:description="@string/wallpaper_description"
/>
code for string.xml file that present in style folder under res:
Code for manifest.xml file
package="com.example.livewallpaper"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:name="android.software.live_wallpaper"
android:required="true" >
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="LiveWallpaperService"
android:enabled="true"
android:label="Wallpaper Example "
android:permission="android.permission.BIND_WALLPAPER" >
android:name="android.service.wallpaper"
android:resource="@xml/mywallpaper" >
Now your Application is ready for test. For test on Emulator you hold right click on home screen. Then a dialogue menu appear then choose wallpaper.
After ward new dialogue menu appear in which you select live wallpaper.
Now you choose your own live paper.
Now Set As wallpaper after clicking set wallpaper.......
You all learner must comment How is it?
thanks... Keep learning with Shivendra (Android Trainer at APSMIND Technology...).
Saturday, 8 February 2014
SimInformation
Telephony Manager
Telephony manager is used to get Telephony information like SIM Information.In given example i have get several information about SIM.
Using This application we can get all SIM related information.
Required Permission: add this permission in manifest file
android.permission.READ_PHONE_STATE
Create an application named SimInfoApplication.
Step1: code for MainActivity.java file
package android.shivendra.siminfoapplicationtelephonymgr;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
String phoneDetails;
ArrayList list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list= new ArrayList();
TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
//Get IMEI Number of Phone
String IMEINumber=tm.getDeviceId();
list.add("IMEI NUMBER "+IMEINumber);
//Get Subscriber ID
String subscriberID=tm.getDeviceId();
//Get SIM Serial Number
String SIMSerialNumber=tm.getSimSerialNumber();
list.add("SIM Serial Number "+SIMSerialNumber);
//Get Network Country ISO Code
String networkCountryISO=tm.getNetworkCountryIso();
//Get SIM Country ISO Code
String SIMCountryISO=tm.getSimCountryIso();
//Get the device software version
String softwareVersion=tm.getDeviceSoftwareVersion();
list.add("Software version "+softwareVersion);
//Get the Voice mail number
String voiceMailNumber=tm.getVoiceMailNumber();
//Get the Phone Type CDMA/GSM/NONE
int phoneType=tm.getPhoneType();
switch (phoneType)
{
case (TelephonyManager.PHONE_TYPE_CDMA):
// your code
break;
case (TelephonyManager.PHONE_TYPE_GSM):
// your code
break;
case (TelephonyManager.PHONE_TYPE_NONE):
// your code
break;
}
//Find whether the Phone is in Roaming, returns true if in roaming
boolean isRoaming=tm.isNetworkRoaming();
if(isRoaming)
phoneDetails+="\nIs In Roaming : "+"YES";
else
phoneDetails+="\nIs In Roaming : "+"NO";
//Get the SIM state
int SIMState=tm.getSimState();
switch(SIMState)
{
case TelephonyManager.SIM_STATE_ABSENT :
Toast.makeText(MainActivity.this, "No Sim Available", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED :
Toast.makeText(MainActivity.this, "Sim card Locked by network", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED :
Toast.makeText(MainActivity.this, "Sim card Locked by User", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED :
Toast.makeText(MainActivity.this, "Sim card Locked PUK Required", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.SIM_STATE_READY :
Toast.makeText(MainActivity.this, "Sim card Ready to work", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.SIM_STATE_UNKNOWN :
// your code
break;
}
ListView lv = (ListView)findViewById(R.id.listView1);
ArrayAdapter adp = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1,list);
lv.setAdapter(adp);
}
@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;
}
}
Step2: Source code for activity_main.xml file
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
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" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Mobile Information" />
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
Run Your Application and Test It
Note:
You can download complete source code here
Subscribe to:
Posts (Atom)