Friday 14 September 2012

How to prevent activity to being restarted on orientation changed | Prevent activity restart on orientation changed


An Activity is being restarted just because of configuration changes like orientation, screenSize(from API level 10), keyboard hidden etc.
So what you need to do is : declare below line in your manifest file. android:configChanges="keyboard|orientation|keyboardHidden". And if you are using above version of android 2.2(API level 8) you can also declare screenSize parameter too.

Example:

Create a project and replace your code by this code


package com.retainstate;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class RetainActivityStateActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        showDialog();
     
    }
 
    private void showDialog()
    {
    AlertDialog.Builder al=new AlertDialog.Builder(this);
        al.setMessage("Hello! Activity will not restart on orientation changing.")
        .setTitle("RetainStateOfActivity").setPositiveButton("OK", null).show();
    }
}

Now let the main.xml as it is

In manifest file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.retainstate"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".RetainActivityStateActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



Now run the project an alertDialog will show and then change the orientation of emulator by leftCtrl+F11. you dialog will remain stay.



Source Code: download zip.file

Thursday 13 September 2012

Hello world Tutorial in android | Android Hello world tutorial

Today, I am going to show you how to create Hello world example. I am assuming that you have successfully installed the android sdk in your PC. In this turn, you need to follow some steps:

Step-1:

Open Eclipse click on file>new>android project


Then write your AndroidProjectName 'HelloWorldExampel' and click on next then select the sdk target (suppose android 2.2). Click on next and write the package name com.androiseeker.helloworldexample Then click finish.

Step-2:

Now Click on your project folder>src>com.androidseeker.helloworldexample>HelloWorldExampleActivity.java


package com.androidseeker.helloworldexample;

import android.app.Activity;
import android.os.Bundle;

public class HelloWorldExampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}


Let this java file remain as it is.

Step-3:

Now click on project folder>res>layout>main.xml and replace the paste this code.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello AndroidSeeker!" />

</LinearLayout>


Step-4:

Now run as android application


For any help do comment.

Thanks!!!


Monday 10 September 2012

SQLite database tutorial in android | How to use SQLite database in android

Step-1
Create DBSampleActivity.java in your project.


package com.dbsample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.dbsample.database.DbHelper;

public class DBSampleActivity extends Activity {
    /** Called when the activity is first created. */
Button btn_submit, btn_show;
EditText txt_name, txt_mobile, txt_salary;
DbHelper dbhelper;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        btn_submit=(Button)findViewById(R.id.btn_submit);
        btn_show=(Button)findViewById(R.id.btn_show_data);
     
        txt_name=(EditText)findViewById(R.id.txt_name);
        txt_mobile=(EditText)findViewById(R.id.txt_mobile);
        txt_salary=(EditText)findViewById(R.id.txt_salary);
     
        btn_submit.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub

dbhelper=new DbHelper(DBSampleActivity.this);

ContentValues cv=new ContentValues();
if(txt_name.getText().toString()!=null && txt_mobile.getText().toString()!=null && txt_salary.getText().toString()!=null)
{
cv.put(DbHelper.EMP_NAME, txt_name.getText().toString().trim());
cv.put(DbHelper.EMP_MOBILE, txt_mobile.getText().toString().trim());
cv.put(DbHelper.EMP_SALARY, txt_salary.getText().toString().trim());


try
{
dbhelper.insertEmpData(cv);
} catch (SQLiteException e) {
// TODO: handle exception
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
});
     
        btn_show.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
Cursor c=null;
try {
AlertDialog.Builder al=new AlertDialog.Builder(DBSampleActivity.this);
c=dbhelper.showData();

if(c.getCount()>0)
{
for (c.moveToFirst();!c.isAfterLast(); c.moveToNext())
{
//c.getInt(0);
c.getString(1);
c.getString(2);
c.getString(3);


al.setTitle("EMP Details").setMessage("NAME : "+c.getString(1)+" \nMOBILE : "+c.getString(2)+" \nSALARY : "+c.getString(3));
al.setCancelable(true);

}

al.show();
c.close();
}
else
{
Log.d("", "No value to display");
}


} catch (Exception e) {
// TODO: handle exception
c.close();
e.printStackTrace();
}


}
});
            }
}

Step-2

