Android Examples
Tuesday, December 1, 2015
Friday, November 27, 2015
spinner and round corners
round_color_for_spinner.xml (drawable)
<?xml version="1.0" encoding="utf-8"?><!-- res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="@color/white" />
<stroke
android:width="3dip"
android:color="@color/light_gray" />
<corners
android:bottomLeftRadius="15dp"
android:bottomRightRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp" />
</shape>
Spinners
public class MainActivity extends Activity
{
private Spinner project;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// init view
project=(Spinner)findViewById(R.id.SpinnerProject);
List<String> list = new ArrayList<String>();
list.add("Pro-XXX-XXX");
list.add("TRN-XXX-XXX");
list.add("SRV-XXX-XXX");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.spinner_item, list);
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
project.setAdapter(adapter);
}
}
use spinner in Colors
spRespons.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int arg2, long arg3) {
((TextView) parent.getChildAt(0)).setTextColor(Color.parseColor(getResources().getString(R.color.GRENN_COLOR)));
((TextView) parent.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_SP, 12F);
((TextView) parent.getChildAt(0)).setTypeface(ARABIC_FONT);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dynamically change the content of spinner
Spinner spinner = (Spinner)findViewById(R.id.mySpinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, android.R.id.text1);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinnerAdapter.add("value");
spinnerAdapter.notifyDataSetChanged();
Thursday, November 12, 2015
canvas reading
As I mentioned before, drawing on Canvas is usually done in performance intensive applications like video games.
There are 2 ways to draw things on a canvas in Android - the first one is to draw on a View, the second way is to draw on a SurfaceView.
Drawing on a View is more suitable when your application does not need to update the screen really fast. It can be used for a game of chess or a similar slow-paced application. The Android system provides a Canvas object that will display our graphics in a View.
To use this method, you need to create a custom class that extends View and has the onDraw() callback method. The onDraw() method is called by Android to tell your View to update its graphics. This is where you can put all the code that draws things using the Canvas type object that is passed as the parameter to this function. The class has a set of methods for drawing that you can use, which include drawBitmap(), drawRect(), drawText() and others.
Note, however, that Android will only call onDraw() of your View if it is necessary. If you decide your application is ready to be drawn, you need to call the View's invalidate() method. This tells Android that the contents should be redrawn. However, using this method does not guarantee that the redraw will occur instantly.
What's interesting is that other classes also have draw() method, which lets you take those Drawables and pass them onto the Canvas to be drawn there.
The other way to draw on a canvas is using the SurfaceView class.
This subclass of View lets us create a dedicated drawing surface inside a View, which is treated just like any other View in theapplication. This surface is offered a separate thread where all the drawing happens, so our main application thread does not hold it back from updating.
In this case you will also need to create a custom class. This time it extends SurfaceView. It should also implement SurfaceHolder.Callback class. This subclass is used to inform you when the underlying Surface dispatches an event, for example, when it is created or changed.
The secondary thread should be defined inside your SurfaceView class. You shouldn't handle the Surface object directly - it can be done using SurfaceHandler. When the SurfaceView object is initialized, you can access the SurfaceHolder object using getHolder() method. Then you tell SurfaceHolder that you want to receive SurfaceHolder callbacks from SurfaceHolder.Callback by calling addCallback(this).
You can then override all the SurfaceHolder.Callback methods inside your SurfaceView class. Those methods are surfaceChanged, surfaceCreated and surfaceDestroyed.
To draw to the SurfaceCanvas from withing your secondary thread, pass the SurfaceHandler object to the thread and retrieve the Canvas with lockCanvas(). You can then take and use the Canvas to draw on it. When you're done drawing, call unlockCanvasAndPost(), passing it your Canvas object. The Surface then draws the Canvas. You need to lock and unlock every time you want to update the screen.
That's all for today. We haven't written a single line of code today but hopefully you now understand the basic mechanism behind drawing graphics in Android. The code itself is pretty self explanatory and will be shown in future tutorials as practical examples.
Thanks for reading!
Transition
In this tutorial we will take a look at the TransitionDrawable class, which lets us display a smooth cross-fade effect between two pictures.
Firstly, we'll need to add 2 pictures to the drawable directory of the project. In my case, they are sample1.jpg and sample2.jpg, and I put both of them in res/drawable-hdpi/ directory.
Add an xml file in the same directory, call it transition.xml. Here we will add a transition node with 2 item nodes inside, each representing an image:
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/d1"/>
<item android:drawable="@drawable/d8"/>
</transition>
package com.example.trans;
import android.content.res.Resources;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
private ImageView image;
private TransitionDrawable trans;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView)findViewById(R.id.image);
Resources res = this.getResources();
trans = (TransitionDrawable)res.getDrawable(R.drawable.transition);
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
image.setImageDrawable(trans);
trans.reverseTransition(1000);
}
});
}
}
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/d1"
/>
</LinearLayout>
Friday, November 6, 2015
Intents Basic Example Between screens
MainActivity.java
package bhanu.firstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
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 ActionBarActivity {
Button b1,b2,st;
EditText et1,et2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
st=(Button)findViewById(R.id.button3);
et1=(EditText)findViewById(R.id.editText1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String str1=et1.getText().toString();
Intent in=new Intent(MainActivity.this,Second.class);
in.putExtra("data", str1);
startActivity(in);
Toast.makeText(getApplicationContext(), "you Clicked on submit", 100).show();
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "You clicked on cancel", 1000).show();
}
});
st.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in1=new Intent(MainActivity.this,Two.class);
startActivity(in1);
}
});
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package bhanu.firstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
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 ActionBarActivity {
Button b1,b2,st;
EditText et1,et2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
st=(Button)findViewById(R.id.button3);
et1=(EditText)findViewById(R.id.editText1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String str1=et1.getText().toString();
Intent in=new Intent(MainActivity.this,Second.class);
in.putExtra("data", str1);
startActivity(in);
Toast.makeText(getApplicationContext(), "you Clicked on submit", 100).show();
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "You clicked on cancel", 1000).show();
}
});
st.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in1=new Intent(MainActivity.this,Two.class);
startActivity(in1);
}
});
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Second.java
package bhanu.firstapp;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.widget.TextView;
import android.widget.Toast;
public class Second extends Activity
{
//TextView t1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String str= getIntent().getExtras().getString("data");
Toast.makeText(getApplicationContext(), str, 500).show();
TextView t1=new TextView(getApplicationContext());
t1.setTextColor(Color.YELLOW);
t1.setText("welcome"+ " " +str);
setContentView(t1);
}
}
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="bhanu.firstapp.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="28dp"
android:text="@string/usn" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="19dp"
android:ems="10"
android:inputType="textPassword" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignLeft="@+id/textView1"
android:text="@string/pwd" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_alignRight="@+id/editText1"
android:text="@string/can" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:text="@string/sub" />
<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_toRightOf="@+id/textView1"
android:ems="10" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="46dp"
android:layout_toRightOf="@+id/textView2"
android:text="@string/st" />
</RelativeLayout>
two.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" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Wednesday, October 7, 2015
Introduction of How Android Works for Java Programmers
Android development is current buzz in Java programming world. It's the
Android, which keeps Java in the fore front from last couple of years. Now, How
important is to understand or learn Android for Java programmers? Well it
depends, if you like application development and want to reach mass, Android
offers that opportunity to you. Millions of Android phones are available and
they are keep increasing, with pace, much higher than IPhone or iOS. What all
these means is, it does make a lot of sense to learn Android programming for
Java programmer, and this article is about that, but this is also a one of
the good reason to learn Java programming.
This tutorial will give you basic idea of How
Android works? not detailed but a good overview. One distinct advantage
Java programmers has over others is that Android API is much like Java API,
though Android doesn't support all classes available in J2SE SDK, it supports
critical ones. Another advantage is that, you can use same tools e.g. IDE like
Eclipse to develop Android applications, Google provides Eclipse plug-in for
Android development. On opposite, if you want to go for iOS development, A steep learning curve with
Objective C and iOS SDK waits you. I think it make more sense for a C++
programmer to do Objective C and iOS, than a Java Programmer. So classic battle
of Java vs C++ still continues with Smartphone application development. Any
way, let's come to the topic of How Android works internally. . If you are
looking for some good books to start with Android, you can also check out Professional Android 4 Application Development and Ian F. Darwin’s Android Cookbook.
How Android works
As I said Android uses Java for application development. So you can code
your Android apps using Java API provided by Google, and it compiles into class
files. Similarity ends here, Android doesn't use Java Virtual machine (JVM) for
executing class files, instead it uses Dalvik
virtual machine, which is not a true JVM and doesn't operate on Java byte
code. In order to run on Dalvik Virtual machines, class files are further
compiled into Dalvik Executable or DEX
format. After conversion to DEX format, class files along with other
resources are bundled into Android Package (APK) for
distribution and installation into various devices. Key thing to know is that,
Dalvik VM is based on subset of the Apache Harmony Project for its core class
library, which means it doesn't support all J2SE API. If you are using Eclipse
IDE for coding Android Apps, then you don't need to worry much because, it will
help you with code completion. Now let's see How Android Application runs on device?How Android apps runs on Device
If you are familiar with Linux and concept of process, then it's easy to
understand how android applications runs. By default, Each Android application
is assigned a unique user id by the Android operating system. After starting
android application, they run on there own process, inside there own virtual
machine. Android operating system manages starting and shutting down the
application process, whenever required. This means, each android application
runs in isolation with other, but they can certainly request access to hardware
and other system resources. If you are familiar with mobile application
development, may be in J2ME, then you may know about permissions. So when an
android application is installed or started, it request necessary permission
required to connect internet, phone book and other system resource. User
explicitly provides grant these permissions, or it may deny. All these
permissions are defined in manifest file of Android application. Unlike Java
Manifest file, Android manifest is an XML file, which lists all the
components of apps, and settings for those components. Four major components of
Android application development is Activities, Services, Content Providers and Broadcast Receivers. Activity is most common of them, as it represent a single
screen in Android Application. For example, in an Android Game, you can have
multiple screens for login, high score, instructions and game screen. Each of
these screen represent different Activities inside
your app. Similar to Java, good thing about Android is that it manages certain
task on behalf of developer, one of them is creating activity object.
Activities are managed by System, when you want to start an activity, you call startActivity() method
which takes an Intent object. In response to this call, System can either
create new activity object or reuse an existing one. Just like Garbage collection in Java,
manages a critical task or reclaiming memory, Android manages starting,
stopping, creating and destroying of apps by themselves. You may think it's
restrictive, but it's not. Android provides life-cycle events, which you can
override to interact with this process.
That's all on How Android works.
Android is definitely worth learning for Java programmer, as it uses
Java, you can reuse your existing knowledge of Java programming techniques, design patterns and best practices to code a good
android app. Of course, you need to adapt some Android specific things like,
but those will come along. So, what are you waiting for, go and explore more
about Android and write an Android HelloWorld application. Finally you can also
take a look some of the best book to start with Android development, Professional Android 4 Application Development and Android Cookbook by Ian F.
Darwin.
Wednesday, October 30, 2013
Android SQLite Database Tutorial
Android provides several
ways to store user and app data. SQLite is one way of storing user data. SQLite
is a very light weight database which comes with Android OS. In this tutorial
I’ll be discussing how to write classes to handle all SQLite operations.
In this tutorial I am
taking an example of storing user contacts in SQLite database. I am using a
table called Contacts to store user contacts. This table contains three columns id (INT), name (TEXT),phone_number(TEXT).
Contacts
Table Structure
Writing
Contact Class
Before
you go further you need to write your Contact class with all getter and setter
methods to maintain single contact as an object.
Contact.java
package com.androidkiran.androidsqlite;
public class Contact
{
//private
variables
int _id;
String
_name;
String
_phone_number;
//
Empty constructor
public Contact(){
}
//
constructor
public Contact(int id,
String name, String _phone_number){
this._id
= id;
this._name
= name;
this._phone_number
= _phone_number;
}
//
constructor
public Contact(String
name, String _phone_number){
this._name
= name;
this._phone_number
= _phone_number;
}
//
getting ID
public int getID(){
return this._id;
}
//
setting id
public void setID(int id){
this._id
= id;
}
//
getting name
public String
getName(){
return this._name;
}
//
setting name
public void setName(String
name){
this._name
= name;
}
//
getting phone number
public String
getPhoneNumber(){
return this._phone_number;
}
//
setting phone number
public void setPhoneNumber(String
phone_number){
this._phone_number
= phone_number;
}
}
Writing
SQLite Database Handler Class
We
need to write our own class to handle all database CRUD(Create, Read, Update
and Delete) operations.
1. Create a new project by going to File
⇒ New
Android Project.
2. Once the project is created, create a new class in your project src directory and name it asDatabaseHandler.java ( Right Click on src/package ⇒ New ⇒ Class)
3. Now extend your DatabaseHandler.java class from SQLiteOpenHelper.
2. Once the project is created, create a new class in your project src directory and name it asDatabaseHandler.java ( Right Click on src/package ⇒ New ⇒ Class)
3. Now extend your DatabaseHandler.java class from SQLiteOpenHelper.
public class
DatabaseHandler
extends SQLiteOpenHelper { |
4. After extending your class from SQLiteOpenHelper you need to
override two methods onCreate() andonUpgrage()
onCreate() – These is where we need to write create table statements. This is called when database is created.
onUpgrade() – This method is called when database is upgraded like modifying the table structure, adding constraints to database etc.,
onCreate() – These is where we need to write create table statements. This is called when database is created.
onUpgrade() – This method is called when database is upgraded like modifying the table structure, adding constraints to database etc.,
public class DatabaseHandler
extends SQLiteOpenHelper {
//
All Static variables
//
Database Version
private static final int DATABASE_VERSION
= 1;
//
Database Name
private static final String DATABASE_NAME =
"contactsManager";
//
Contacts table name
private static final String TABLE_CONTACTS = "contacts";
//
Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context,
DATABASE_NAME, null, DATABASE_VERSION);
}
//
Creating Tables
@Override
public void onCreate(SQLiteDatabase
db) {
String
CREATE_CONTACTS_TABLE = "CREATE TABLE " +
TABLE_CONTACTS + "("
+
KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + "
TEXT,"
+
KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
//
Upgrading database
@Override
public void onUpgrade(SQLiteDatabase
db, int oldVersion, int newVersion)
{
//
Drop older table if existed
db.execSQL("DROP
TABLE IF EXISTS " + TABLE_CONTACTS);
//
Create tables again
onCreate(db);
}
⇒All CRUD Operations
(Create, Read, Update and Delete)
Now
we need to write methods for handling all database read and write operations.
Here we are implementing following methods for our contacts table.
// Adding
new contact
public void addContact(Contact
contact) {}
// Getting
single contact
public Contact
getContact(int id) {}
// Getting
All Contacts
public List<Contact>
getAllContacts() {}
// Getting
contacts Count
public int getContactsCount()
{}
//
Updating single contact
public int updateContact(Contact
contact) {}
//
Deleting single contact
public void deleteContact(Contact
contact) {}
⇒Inserting new Record
The addContact() method
accepts Contact object as parameter. We need to build ContentValues parameters
using Contact object. Once we inserted data in database we need to close the
database connection.
addContact()
//Adding new Contact
public void addContact(Contact
contact) {
SQLiteDatabase
db = this.getWritableDatabase();
ContentValues
values = new ContentValues();
values.put(KEY_NAME,
contact.getName()); // Contact Name
values.put(KEY_PH_NO,
contact.getPhoneNumber()); // Contact Phone Number
//
Inserting Row
db.insert(TABLE_CONTACTS,
null, values);
db.close();
// Closing database connection
}
⇒Reading Row(s)
The
following method getContact() will
read single contact row. It accepts id as parameter and will return the matched
row from the database.
Get Contact()
//Getting
single contact
public Contact
getContact(int id) {
SQLiteDatabase
db = this.getReadableDatabase();
Cursor
cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME,
KEY_PH_NO }, KEY_ID + "=?",
new String[]
{ String.valueOf(id) }, null, null, null, null);
if (cursor
!= null)
cursor.moveToFirst();
Contact
contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2));
//
return contact
return contact;
}
getAllContacts() will
return all contacts from database in array list format of Contact class type.
You need to write a for loop to go through each contact.
getAllContacts()
//Getting
all contacts
public List<Contact>
getAllContacts() {
List<Contact>
contactList = new ArrayList<Contact>();
//
Select All Query
String
selectQuery = "SELECT * FROM " +
TABLE_CONTACTS;
SQLiteDatabase
db = this.getWritableDatabase();
Cursor
cursor = db.rawQuery(selectQuery, null);
//
looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
Contact
contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
//
Adding contact to list
contactList.add(contact);
}
while (cursor.moveToNext());
}
//
return contact list
return contactList;
}
getContactsCount() will
return total number of contacts in SQLite database.
getContactsCount()
// Getting Contacts count
public int getContactsCount()
{
String
countQuery = "SELECT * FROM " +
TABLE_CONTACTS;
SQLiteDatabase
db = this.getReadableDatabase();
Cursor
cursor = db.rawQuery(countQuery, null);
cursor.close();
//
return count
return cursor.getCount();
}
⇒Updating Record
updateContact() will
update single contact in database. This method accepts Contact class object as
parameter.
updateContact()
//
Updating single contact
public int updateContact(Contact
contact) {
SQLiteDatabase
db = this.getWritableDatabase();
ContentValues
values = new ContentValues();
values.put(KEY_NAME,
contact.getName());
values.put(KEY_PH_NO,
contact.getPhoneNumber());
//
updating row
return db.update(TABLE_CONTACTS,
values, KEY_ID + " = ?",
new String[]
{ String.valueOf(contact.getID()) });
}
⇒Deleting Record
deleteContact() will
delete single contact from database.
deleteContact()
//Deleting single contact.
public void deleteContact(Contact
contact) {
SQLiteDatabase
db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS,
KEY_ID + " = ?",
new String[]
{ String.valueOf(contact.getID()) });
db.close();
}
Complete
DatabaseHandler.java Code:
DatabaseHandler.java
package com.androidkiran.androidsqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler
extends SQLiteOpenHelper {
//
All Static variables
//
Database Version
private static final int DATABASE_VERSION
= 1;
//
Database Name
private static final String
DATABASE_NAME = "contactsManager";
//
Contacts table name
private static final String
TABLE_CONTACTS = "contacts";
//
Contacts Table Columns names
private static final String
KEY_ID = "id";
private static final String
KEY_NAME = "name";
private static final String
KEY_PH_NO = "phone_number";
public DatabaseHandler(Context
context) {
super(context,
DATABASE_NAME, null, DATABASE_VERSION);
}
//
Creating Tables
@Override
public void onCreate(SQLiteDatabase
db) {
String
CREATE_CONTACTS_TABLE = "CREATE TABLE " +
TABLE_CONTACTS + "("
+
KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + "
TEXT,"
+
KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
//
Upgrading database
@Override
public void onUpgrade(SQLiteDatabase
db, int oldVersion, int newVersion)
{
//
Drop older table if existed
db.execSQL("DROP
TABLE IF EXISTS " + TABLE_CONTACTS);
//
Create tables again
onCreate(db);
}
/**
*
All CRUD(Create, Read, Update, Delete) Operations
*/
//
Adding new contact
void addContact(Contact
contact) {
SQLiteDatabase
db = this.getWritableDatabase();
ContentValues
values = new ContentValues();
values.put(KEY_NAME,
contact.getName()); // Contact Name
values.put(KEY_PH_NO,
contact.getPhoneNumber()); // Contact Phone
//
Inserting Row
db.insert(TABLE_CONTACTS,
null, values);
db.close();
// Closing database connection
}
//
Getting single contact
Contact
getContact(int id) {
SQLiteDatabase
db = this.getReadableDatabase();
Cursor
cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME,
KEY_PH_NO }, KEY_ID + "=?",
new String[]
{ String.valueOf(id) }, null, null, null, null);
if (cursor
!= null)
cursor.moveToFirst();
Contact
contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2));
//
return contact
return contact;
}
//
Getting All Contacts
public List<Contact>
getAllContacts() {
List<Contact>
contactList = new ArrayList<Contact>();
//
Select All Query
String
selectQuery = "SELECT * FROM " +
TABLE_CONTACTS;
SQLiteDatabase
db = this.getWritableDatabase();
Cursor
cursor = db.rawQuery(selectQuery, null);
//
looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
Contact
contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
//
Adding contact to list
contactList.add(contact);
}
while (cursor.moveToNext());
}
//
return contact list
return contactList;
}
//
Updating single contact
public int updateContact(Contact
contact) {
SQLiteDatabase
db = this.getWritableDatabase();
ContentValues
values = new ContentValues();
values.put(KEY_NAME,
contact.getName());
values.put(KEY_PH_NO,
contact.getPhoneNumber());
//
updating row
return db.update(TABLE_CONTACTS,
values, KEY_ID + " = ?",
new String[]
{ String.valueOf(contact.getID()) });
}
//
Deleting single contact
public void deleteContact(Contact
contact) {
SQLiteDatabase
db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS,
KEY_ID + " = ?",
new String[]
{ String.valueOf(contact.getID()) });
db.close();
}
//
Getting contacts Count
public int getContactsCount()
{
String
countQuery = "SELECT * FROM " +
TABLE_CONTACTS;
SQLiteDatabase
db = this.getReadableDatabase();
Cursor
cursor = db.rawQuery(countQuery, null);
cursor.close();
//
return count
return cursor.getCount();
}
}
Usage:
AndroidSQLiteTutorialActivity
package com.androidkiran.androidsqlite;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AndroidSQLiteTutorialActivity
extends Activity {
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHandler
db = new DatabaseHandler(this);
/**
*
CRUD Operations
*
*/
//
Inserting Contacts
Log.d("Insert:
", "Inserting ..");
db.addContact(new Contact("Ravi",
"9100000000"));
db.addContact(new Contact("Srinivas",
"9199999999"));
db.addContact(new Contact("Tommy",
"9522222222"));
db.addContact(new Contact("Karthik",
"9533333333"));
//
Reading all contacts
Log.d("Reading:
", "Reading all contacts..");
List<Contact>
contacts = db.getAllContacts();
for (Contact
cn : contacts) {
String
log = "Id: "+cn.getID()+" ,Name: " +
cn.getName() + " ,Phone: " + cn.getPhoneNumber();
//
Writing Contacts to log
Log.d("Name:
", log);
}
}
}
Subscribe to:
Comments (Atom)