Tuesday, 9 September 2014

SqliteDatabase



About SQLite:
                     SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. In addition it requires only little memory at runtime approx 250kb. 


SQLite supports the data types TEXT, INTEGER, REAL.  All other types must be converted into one of these fields before saving them in the database.

SQLiteDatabase is available on every Android device . Using an SQLiteDatabase in Android does not require any database setup or administration.



What is SQLite?
SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. In addition it requires only little memory at runtime (approx. 250 KByte).

SQLite supports the data types 
TEXT (similar to String in Java), INTEGER (similar to long in Java) andREAL (similar to double in Java). All other types must be converted into one of these fields before saving them in the database. SQLite itself does not validate if the types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.

SQLite in Android?
SQLite is available on every Android device. Using an SQLite database in Android does not require any database setup or administration.
You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform.
Access to an SQLite database involves accessing the filesystem. This can be slow. Therefore it is recommended to perform database operations asynchronously, for example inside the AsyncTaskclass.
If your application creates a database, this database is by default saved in the directoryDATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is the path which the Environment.getDataDirectory() method returns. APP_NAME is your application name.FILENAME is the name you specify in your application code for the database.

SQLiteOpenHelper:
To create and upgrade a database in your Android application you usually subclass
SQLiteOpenHelper. In the constructor of your subclass you call the super() method ofSQLiteOpenHelper, specifying the database name and the current database version.
In this class you need to override the onCreate() and onUpgrade() methods.
onCreate() is called by the framework, if the database does not exists.
onUpgrade() is called, if the database version is increased in your application code. This method allows you to update the database schema.
Both methods receive an SQLiteDatabase object as parameter which represents the database.
SQLiteOpenHelper provides the      methods getReadableDatabase() andgetWriteableDatabase() to get access to an SQLiteDatabase object; either in read or write mode.
The database tables should use the identifier _id for the primary key of the table. Several Android functions rely on this standard.
It is best practice to create a separate class per table. This class defines static onCreate() andonUpgrade() methods. These methods are called in the corresponding methods ofSQLiteOpenHelper. This way your implementation of SQLiteOpenHelper will stay readable, even if you have several tables.

SQLiteDatabase?SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database.
More specifically SQLiteDatabase provides the insert(), update() and delete() methods.
In addition it provides the execSQL() method, which allows to execute an SQL statement directly.
The object ContentValues allows to define key/values. The "key" represents the table column identifier and the "value" represents the content for the table record in this column. ContentValuescan be used for inserts and updates of database entries.
Queries can be created via the rawQuery() and query() methods or via theSQLiteQueryBuilder class .
rawQuery() directly accepts an SQL select statement as input.
query() provides a structured interface for specifying the SQL query.
SQLiteQueryBuilder is a convenience class that helps to build SQL queries.

Cursor:A query returns a Cursor object. A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.

To get the number of elements of the resulting query use the getCount() method.

To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.
A Cursor needs to be closed with the close() method call.
We need to write our own class to handle all database CRUD(Create, Read, Update and Delete) operations.

Example:
Step1: Create a new class called StudentDB.java

Step2: Now extend y StudentDB.java class from SQLiteOpenHelper.

Step3: After extending your class from SQLiteOpenHelper you need to override two methodsonCreate() and onUpgrage()

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.,

Step4: Now we need to write methods for handling all database read and write operations. 






public class database extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.database);


SQLiteDatabase sqlitedb=openOrCreateDatabase("Raja",MODE_PRIVATE , null);

sqlitedb.execSQL("create table if not exists sampletable(firstname varchar,lastname char)");

sqlitedb.execSQL("insert into sampletable values('Raja','babu')");

Cursor cr=sqlitedb.rawQuery("select * from sampletable", null);
cr.moveToFirst();

//Getting data using column name
String fname = cr.getString(cr.getColumnIndex("firstname"));

//Getting data using column index number

String lname = cr.getString(1);

Toast.makeText(getApplicationContext(), "firstname :"+fname+"\n"+"lastname :"+lname, Toast.LENGTH_LONG).show();

}

}

CustomListView

custom.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="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
   
</LinearLayout>