main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >





    <EditText
        android:id="@+id/txt_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter name"
        android:inputType="textPersonName" >

        <requestFocus />

    </EditText>




    <EditText
        android:id="@+id/txt_mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Mobile number"
        android:inputType="number" />




    <EditText
        android:id="@+id/txt_salary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Salary"
        android:inputType="number" />






    <Button
        android:id="@+id/btn_submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit" />





    <Button
        android:id="@+id/btn_show_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Data" />

</LinearLayout>

screen shot for main.xml



Step-3:
Create a new java class DbHelper.java


package com.dbsample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbHelper extends SQLiteOpenHelper{

public static String DATABASE_NAME="testdb";
public static String TBL_EMP_DETAILS="records";
public static String EMP_NAME="emp_name";
public static String EMP_MOBILE="emp_mobile";
public static String EMP_SALARY="emp_salary";
private String TAG;

public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// TODO Auto-generated constructor stub



}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

String query="CREATE TABLE "+TBL_EMP_DETAILS+" ( _id integer primary key autoincrement, "+EMP_NAME+" text not null, "+EMP_MOBILE+" text not null, "+EMP_SALARY+ " text not null )";

db.execSQL(query);

Log.d(TAG, "query executed");

}


public void insertEmpData(ContentValues cv)
{
SQLiteDatabase db=getWritableDatabase();

db.insert(TBL_EMP_DETAILS, null, cv);
}

public Cursor showData()
{
SQLiteDatabase db=getReadableDatabase();

return db.rawQuery("SELECT * FROM "+TBL_EMP_DETAILS, null);

}

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

}


}

Step-4:

Now, You run your android project and then insert details then click on show button then you see the output onto the emulator.






Thanks

Regards-
Lalit



Wednesday 5 September 2012

How to apply new theme to whole application in android | Applying theme at run time in android

It is pretty easy to applying new theme to the whole application at run time. First you create a your own custom themes and set it in the java code. Whenever a new theme is applied at run time we have set the same before calling onCreate() and setContentView() method.
See the instructions enjoy coding....

Step-1:
Create  attrs.xml in '.../res/values' folder.


<?xml version="1.0" encoding="utf-8"?>
  <resources>
       <!-- View styles -->
       <attr name="textTitle" format="reference" />
       <attr name="textBody" format="reference" />
       <attr name="buttonText" format="reference"/>
       <attr name="radioButtonText" format="reference"/>
       <attr name="backgroundTheme" format="reference"></attr>
     
 </resources>
Step-2:

Create color.xml in values folder of you project.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_color">#2B3856</color>
</resources>


Step-3:

Create styles.xml file in the '.../res/values' folder.



<?xml version="1.0" encoding="utf-8"?>
<resources>
   <style name="small_title_text">
      <item name="android:textSize">20sp</item>
      <item name="android:textColor">#228B22</item>
      <item name="android:textStyle">normal</item>
      <item name="android:paddingBottom">5dip</item>
   </style>
   <style name="small_body_text">
      <item name="android:textSize">16sp</item>
      <item name="android:textColor"> #228B22</item>
      <item name="android:textStyle">normal</item>
      <item name="android:paddingBottom">5dip</item>
   </style>
   <style name="small_button_text">
      <item name="android:textSize">16sp</item>
      <item name="android:textColor"> #228B22</item>
      <item name="android:textStyle">normal</item>
 
   </style>


   <style name="large_title_text">
      <item name="android:textSize">24sp</item>
      <item name="android:textColor"> #228B22</item>
      <item name="android:textStyle">normal</item>
      <item name="android:paddingBottom">5dip</item>
   </style>

   <style name="large_body_text">
      <item name="android:textSize">20sp</item>
      <item name="android:textColor"> #228B22</item>
      <item name="android:textStyle">normal</item>
      <item name="android:paddingBottom">5dip</item>
   </style>
   <style name="large_button_text">
      <item name="android:textSize">20sp</item>
      <item name="android:textColor"> #228B22 </item>
      <item name="android:textStyle">normal</item>

   </style>

   <!--radio button style  -->

   <style name="small_radio_btn_text">
      <item name="android:textSize">16sp</item>
      <item name="android:textColor"> #228B22 </item>
      <item name="android:textStyle">normal</item>
      <item name="android:paddingBottom">5dip</item>
   </style>

   <style name="large_radio_btn_text">
      <item name="android:textSize">20sp</item>
      <item name="android:textColor">#228B22</item>
      <item name="android:textStyle">normal</item>
      <item name="android:paddingBottom">5dip</item>
   </style>

   <style name="default_radio_btn_text">
      <item name="android:textSize">15sp</item>
      <item name="android:textColor"> #228B22 </item>
      <item name="android:textStyle">normal</item>
      <item name="android:paddingBottom">5dip</item>
   </style>

  <!-- Change gray_radient theme -->

  <style name="gray_gradient">
      <item name="android:background"> #C1CDCD </item>
      <item  name="android:padding">2dp</item>
