Tuesday, 27 May 2014

Android Spinner (drop down list)- How to add Items in Spinner

Android  uses  Spinner  as drop-down list item in activity or action bar frequently.It is a quick way to select a value from the list.
Here in my example I have implemented a spinner view which contains the list of cities. If we click on show button it will take the current selected value  from the spinner and show as toast message .
Reset button will reset the default value in spinner.


Step-1:  Create a new project and add the spinner layout in activity_main.xml file

<Spinner
        android:id="@+id/spinner1"
        android:layout_width="150dp"
        android:layout_height="40dp">
                
</Spinner>

You can define your layout size according to requirement  Or  leave as match_parent or wrap_content

Also add two buttons. After this our Activity file will we like this:

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=".MainActivity"
    android:background="#2EFEF7" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/spinner1"
        android:layout_marginTop="54dp"
        android:text="Show" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="150dp"
        android:layout_height="40dp"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignParentTop="true"
        android:layout_marginTop="47dp" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_centerHorizontal="true"
        android:text="Reset" />

</RelativeLayout>

Step-2:   Define the list of items which you want to show in Spinner. You can do it in many ways. Like you can define in resources.xml file as string-array. See here. You can also take values from database and store in string-array. Here I have taken static values in string-array . Add this in to your MainActivity.java file

   String[] items=new String[] {"<Select City>","Bangalore","New            Delhi","Koltaka","Chennai"};


Step-3:  Define the Spinner layout.

    final Spinner spinner=(Spinner) findViewById(R.id.spinner1);

Step-4:   Create an ArrayAdapter  to show the values in list. Set the adapter with your string-array as follows.

// Create an ArrayAdapter using the string array and a default spinner layout
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
               android.R.layout.simple_spinner_item,items);                      // Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);

Now our Spinner is ready for use.

Step-5:   For buttonClickListeners get the values from spinner by following:

// get the particular item from spinner
String item= spinner.getSelectedItem().toString();

//set the particular item in spinner
spinner.setSelection(0);

Final Code:

MainActivity.java

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemSelectedListener {

       //items to show in spinners
      
       String[] items=new String[] {"<Select City>","Bangalore","New Delhi","Koltaka","Chennai"};
      
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
             
              Button bShow=(Button) findViewById(R.id.button1);
              Button bReset=(Button) findViewById(R.id.button2);
              final Spinner spinner=(Spinner) findViewById(R.id.spinner1);
             
              // Create an ArrayAdapter using the string array and a default spinner layout
              ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                      android.R.layout.simple_spinner_item,items);
              // Specify the layout to use when the list of choices appears
              adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
              // Apply the adapter to the spinner
              spinner.setAdapter(adapter);
             
              bShow.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View arg0) {
                           // get the particular item from spinner
                          
                           String item= spinner.getSelectedItem().toString();
                           Toast.makeText(getApplicationContext(),"Selected item:"+item,0).show();
                          
                     }
              });
             
      bReset.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View arg0) {
                          
                           //set the particular item in spinner
                           spinner.setSelection(0);
                           Toast.makeText(getApplicationContext(),"Spinner Resetted",0).show();
                          
                     }
              });
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
       }

       @Override
       public void onItemSelected(AdapterView<?> parent, View view, int pos,
                     long id) {
       // An item was selected. You can retrieve the selected item using
        //parent.getItemAtPosition(pos);
        //Here you can do more implementations according to your requirements    based on selecting particular item
       }

       @Override
       public void onNothingSelected(AdapterView<?> arg0) {
              // TODO Auto-generated method stub
             
       }

}

Step-6:   Run the project . You can your additional logic as per requirements in above three functions.
         Please comment and feedback for any issue .Thank You!!







Thursday, 8 May 2014

How to hide Action bar / Notification bar/ Status bar in Android | How to display activity in full screen

We saw in many games or another application that splash activity starts on full screen without status bar or anything. It’s very easy to implement this.
There are two sets of codes for android version 4.1 above and below. So I have put in If statement both codes.
Step-1: Copy and paste the below codes after setContentView() in onCreate(), whichever activity you want in full screen.

Code:

if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
       
        else{
              View decorView = getWindow().getDecorView();
              // Hide the status bar.
              int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
              decorView.setSystemUiVisibility(uiOptions);
              // Remember that you should never show the action bar if the
              // status bar is hidden, so hide that too if necessary.
              ActionBar actionBar = getActionBar();
              actionBar.hide();
        }

Step-2: After pasting this code will give some errors.Keep the mouse cursor on red and import relataed classes.. Your code will run.



Monday, 5 May 2014

How to save Login information in Android using Sqlite I How to save UserName and Password in Android

While developing a business application I found that almost all business apps or social media related apps are storing the login details for future use, so that user should skip the login step while next time opens the application.

It’s very easy to develop this feature in any android app. You can do it by storing Login details either in shared preferences or sqlite database.  Here in my Example I’m storing in sqlite database.


Step-1: Create new project -> Android Application Project. Name as ‘Save Login’ and click ‘next’,‘next’,               And lastly finish’
Step-2: Goto  res folder -> layout-> activity_main.xml file and design your login screen.

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

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="UserName">

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="37dp"
        android:ems="10"
        android:hint="PassWord" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="30dp"
        android:text="Save Login" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/checkBox1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:text="Login" />

</RelativeLayout>

After this your login screen will look like this.





