Search Tutorials

Thursday 31 October 2013

Shared Preferences Android Example

In this application, we will learn how to use shared preference in android. Shared preferences is used to save the value in cache where we can retrieve and save any value very fast but the cache memory is very small in mobile devices so we used it mostly to save only user name and password in session management, game level, score in game or any application, etc. Let's start with this application, create new project and drop edit text, button and text view and give id editText1, button1 and textView1 respectively. We will take value from edit text and save it to shared preferences and retrieve saved value and display on text view. The code of android XML file is given below:

Shared Preferences in Android
Shared Preferences Android Exmaple

<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:background="#abc" >
<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="44dp"
   android:ems="10" >
  <requestFocus />
</EditText>
<Button
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_below="@+id/editText1"
   android:layout_centerHorizontal="true"
   android:onClick="action"
   android:text="Button" />
<TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_centerVertical="true"
   android:text=" "
   android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Now open Java file and initialize all objects. Give name to your shared Preferences space and open it privately. Use key value to store in shared preferences and we can retrieve the saved value using key value. The code of android Java file is given below with explanation:


package com.example.sharedpr; //your package name

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
  EditText tv1=null;
  SharedPreferences sp=null;
  Button bt=null;
  TextView text=null;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //initialize all view objects
    tv1=(EditText)findViewById(R.id.editText1);
    bt=(Button)findViewById(R.id.button1);
    text=(TextView)findViewById(R.id.textView1);
    //give share memory name and mode
    sp=getSharedPreferences("First_share_memory", Activity.MODE_PRIVATE);
   }
   //This method will execute when we click on button
   public void action(View v)
   {
   //Get Text from Edit text box and save in a string
   String str1=tv1.getText().toString();
   //save in cache (Shared Preference)
   sp.edit().putString("share_key", str1).commit();
   //retrieve from cache (Shared Preference)
   String saved_value=sp.getString("share_key",null);
   //Display Shared Preference value on text view
   text.setText("Shared Preference value= "+saved_value);
   }
}

Now run you project and test this application. If you have any doubts please comment. Share and and help all developers.

Related Tutorials:-

Use SQLite Database

Enable and Disable WiFi

Enable and Disable Bluetooth

Get Latitude and Longitude of the current Location

Use Sensor | Motion detection

Convert Text to Speech

Convert Text to Speech in Android

This is a text to speech android application which takes text from edit text and speaks in a given language. Create new android project and drop text view, edit text, button on linear layout and give id txtText to edit text and btnspeak to button. The code of android XML file is given below:

Convert Text to Speech in Android
Convert Text to Speech in Android

<?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"
   android:background="#345" >
 
<TextView android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Text To Speech"
   android:padding="15dip"
   android:textColor="#0587d9"
   android:textSize="26dip"
   android:gravity="center"
   android:textStyle="bold"/>
 
<EditText android:id="@+id/txtText"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:hint="Enter some text to speak"
   android:layout_marginTop="20dip"
   android:layout_margin="10dip"/>
 
<Button android:id="@+id/btnSpeak"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Speak Out"
   android:layout_margin="10dip"/>
</LinearLayout>

Now open Java file and initialize TTS (Text To Speech) object and check given language is available or not, given language is supported or not, etc. The code of android Java file is given below with explanation:


package com.innosen.texttospeech; //your package name