</style>

  <!-- Change radial gradient theme -->

  <style name="radial_gradient">
      <item name="android:background"> #36648B </item>
      <item  name="android:padding">2dp</item>
</style>

  <style name="default_theme">
      <item name="android:background">@drawable/background</item>
      <item  name="android:padding">2dp</item>
</style>


  <!-- Change default theme -->

  <style name="background_default">
      <item name="android:background">@drawable/background</item>
      <item  name="android:padding">2dp</item>
</style>




  <!-- Base application theme is the default theme. -->
  <style name="Theme" parent="android:Theme">
  </style>

  <style name="Theme.SmallText">
     <item name="textTitle">@style/small_title_text</item>
     <item name="textBody">@style/small_body_text</item>
     <item name="buttonText">@style/small_button_text</item>
     <item name="radioButtonText">@style/small_radio_btn_text</item>
 
  </style>

  <style name="Theme.LargeText">
      <item name="textTitle">@style/large_title_text</item>
      <item name="textBody">@style/large_body_text</item>
      <item name="buttonText">@style/large_button_text</item>
      <item name="radioButtonText">@style/large_radio_btn_text</item>
  </style>

  <style name="Theme.DefaultText">
      <item name="backgroundTheme">@style/background_default</item>
      <item name="radioButtonText">@style/default_radio_btn_text</item>
  </style>

  <style name="Theme.Gray">
      <item name="backgroundTheme">@style/gray_gradient</item>
  </style>

  <style name="Theme.Radial">
      <item name="backgroundTheme">@style/radial_gradient</item>
  </style>

  <style name="Theme.DefaultTheme">
      <item name="backgroundTheme">@style/background_default</item>
  </style>

  <style name="PreferencesTheme" parent="android:Theme.Light">
       <item name="android:background">#FFEAEAEA</item>
</style>
 </resources>


Step-4:
Create  questions.xml, 
Then you need to declare you style in your xml file. 


<?xml version="1.0" encoding="utf-8"?>
<ScrollView
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:id="@+id/scroll_view_start_test_for_all"
 android:layout_above="@+id/lin_lay"
 android:layout_below="@+id/top"
 style="?backgroundTheme"
 android:layout_height="fill_parent">
       
           <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:paddingBottom="10dp"
            android:orientation="vertical">
       
     
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginBottom="10dp"
         android:textStyle="bold"
         style="?textBody"
         android:textColor="@color/text_color"
         android:text="Question No: "/>
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginBottom="10dp"
         android:layout_weight="1.7"
         style="?textBody"
         android:textColor="@color/text_color"
         android:textStyle="bold"
         android:id="@+id/start_all_que_no"/>
   
     </LinearLayout>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/text_color"
        android:layout_marginBottom="10dp"
        style="?textBody"
        android:id="@+id/start_all_que_detail"
        android:text="@string/question"/>
   
     <RadioGroup
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:id="@+id/group_start_test_for_all"
         android:orientation="vertical">
   
      <RadioButton
       android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="@color/text_color"
          android:id="@+id/rd_option_a_start_test"
          style="?radioButtonText"
         android:text="A: LuckNow" />

       <RadioButton
       android:layout_width="wrap_content"
       android:id="@+id/rd_option_b_start_test"
       android:text="B: Agra"
       style="?radioButtonText"
       android:textColor="@color/text_color"
       android:layout_height="wrap_content"/>

       <RadioButton
       android:layout_width="wrap_content"
       android:id="@+id/rd_option_c_start_test"
       android:textColor="@color/text_color"
       android:text="C: Delhi"
       style="?radioButtonText"
       android:layout_height="wrap_content"/>

       <RadioButton
          android:layout_width="wrap_content"
          android:id="@+id/rd_option_d_start_test"
          android:text="D: Banglore"
          style="?radioButtonText"
          android:textColor="@color/text_color"
          android:layout_height="wrap_content" />
 
     </RadioGroup>
           
