Thursday, 25 December 2014

Color shade effects designing in android

Today i am going to post about color shade designing in android with using XML.

You can download necessary files for this example from HEAR.


In this there is no need to Add anything in java file, you can design by XML file only.

activity_main.xml
<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="com.AndroidTecHub.colorshade.MainActivity" >
   
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        android:layout_weight="5"
        android:weightSum="9">
       
        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:background="@drawable/one_shade">
           
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1"
                android:textSize="55dp"
                android:layout_gravity="center"/>
           
        </FrameLayout>
        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:background="@drawable/two_shade">
           
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="2"
                android:textSize="55dp"
                android:layout_gravity="center"/>
           
        </FrameLayout>
        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:background="@drawable/three_shade">
           
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="3"
                android:textSize="55dp"
                android:layout_gravity="center"/>
           
        </FrameLayout>
       
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        android:layout_weight="5">
       
        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:background="@drawable/four_shade">
           
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="4"
                android:textSize="55dp"
                android:layout_gravity="center"/>
           
        </FrameLayout>
        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:background="@drawable/five_shade">
           
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="5"
                android:textSize="55dp"
                android:layout_gravity="center"/>
           
        </FrameLayout>
        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:background="@drawable/six_shade">
           
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="6"
                android:textSize="55dp"
                android:layout_gravity="center"/>
           
        </FrameLayout>
       
    </LinearLayout>




</LinearLayout>




Hear is one of the drawable xml file for example,You can download all file from download link.

one_shad.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item >
    <shape android:shape="rectangle"  >
         <gradient android:angle="-90" android:startColor="#FF0000" android:endColor="#FFFFFF" />           
     </shape>
 </item>
</selector>



You can download necessary files for this example from HEAR.

I hope it will help you in developing android app.
Happy coding...

Tuesday, 23 December 2014

Send Email from your Application without using intent in Android

Today I will show you how to send E-mail from your Application without using intent and without re-direct in any mail application.

You can download all necessary files from HEAR.




Step - 1: Import 3 jar file in your application lib folder You can get all jar from witch are given in Download Link.

Step - 2: You need to add 2 permission in your Manifest file

1.android.permission.INTERNET
2. android.permission.ACCESS_NETWORK_STATE

Step - 3: Now add 2 Java files GMailSender.java and JSSEProvider.java both file you can get from download link.

MainActivity.Java

package com.example.mailtry;

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 {

    EditText etSender, etBody, etPassword, etSubject, etTo;

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

        etSender = (EditText) findViewById(R.id.etSender);
        etBody = (EditText) findViewById(R.id.etBody);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etSubject = (EditText) findViewById(R.id.etSubject);
        etTo = (EditText) findViewById(R.id.etTo);
        Button btnSend = (Button) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (etSender.getText().toString().trim() != ""
                        && etPassword.getText().toString().trim() != ""
                        && etTo.getText().toString().trim() != ""
                        && etSubject.getText().toString().trim() != "") {

                new Thread(new Runnable() {
                    public void run() {
                        try {
                            GMailSender sender = new GMailSender(
                                    etSender.getText().toString().trim(), etPassword.getText().toString().trim());

                            //------  You can attech attechment from below code also -----//
                            // sender.addAttachment(Environment.getExternalStorageDirectory().getPath()+"/image.jpg");
                            sender.sendMail(etSubject.getText().toString().trim(),
                                    etBody.getText().toString().trim(),
                                    etSender.getText().toString().trim(),
                                    etTo.getText().toString().trim());

                          

                        } catch (Exception e) {
                        }
                    }
                }).start();
            }
                Toast.makeText(getApplicationContext(),"Your mail has been sent",Toast.LENGTH_LONG).show();
              
            }
        });

    }

}





activity_mail.xml

<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"
    tools:context="com.example.mailtry.MainActivity"
    android:orientation="vertical">
   
    <EditText
        android:id="@+id/etSender"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:hint="Sender"
        android:layout_marginBottom="10dp"/>
   
    <EditText
        android:id="@+id/etPassword"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:layout_marginBottom="10dp"/>
   
    <EditText
        android:id="@+id/etTo"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:hint="To"
        android:layout_marginBottom="10dp"/>
   
    <EditText
        android:id="@+id/etSubject"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:hint="Subject"
        android:layout_marginBottom="10dp"/>
   
    <EditText
        android:id="@+id/etBody"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:hint="Body"
        android:layout_marginBottom="10dp"/>

    <Button
        android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="send" />

</LinearLayout>


You can download all necessary files from HEAR.

I hope this will help you,
Happy Coding...

Friday, 12 December 2014