import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
  private int result=0;
  private TextToSpeech tts;
  private Button btnSpeak;
  private EditText txtText;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tts = new TextToSpeech(this, this);
    btnSpeak = (Button)findViewById(R.id.btnSpeak);
    txtText = (EditText)findViewById(R.id.txtText);
    //button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View arg0) {
          speakOut();
        }
    });
  }
  //shutdown tts when activity destroy
  @Override
  public void onDestroy() {
  // Don't forget to shutdown!
  if (tts != null) {
    tts.stop();
    tts.shutdown();
   }
   super.onDestroy();
  }
  //It will called before TTS started
  @Override
  public void onInit(int status) {
  // TODO Auto-generated method stub
  //check status for TTS is initialized or not
  if (status == TextToSpeech.SUCCESS) {
  //if TTS initialized than set language
  result = tts.setLanguage(Locale.US);

  // tts.setPitch(5); // you can set pitch level
  // tts.setSpeechRate(2); //you can set speech speed rate

  //check language is supported or not
  //check language data is available or not
 if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
   Toast.makeText(this, "Missing data", Toast.LENGTH_LONG).show();
   //disable button
   btnSpeak.setEnabled(false);
  } else {
   //if all is good than enable button convert text to speech
   btnSpeak.setEnabled(true);
   }
  } else {
      Log.e("TTS", "Initilization Failed");
     }
  }
  //call this method to speak text
  private void speakOut() {
  String text = txtText.getText().toString();
  if(result!=tts.setLanguage(Locale.US))
  {
  Toast.makeText(getApplicationContext(), "Enter right Words...... ", Toast.LENGTH_LONG).show();
  }else
   {
    //speak given text
    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
   }
  }
}

Enter some text in Edit text box and click on given below button and listen voice. Voice may not come if you are testing this project on emulator, so install .APK file of this project in your mobile and use. If you any doubts please comment. Share this post and help all android developers.

Related Tutorials:-

Play mp3 file from a project folder

Use SQLite Database

Enable and Disable WiFi

Enable and Disable Bluetooth

Get Latitude and Longitude of the current Location

Use Sensor | Motion detection

Monday 28 October 2013

Motion detection using Sensor in Android

In this application, we will learn how to use Sensor and how to perform action if we shake device in any direction. There are many sensors available in mobile devices but usually all mobile device have Accelerometer sensor and this sensor is used to catch motion of the device. So we can easily find direction in which mobile is moving. So let’s start to get direction of the mobile motion, create new project and drop one text view and give id textView1 which will use to display random number on every shake of mobile in any direction. The code of android XML file is given below:

Android Sensor ExampleMotion detection using Sensor in Android

<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:background="#d56"
   android:orientation="vertical" >

<TextView
   android:id="@+id/textView1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:text=""
   android:gravity="center"
   android:textSize="400sp" />
</LinearLayout>

Now open your Java file and use Sensor manager to get sensor services. Register your Sensor object to Accelerometer sensor and give delay according to your application, use game delay in game application. Now whenever we shake our mobile device in any direction than onSensorChanged() method will call and object of SensorEvent will keep the new direction (axis) values (i.e. x, y and z). Now take these values and use in any action, we can perform different action on every different axis, but here we are using all values and performing an action if device shakes in any direction. The code of android Java file is given below with explanation:


package sense.nonsense; //your package name

import java.util.Random;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;

public class MainActivity extends Activity implements SensorEventListener {
  SensorManager sm;
  TextView tv;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   tv=(TextView)findViewById(R.id.textView1);
   //get sensor service
   sm=(SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
   //Tell which sensor you are going to use
   //And declare delay of sensor
   //Register all to your sensor object to use
 sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy)
  {
   // TODO Auto-generated method stub
  }
  //This method is called when your mobile moves any direction
  @Override
  public void onSensorChanged(SensorEvent event)
  {
   if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER)
   {
    //get x, y, z values
    float value[]=event.values;
    float x=value[0];
    float y=value[1];
    float z=value[2];
    //use the following formula
   //use gravity according to your place if you are on moon than use moon gravity
   float asr=(x*x+y*y+z*z)/(SensorManager.GRAVITY_EARTH*
SensorManager.GRAVITY_EARTH);
   //If mobile move any direction then the following condition will become true
   if(asr>=2)
     {
      //Generate random number every time and display on text view
      Random r=new Random();
      int i=r.nextInt(10);
      tv.setText(""+i);
     }
    }
  }
}
 

Now run your project and install .apk file in your mobile and test. You can’t test it on emulator because you can’t shake your emulator and there is no sensor in emulator. If you have any doubts please comment.

Related Tutorials:-

Convert Text to Speech

Use Shared Preferences

Perform action on any Hardware button

Get all Mobile Contacts

Get Battery level using Broadcast Receiver

Android Location, Address and Distance Tutorial with Example