</LinearLayout>
   
</ScrollView>




Step-5:

Create a java file 'Utils.java' in you package res/com.example.customTheme



package com.example.com.exampe.changetheme;

import android.app.Activity;
import android.util.Log;

public class Utils {

public static String SIZE="";
public static boolean settingChanged=false;
public static String THEME="";

public static void setThemeToActivity(Activity act )
{

 try {


if (Utils.SIZE.equalsIgnoreCase("LARGE"))
{
   act.setTheme(R.style.Theme_LargeText);
   Log.d(" ", "Theme Large txt size is to be is applied.");
}
if (Utils.SIZE.equalsIgnoreCase("SMALL"))
{
   act.setTheme(R.style.Theme_SmallText);
   Log.d(" ", "Theme Small text Size is to be is applied.");
}

if(Utils.SIZE.equalsIgnoreCase("DEFAULT"))
{
act.setTheme(R.style.Theme_DefaultText);
Log.d("", "theme default text size is applied.");
}

if(Utils.THEME.equalsIgnoreCase("defaultTheme"))
{
act.setTheme(R.style.Theme_DefaultTheme);
Log.d("", "Default theme is to be applied.");
}


if(Utils.THEME.equalsIgnoreCase("Gray"))
{
act.setTheme(R.style.Theme_Gray);
Log.d("", "gray theme is to be applied.");
}

if(Utils.THEME.equalsIgnoreCase("Radial"))
{
act.setTheme(R.style.Theme_Radial);
Log.d("", "radial theme is to be applied.");
}
 

 }
 catch (Exception e) {
e.printStackTrace();
}

}
}


Step-6:

Create Activity file (CustomThemeActivity.java)  and set theme before super.onCreate() and setContentView().


package com.example.com.exampe.changetheme;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class CustomThemeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Utils.setThemeToActivity(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);



}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
startActivity(new Intent(getBaseContext(), SettingsTheme.class));
CustomThemeActivity.this.finish();
}
}



Step-7:

Create another activity SettingTheme.java


package com.example.com.exampe.changetheme;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class SettingsTheme extends Activity implements View.OnClickListener

{
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  Utils.setThemeToActivity(this);
  setContentView(R.layout.config);

  findViewById(R.id.button1).setOnClickListener(this);
  findViewById(R.id.button2).setOnClickListener(this);
  findViewById(R.id.button3).setOnClickListener(this);
 }

 public void onClick(View v)
 {
  switch (v.getId())
  {
  case R.id.button1:
      Utils.THEME="DEFAULT";
      Utils.settingChanged=true;
      Utils.SIZE="DEFAULT";
      startActivity(new Intent( SettingsTheme.this,  CustomThemeActivity.class));

   break;
  case R.id.button2:
    Utils.THEME="Gray";
    Utils.settingChanged=true;
    Utils.SIZE="SMALL";
    startActivity(new Intent( SettingsTheme.this,  CustomThemeActivity.class));
   break;
  case R.id.button3:
       Utils.THEME="Radial";
       Utils.settingChanged=true;
       Utils.SIZE="LARGE";
       startActivity(new Intent( SettingsTheme.this,  CustomThemeActivity.class));
       break;
  default :
 break;

  }

 }
     public void onBackPressed() {
  // TODO Auto-generated method stub
  super.onBackPressed();
  startActivity(new Intent( SettingsTheme.this,  CustomThemeActivity.class));
  SettingsTheme.this.finish();

 }

}




Step-8:

Create an xml for SettingActivity - config.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 style="?backgroundTheme"
 android:layout_height="fill_parent">

 <LinearLayout

  android:layout_width="fill_parent"
  android:orientation="vertical"
  android:gravity="center_vertical"
  android:layout_height="fill_parent">

  <Button
   android:id="@+id/button1"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Default with Normal Text Size"/>

  <Button
   android:id="@+id/button2"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Gray with medium text Size"/>

  <Button
   android:id="@+id/button3"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Radial with Large Size"/>

 </LinearLayout>

</LinearLayout>




You have almost done, run your application

These are the output when you select your theme.







You can also download the source code of this project from here : download zip.file
Hope this will help you to do well.

Regards:

Lalit