Step-3: Create your second screen as HomePage of app in layout folder.

home.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 to Home Page"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

This simple Homepage will look like this. You can add more buttons ,icons etc according to your app requirements.



Step-4: Now goto src folder and right click-> new-> class, name as Home. This class is corresponding java file for Home screen. We should have corresponding java files for each activity to access it from another activity.
Pase the following code in Home.java

Home.java
package com.example.savelogin;

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

public class Home extends Activity {

      
       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.home); // Loading the home page
      
       }

}

Step-5: Open AndroidMenifest.xml file and define your home activity in that as following within <application> tab

<activity android:name="Home"></activity>

Step-6:Now to store login data we need to create the sqlite data base.
Go to src-add new class as MyDatabase.java. Here we will create our database. Database name is Mydb.db and table name is ‘logincredentials’.

MyDatabase.java

package com.example.savelogin;

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

public class Home extends Activity {

      
       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.home); // Loading the home page
      
       }

}
package com.example.savelogin;


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

public class MyDatabase {

       MyHelper mh;
       SQLiteDatabase sdb;
      
       public MyDatabase(Context con) {
              // Creating MyDatabase Mydb.db
              mh=new MyHelper(con, "Mydb.db", null, 1);
       }
      
       public void open(){
              sdb = mh.getWritableDatabase();
       }
      
       //getting data from user Login page.
       public void insertLoginCredentials(String tmpUName,String tmpPWD, String tmpLoginStatus){
              ContentValues cv = new ContentValues();
              cv.put("UserName",tmpUName);            
              cv.put("PassWord",tmpPWD);
              cv.put("LoginStatus", tmpLoginStatus);
              sdb.insert("loginCredentials", null, cv);      
             
       }
       //read values from emp table
       public Cursor getLoginCrendentials(){
              Cursor c=null;
              c=sdb.query("loginCredentials", null, null, null, null, null, null);
             
              return c;
       }
      
      
       private class MyHelper extends SQLiteOpenHelper{

              public MyHelper(Context context, String name, CursorFactory factory,
                           int version) {
                     super(context, name, factory, version);
                     // TODO Auto-generated constructor stub
              }

              @Override
              public void onCreate(SQLiteDatabase db) {
                     // Creating table in database
                    
                     db.execSQL("Create table loginCredentials(_id integer primary key, " +
                                  "UserName text, PassWord text, LoginStatus text);");
                    
              }

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

Step-7: Now our database is ready to save our data. Go to MainActivity.java and implement the login to save data and login. Here is the final code.

MainActivity.java

package com.example.savelogin;


import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


       //Declaring variables for views
      
       EditText etUser,etPass;
       Button bLogin;
       CheckBox cb;
       Cursor c=null;
       public static String hasSavedLogin="false";
      
       MyDatabase mdb=new MyDatabase(this);
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              //opening the database and reading the value
             
              mdb.open();
              c=mdb.getLoginCrendentials();
               if(c!=null){
                           //then only proceed
                            
                           while(c.moveToNext()){
                                  hasSavedLogin = c.getString(3);
                          
                           }
                     }
             
               // If login details is not saved enter in if statements
               
               if(!hasSavedLogin.equals("true")){
                      
      
             
                 etUser=(EditText) findViewById(R.id.editText1);
              etPass=(EditText) findViewById(R.id.editText2);
             
              bLogin=(Button) findViewById(R.id.button1);
              //Check box
             
              cb=(CheckBox) findViewById(R.id.checkBox1);
           
              bLogin.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View arg0) {               
                          
                           String user=etUser.getText().toString();
                           String pass=etPass.getText().toString();
                          
                           if(user.equals("android") && pass.equals("android")){
                                  Intent in=new Intent(getApplicationContext(),Home.class);
                                  if(cb.isChecked()){
                                         startActivity(in);
                                         etUser.setText("");
                                         etUser.requestFocus();
                                         etPass.setText("");
                                        
                                         //Storing Login details in MyDatabase
                                         hasSavedLogin="true";
                                        
                                         mdb.insertLoginCredentials(user,pass,hasSavedLogin);
                                     
                                        
                                         Toast.makeText(getApplicationContext(), "User saved", 0).show();
                                        
                                         finish();
                                  }
                                 
                                  //Login without saving data
                                  else{
                                  startActivity(in);
                                  etUser.setText("");
                                  etUser.requestFocus();
                                  etPass.setText("");
                                  finish();
                                  }
                           }
                          
                           //If Username or pwd is wrong
                          
                           else{
                                  Toast.makeText(getApplicationContext(), "Wrong username or password, please re-enter!", 0).show();
                                  etUser.setText("");
                                  etUser.requestFocus();
                                  etPass.setText(""); 
                           }                   
                          
                     }
              });        
            
       }
               
               //when user already saved the Logindetails,direct start home activity.
               
               else{
                      Intent in=new Intent(getApplicationContext(),Home.class);
                           startActivity(in);
                           finish();
               }

       }
}

I have commented in each section of codes for understanding purpose. Run the code and by default i have given username = ”android”and password = ”android”  to match for successful login.You can apply your own login credentials to match with database and validation for successful l login. Here I’m only trying to show to save the login credentials for next time login.

After successful  login you will switch to Home page. Close the app and again start, this time you will be directed to Home page without login.

Please comments if any doubts or suggestions. Thank You...Good Luck!!