In this application, first we will learn how to find the best location of the user. To know about location of any user, we have to find latitude and longitude of location. So create new project and drop four text view on relative layout and give id lng and lat to second and fourth text view respectively. The code of android XML file is given below:

Latitude and Longitude of current Location in Android
Latitude and Longitude of current Location in Android

<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:background="#89b" >
<TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentLeft="true"
   android:layout_alignParentTop="true"
   android:layout_marginLeft="18dp"
   android:layout_marginTop="16dp"
   android:text="Longitude:" />
<TextView
   android:id="@+id/lng"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_below="@+id/textView1"
   android:layout_marginLeft="60dp"
   android:layout_marginTop="14dp"
   android:layout_toRightOf="@+id/textView1"
   android:text=""
   android:textSize="30sp" />
<TextView
   android:id="@+id/textView3"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignRight="@+id/textView1"
   android:layout_below="@+id/lng"
   android:layout_marginTop="53dp"
   android:text="Latitude:" />
<TextView
   android:id="@+id/lat"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/lng"
   android:layout_below="@+id/textView3"
   android:text=""
   android:textSize="30sp" />
</RelativeLayout>

Now open Java file and Location manager is used to get the location service. Find the best network provider in mobile and calculate the latitude and longitude of the location. The code of android Java file is given below with explanation:

package innosen.loc; //your package name

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;

public class MainActivity extends Activity implements LocationListener{
  LocationManager lm;
  TextView lt, ln;
  String provider;
  Location l;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   ln=(TextView)findViewById(R.id.lng);
   lt=(TextView)findViewById(R.id.lat);
   //get location service
   lm=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
   Criteria c=new Criteria();
   //criteria object will select best service based on
   //Accuracy, power consumption, response, bearing and monetary cost
   //set false to use best service otherwise it will select the default Sim network
   //and give the location based on sim network 
   //now it will first check satellite than Internet than Sim network location
   provider=lm.getBestProvider(c, false);
   //now you have best provider
   //get location
   l=lm.getLastKnownLocation(provider);
   if(l!=null)
   {
     //get latitude and longitude of the location
     double lng=l.getLongitude();
     double lat=l.getLatitude();
     //display on text view
     ln.setText(""+lng);
     lt.setText(""+lat);
   }
   else
   {
    ln.setText("No Provider");
    lt.setText("No Provider");
   }
  }
   //If you want location on changing place also than use below method
   //otherwise remove all below methods and don't implement location listener
   @Override
   public void onLocationChanged(Location arg0)
   {
    double lng=l.getLongitude();
    double lat=l.getLatitude();
    ln.setText(""+lng);
    lt.setText(""+lat);
   }

  @Override
  public void onProviderDisabled(String arg0) {
   // TODO Auto-generated method stub
  }
  @Override
  public void onProviderEnabled(String arg0) {
   // TODO Auto-generated method stub
  }

  @Override
  public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
   // TODO Auto-generated method stub
  }
}

Now open AndroidManifest.xml file and take permission to use location service and to find best location. The code of AndroidManifest.xml file is given below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="selecom.loc"
   android:versionCode="1"
   android:versionName="1.0" >
<uses-sdk
   android:minSdkVersion="10"
   android:targetSdkVersion="10" />
<uses-permission         
   android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission  
   android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
   android:allowBackup="true"
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
<activity
   android:name="innosen.loc.MainActivity"
   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 your project and install .APK file in your mobile and use because if you run this application on emulator than you will not be able to find any location provider and Open your GPRS before getting Location point. If you have any doubts please comment. Share this post and help all android Developers.

Update:

I am just updating my previous post “Find Latitude and Longitude of current Location in Android” with new useful codes. I got many comments from location based tutorial post so I am going to make it more useful. What’s new in this post….

1. How to get distance between two location using latitude and longitude?

Location l1=new Location("One");
l1.setLatitude(location.getLatitude());
l1.setLongitude(location.getLongitude());
     
Location l2=new Location("Two");
l2.setLatitude(Double.parseDouble(frnd_lat));
l2.setLongitude(Double.parseDouble(frnd_longi));
     