---------------------------------------------------------------------------------------------------------------
customactivity.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" >
    
  <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>
---------------------------------------------------------------------------------------------------------------

public class CusActvity extends Activity{
String[] names = {"name1", "name2", "name3", "name4", "name5", "nam6","name7", "name8", "name9", "name10" };

String[] locations = { "location1", "location2", "location3", "location4","location5", "location6", "location7", "location8", "location9","location10" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customactivity);
ListView list = (ListView) findViewById(R.id.listView1);

raja ca = new raja();
list.setAdapter(ca);
}
public class raja extends BaseAdapter{

@Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.custom, null);
TextView t1 = (TextView)convertView.findViewById(R.id.textView1);
TextView t2 = (TextView)convertView.findViewById(R.id.textView2);
t1.setText(names[position]);
t2.setText(locations[position]);
// TODO Auto-generated method stub
return convertView;
}
}
}

AsyncTask Example in Android

Using AsyncTask we can avoid ANR(Application Not Responding).


AsyncTask's Generic Types:


Params, the type of the parameters sent to the task upon execution.
    Progress, the type of the progress units published during the background computation.
      Result, the type of the result of the background computation.

      The 4 Steps:
        When an asynchronous task is executed, the task goes through 4 steps:
          1.onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
            2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. 
              These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
                3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
                  4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.



                  public class AshncTask extends Activity{

                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.ashnctask);

                  new asy().execute();

                  }
                  class asy extends AsyncTask<Void, Void, Void> {
                  ProgressDialog pd;
                  @Override
                  protected void onPreExecute() {

                     pd = new ProgressDialog(AshncTask.this);
                         pd.setTitle("downloading");
                           pd.setMessage("please wait");
                               pd.show();

                  super.onPreExecute();

                  }

                  @Override
                  protected Void doInBackground(Void... params) {

                  try {

                  Thread.sleep(5000);


                  } catch (InterruptedException e) {
                  e.printStackTrace();
                  }
                  return null;
                  }


                  @Override
                  protected void onPostExecute(Void result) {
                  pd.cancel();
                  super.onPostExecute(result);
                  }
                  }

                  }
                  .............................................................................................................................................................
                  <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" >

                      <TextView
                          android:id="@+id/textView1"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_alignParentTop="true"
                          android:layout_centerHorizontal="true"
                          android:text="async_task"
                          tools:context=".AsyncTaskActivity" />

                      <ProgressBar
                          android:id="@+id/progress"
                          style="?android:attr/progressBarStyleHorizontal"
                          android:layout_width="match_parent"
                          android:layout_height="50dp"
                          android:layout_below="@+id/textView1"
                          android:layout_marginTop="30dp" />

                      <Button
                          android:id="@+id/btn_start"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_below="@+id/progress"
                          android:layout_centerHorizontal="true"
                          android:layout_marginTop="40dp"
                          android:minWidth="120dp"
                          android:text="start_btn" />

                      <TextView
                          android:id="@+id/txt_percentage"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_alignParentLeft="true"
                          android:layout_below="@+id/progress"
                          android:text="downloading  0%"
                          android:textAppearance="?android:attr/textAppearanceMedium" />

                  </RelativeLayout>


                  public class agshjkhas extends Activity implements OnClickListener{
                  Button btn_start;
                  ProgressBar progressBar;
                  TextView txt_percentage;
                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.agsync);
                  btn_start = (Button) findViewById(R.id.btn_start);
                  progressBar = (ProgressBar) findViewById(R.id.progress);
                  txt_percentage = (TextView) findViewById(R.id.txt_percentage);
                  btn_start.setOnClickListener(this);
                  }
                  @Override
                  public void onClick(View v) {
                  btn_start.setEnabled(false);
                  new agjghjas().execute();
                  }
                  private class agjghjas extends AsyncTask<Void, Integer, Void>{

                  int prograssStatus;


                  @Override
                  protected void onPreExecute() {

                  prograssStatus = 0;
                  txt_percentage.setText("downloading 0%");
                  super.onPreExecute();
                  }
                  @Override
                  protected Void doInBackground(Void... params) {
                  while (prograssStatus < 100) {

                  prograssStatus += 2;

                  publishProgress(prograssStatus);
                  SystemClock.sleep(3000);

                  }
                  return null;
                  }
                  @Override
                  protected void onProgressUpdate(Integer... values) {
                  // TODO Auto-generated method stub
                  super.onProgressUpdate(values);
                  progressBar.setProgress(values[0]);
                  txt_percentage.setText("downloading " + values[0] + "%");
                  }
                  @Override
                  protected void onPostExecute(Void result) {
                  // TODO Auto-generated method stub
                  super.onPostExecute(result);
                  txt_percentage.setText("download complete");
                  btn_start.setEnabled(true);
                  }
                  }
                  }

                  Monday, 8 September 2014

                  ListView in Android

                  text.xml:
                  <?xml version="1.0" encoding="utf-8"?>
                  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
                      android:layout_width="match_parent"
                      android:layout_height="match_parent"
                      android:textSize="20dp"
                      android:textColor="##ff2020" >

                  </TextView>



                  activity_main.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="match_parent"
                      android:layout_height="match_parent"
                      android:orientation="vertical"
                      tools:context=".MainActivity"
                      android:background="#ff00ff" >

                      <ListView
                          android:id="@+id/listView1"
                          android:layout_width="match_parent"
                          android:layout_height="wrap_content"
                          android:cacheColorHint="#ff00ff" >
                      </ListView>

                  </LinearLayout>



                  public class list  extends Activity{
                  String[] names = { "name1", "name2", "name3", "name4", "name5", "Second Activity", "name7", "name8", "name9", "name10" , "name11", "name12", "name13", "name14", "name15", "name16","name17", "name18", "name19", "name20"};

                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.list);

                  ListView list = (ListView) findViewById(R.id.listView1);

                  ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.text,names);
                  list.setAdapter(adapter);

                  }


                  }

                  Custom Dialog in Android

                  custom.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="Enter user name"
                          android:textAppearance="?android:attr/textAppearanceLarge" />

                      <EditText
                          android:id="@+id/editText1"
                          android:layout_width="match_parent"
                          android:layout_height="wrap_content"
                          android:ems="10"
                          android:inputType="textPersonName" >
                      </EditText>

                      <TextView
                          android:id="@+id/textView2"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:text="Enter password"
                          android:textAppearance="?android:attr/textAppearanceLarge" />

                      <EditText
                          android:id="@+id/editText2"
                          android:layout_width="match_parent"
                          android:layout_height="wrap_content"
                          android:ems="10"
                          android:inputType="textPassword" />

                      <TableRow
                          android:id="@+id/tableRow1"
                          android:layout_width="match_parent"
                          android:layout_height="wrap_content" >

                          <Button
                              android:id="@+id/button1"
                              android:layout_width="wrap_content"
                              android:layout_height="wrap_content"
                              android:text="ok" />

                          <Button
                              android:id="@+id/button2"
                              android:layout_width="wrap_content"
                              android:layout_height="wrap_content"
                              android:text="cancel" />
                      </TableRow>

                  </LinearLayout>




                  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"
                      tools:context=".MainActivity" >

                      <Button
                          android:id="@+id/button1custom"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_alignParentTop="true"
                          android:layout_centerHorizontal="true"
                          android:layout_marginTop="130dp"
                          android:text="Custom dialog" />

                  </RelativeLayout>


                  public class MainActivity extends Activity {

                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  Button b = (Button)findViewById(R.id.button1custom);
                  b.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                  // TODO Auto-generated method stub
                  final Dialog customDialog = new Dialog(MainActivity.this);
                  customDialog.setTitle("Custom Dialog");
                  customDialog.setContentView(R.layout.custom);
                  customDialog.show();
                  Button okButton = (Button)customDialog. findViewById(R.id.button1);
                  okButton.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                  // TODO Auto-generated method stub
                  Toast.makeText(getApplicationContext(), "ok button is working", Toast.LENGTH_SHORT).show();
                  }
                  });
                  Button cancelButton =(Button)customDialog.findViewById(R.id.button2) ;
                  cancelButton.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                  // TODO Auto-generated method stub
                  customDialog.dismiss();
                  }
                  });
                  }
                  });
                  }

                   

                  }