Android work with SQLITE database with copy database in phone (Create, Select, Add in database)

Today I will explain you to how to Copy database in your phone, connection with SQLite, in android development.

I am going to create one simple SQLite database in SQLite manager and connect it with my Application.For crate database i am prefer to use Mozila Firefox Add-ons tool.


Screen Short :




You can download Necessary files for example from HEAR 
 

First open mozila Add-ons,If you can't find Add-ons then use shortcut key "Ctrl+Shift+A" to open Add-ons.

Now search for Sqlite Manager and install it and you need to restart browser ones.


 Now you can find SQLite in your menu bar
"Tools -> SQLite Manager"

By opening it you will get new browser window with SQLite Manager here you can create simple database with table.

Let I create database with name AndroidTecHub with table name Information and it contains column name,PhoneNumber,MailId.

  

 Your database will save with .sqlite extension at your specified place.

Now copy database in projects assets folder.

Make one class file with name DatabaseHelper.java, this will handle copy and all the connection with database to application.



DatabaseHelper.java File :-

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

public class DataBaseHelper extends SQLiteOpenHelper {
    // The Android's default system path of your application database.
    public static String DB_PATH = Environment.getExternalStorageDirectory()+"/";
    private static String DB_NAME = "AndroidTecHub.sqlite";
    private static String DB_NAME_MY = "AndroidTecHub.sqlite";
    private SQLiteDatabase AndroidTecHub;
    private final Context myContext;

    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     *
     * @param context
     */

    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     * */
    public void createDataBase() throws IOException {
        // for first database;
        boolean dbExist = checkDataBase(DB_NAME);
        if (!dbExist) {
            try {
                copyDataBase(DB_NAME_MY, DB_NAME);
            } catch (Exception e) {
                throw new Error("Copying not done");
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(String DB) {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e)
        {
           
        }

        if (checkDB != null) {

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private void copyDataBase(String assetfile, String DB) {

        // Open your local db as the input stream
        InputStream myInput = null;
        // Open the empty db as the output stream
        OutputStream myOutput = null;
        try {
            myInput = myContext.getAssets().open(assetfile);

            // Path to the just created empty db
            myOutput = new FileOutputStream(Environment.getExternalStorageDirectory()+"/AndroidTecHub.sqlite");

            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }

            System.out.println("***************************************");
            System.out.println("####### Data base copied ##############");
            System.out.println("***************************************");

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // Close the streams
            try {
                myOutput.flush();
                myOutput.close();
                myInput.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void openDataBase() {

        try {
            // Open the database
            String myPath = DB_PATH + DB_NAME;
            AndroidTecHub = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READWRITE);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public synchronized void close() {

        if (AndroidTecHub != null)
            AndroidTecHub.close();

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
       
    }

    public boolean update(String strUpdate) {
        // TODO Auto-generated method stub
        try
        {
            AndroidTecHub.execSQL(strUpdate);
            return true;
        }
        catch (Exception ex)
        {
           
            return false;
        }
    }
    public boolean insertRecord(String strInsert)
    {
        try
        {
            AndroidTecHub.execSQL(strInsert);
            return true;
        }
        catch (Exception ex)
        {
           
            return false;
        }
    }
   
    public boolean deleteRecord(String strDelete)
    {
        try
        {
            AndroidTecHub.execSQL(strDelete);
            return true;
        }
        catch (Exception ex)
        {
           
            return false;
        }
    }
   
    public Cursor selectRecord(String strSelect)
    {
        try
        {
            Cursor cursor = AndroidTecHub.rawQuery(strSelect, null);
            cursor.moveToFirst();
            return cursor;
        }
        catch (Exception ex)
        {
           
            return null;
        }
    }
    public int CountRow(String strCount)
    {
        long numRows = DatabaseUtils.longForQuery(AndroidTecHub,strCount, null);
        int numrows=(int) numRows;
        return numrows;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
       
    }


    // Add your public helper methods to access and get content from the
    // database.
    // You could return cursors by doing "return myDataBase.query(....)" so it'd
    // be easy
    // to you to create adapters for your views.

}


Now For Add data Use code :

--------------------------------------------------------------
DataBaseHelper datahelper;
datahelper = new DataBaseHelper(this);
        try {
            datahelper.createDataBase();
            datahelper.openDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
datahelper.insertRecord("Insert into Information (Name,PhoneNumber,MailId) values (\""
                                + etName.getText().toString()
                                + "\",\""
                                + etPhoneNumber.getText().toString()
                                + "\",\""
                                + etEmailId.getText().toString() + "\")");

------------------------------------------------------------------


And For Fetch data Use code :

------------------------------------------------------------------

datahelper = new DataBaseHelper(this);
            datahelper.openDataBase();
            try
            {
                Cursor cursor = datahelper.selectRecord("SELECT * FROM Information");
                if (cursor.getCount() > 0) {
                    for(int i=0;i<cursor.getCount();i++)
                    {
                        txtData.append("Name : "+cursor.getString(0)+"\n");
                        txtData.append("Phone Number : "+cursor.getString(1)+"\n");
                        txtData.append("EmailId : "+cursor.getString(2)+"\n");
                        txtData.append("------------------------\n");
                        cursor.moveToNext();
                    }
                }
                datahelper.close();
            }
            catch(Exception ex)
            {
               
            }

------------------------------------------------------------------


Last And Most Impotent,

Add permission in your Manifest file   


    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

--------------------------------------------------------------------

You can download Necessary files for example from HEAR 

Hope You Help this,

Enjoy,Happy coding.

Thursday, 11 December 2014

Android Set textsize for Multiple Screens


There is main issue in android to design your application in a way to application should look proper in all devices whether it will small size device or it will tablet, So Today I am going to Explain How to design your application For different size of devices.

Step - 1:
First Create New Sample application,

For Create New Application in Eclipse go to

File-> New-> Android Application Project



Now Press Next...Finish.


 Step - 2:
Set "res" Folder,

Create new 4 folders in "Package Explorer -> YourApp -> res" folder,with name  
  • values-small
  • values-normal,
  • values-large
  • values-xlarge

(Note : if you cant get find Package Explorer then go to in Menu bar
"Window -> Show View -> Package Explorer")

 Now Create XML file in all this 4 new folders with same name "dimens.xm".




Step - 3 :
Set TextSize of Textview:

Now Let we set on size of font for different devices using by calling values from dimens.xml file.

Open Your main design xml page from Layout folder.and take one textview
and call text size from dimens.xml file as give in below.


Yes,It will give an error when we set "textsize" in textview because we trying to fetch value of textsize from dimen.xml but we are still not define value in dimens.xml,So let we define it in all dimens files.

Step - 4:
define TextSize in all dimens.xml:

 now set values of textsize in dimens file,

For "values-small -> dimens.xml" use below code,
<dimen name="textsize">16dp</dimen>

For "values-normal -> dimens.xml" use below code,
<dimen name="textsize">20dp</dimen>

For "values-large -> dimens.xml" use below code,
<dimen name="textsize">35dp</dimen>

For "values-xlarge -> dimens.xml" use below code,
<dimen name="textsize">55dp</dimen>




Thats it!!!!
Now when you can check your output for all devices it will look appropriately for all devices .

By this way devices will fetch textsize from dimens.xml.

 Device Size
  • For devices of size < 2.7" fatch vaues from values-small
  • For devices of size  3.2" to 4.7" fatch vaues from values-normal folder
  • For devices of size 5.1" to 7.0" fatch vaues from values-large folder
  • For 10" tablet fatch vaues from values-xlarge folder  









 
  




Android Life Cycle

In this post i am posting about Life cycle of android,It will help you for understanding how any application work.






OnCreate();

 Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().


onRestart();
Called after your activity has been stopped, prior to it being started again. Always followed by onStart() .


onStart();
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.


onResume();
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().


OnPause();
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.


onStope();
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

Note : that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.


onDestory();
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.



When the Activity first time loads the events are called as below:
  • onCreate(); 
  • onStart();
  • onResume();
When you click on Phone button the Activity goes to the background and the below events are called:
  • onPause();
  • onStop();
 Exit the phone dialer and the below events will be called:
  • onRestart();
  • onStart();
  • onResume();
 When you click the back button OR try to finish() the activity the events are called as below:
  • onPause();
  • onStop();
  • onDestroy();



Activity States

The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:

These states can be broken into three main groups as follows:

Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.

Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.

Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.



below code for understand more about LifeCycle :

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    String tag = "LifeCycleEvents";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Log.d(tag, "In the onCreate() event");
    }
    public void onStart()
    {
       super.onStart();
       Log.d(tag, "In the onStart() event");
    }
    public void onRestart()
    {
       super.onRestart();
       Log.d(tag, "In the onRestart() event");
    }
    public void onResume()
    {
       super.onResume();
       Log.d(tag, "In the onResume() event");
    }
    public void onPause()
    {
       super.onPause();
       Log.d(tag, "In the onPause() event");
    }
    public void onStop()
    {
       super.onStop();
       Log.d(tag, "In the onStop() event");
    }
    public void onDestroy()
    {
       super.onDestroy();
       Log.d(tag, "In the onDestroy() event");
    }
}