float distance_bw_one_and_two=l1.distanceTo(l2);

2. How to get Address of any location using latitude and longitude?

Geocoder geo=new Geocoder(getApplicationContext(), Locale.getDefault());
String mylocation; if(Geocoder.isPresent()) { try { List<Address> addresses = geo.getFromLocation(l.getLatitude(), l.getLongitude(), 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); String addressText = String.format("%s, %s, %s", // If there's a street address, add it address.getMaxAddressLineIndex() > 0 ?address.getAddressLine(0) : "", // Locality is usually a city address.getLocality(), // The country of the address address.getCountryName()); mylocation="Lattitude: "+l.getLatitude()+" Longitude: "+l.getLongitude()+"\nAddress: "+addressText; } } catch (IOException e) { e.printStackTrace(); } }

3. How to get latitude and longitude using Address?


try {
        Geocoder selected_place_geocoder = new Geocoder(context);
        List<Address> address;  
        address = selected_place_geocoder.getFromLocationName(place, 5);
  if(address == null) {
   //do nothing
        } else {
        Address location = address.get(0);
  Latitude lat= location.getLatitude();
  Longitude lng = location.getLongitude();
   }
        } catch (Exception e) {
                e.printStackTrace();
 }

Hope this update make you all more happy.

Related Tutorials:-

Advance Android Google Map 2 Tutorial with Examples - Part 1

Advance Android Google Map 2 Tutorial with Examples - Part 2

Android Sensor | Motion detection Tutorial

Convert Text to Speech Tutorial

Android Shared Preferences Tutorial

Enable and Disable Bluetooth using Program in Android

In this Application, we will learn how to enable and disable bluetooth in android device using coding. We will show two methods to enable bluetooth:

1) Enable bluetooth without asking user permission.

2) Enable bluetooth with user permission (a dialog box will open to confirm to enable bluetooth).

Use any one method as per your application requirement. Here, we are taking one single button and we will use it to enable and disable blue device. So, create new project and drop a button from widget to relative layout and give id button1. The code of android XML file is given below:

Enable and Disable Bluetooth using Program in Android
Enable and Disable Bluetooth


<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:background="#024" >
<Button
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_centerVertical="true"
   android:onClick="action"
   android:text="Enable and disable bluetooth"
   android:textSize="18sp" />
</RelativeLayout>

Now open your Java file and initialize all objects. Simply use enable() and disable() method and we can use Intent to start bluetooth service which will ask permission to enable bluetooth. The code of android Java file is given below with explanation:


package innosen.com;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;

public class MainActivity extends Activity {
  BluetoothAdapter bt=null;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   //initialize bluetooth adapter object
   bt=BluetoothAdapter.getDefaultAdapter();
  }
  //this method will call when we click on button
  public void action(View v)
  {
  //if bluetooth not found
  if(bt==null)
  {
   Toast.makeText(this, "No bluetooth found.."+bt, Toast.LENGTH_LONG).show();
   }
   else
   {
     if(!bt.isEnabled())
    {
     /*****first method to enable bluetooth*****/
     //enable bluetooth without pop-up any dialog box
     bt.enable();
     /*****Second method to enable bluetooth*****/
     //Pop-up dialog box to confirm to enable bluetooth
     /*Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
     startActivity(i); */
     //Display blutooth device value on Toast
     Toast.makeText(this, "bluetooth found.."+bt, Toast.LENGTH_LONG).show();
    }
    else
    {
     //disable bluetooth
     bt.disable();
    }
   }
  }
}

Now open your AndroidManifest.xml file to take permission to use bluetooth and changing the state of bluetooth. The code of AndroidManifest.xml fiel is given below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="innosen.com"
   android:versionCode="1"
   android:versionName="1.0" >
<uses-sdk
   android:minSdkVersion="10"
   android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
   android:allowBackup="true"
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
<activity
   android:name="sel.bil.MainActivity"
   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 your project and install .apk of this project in your android mobile and test application. This application can't test on the emulator but will not give error on emulator.
If you have any doubts please comment. Thanks... :)
Back to Top