Wednesday, July 24, 2013

Android GPS Using. How to get current location example

To use GPS in your application first of all you must specify the uses-permission in Android manifest file

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

If you don’t set this permission the application can’t get access to location service.
To use this application with android emulator you must mock location data. To do this using Eclipse you must:
  • Select Window > Show View > Other > Emulator Control
  • In Emulator Control panel enter the GPS coordinates under Location Controls and press Send
This operation you must do every time then you Run application.
Below you can see the application activity (MainCoordinate.java) source. Below you can download the source code of this Android project.
package com.muchbeer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {

 private EditText editTextShowLocation;
 private Button buttonGetLocation;
 private ProgressBar progress;

 private LocationManager locManager;
 private LocationListener locListener = new MyLocationListener();

 private boolean gps_enabled = false;
 private boolean network_enabled = false;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);

  progress = (ProgressBar) findViewById(R.id.progressBar1);
  progress.setVisibility(View.GONE);

  buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
  buttonGetLocation.setOnClickListener(this);

  locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
 }

 @Override
 public void onClick(View v) {
  progress.setVisibility(View.VISIBLE);
  // exceptions will be thrown if provider is not permitted.
  try {
   gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
  } catch (Exception ex) {
  }
  try {
   network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
  } catch (Exception ex) {
  }

  // don't start listeners if no provider is enabled
  if (!gps_enabled &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; !network_enabled) {
   AlertDialog.Builder builder = new Builder(this);
   builder.setTitle("Attention!");
   builder.setMessage("Sorry, location is not determined. Please enable location providers");
   builder.setPositiveButton("OK", this);
   builder.setNeutralButton("Cancel", this);
   builder.create().show();
   progress.setVisibility(View.GONE);
  }

  if (gps_enabled) {
   locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
  }
  if (network_enabled) {
   locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
  }
 }

 class MyLocationListener implements LocationListener {
  @Override
  public void onLocationChanged(Location location) {
   if (location != null) {
    // This needs to stop getting the location data and save the battery power.
    locManager.removeUpdates(locListener); 

    String londitude = "Londitude: " + location.getLongitude();
    String latitude = "Latitude: " + location.getLatitude();
    String altitiude = "Altitiude: " + location.getAltitude();
    String accuracy = "Accuracy: " + location.getAccuracy();
    String time = "Time: " + location.getTime();

    editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
    progress.setVisibility(View.GONE);
   } 
  }

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

  }

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

  }

  @Override
  public void onStatusChanged(String provider, int status, Bundle extras) {
   // TODO Auto-generated method stub

  }
 }

 @Override
 public void onClick(DialogInterface dialog, int which) {
  if(which == DialogInterface.BUTTON_NEUTRAL){
   editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
  }else if (which == DialogInterface.BUTTON_POSITIVE) {
   startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
  }
 }

}


For more detail information please visit: http://www.hrupin.com/2011/04/android-gps-using-how-to-get-current-location-example


Monday, July 15, 2013

android tutorial Adding Search Functionality to ListView





Adding search functionality to listview will filters the list data with a matching string, hence provides user an easy way to find the information he needs. In this tutorial i am discussing how to enable search filter to android ListView.

1. Create a new project in Eclipse File New ⇒ Android ⇒ Application Project and fill the required details.
2. Create required files needed to generate a listview. I am using my defaultactivity_main.xml as listview and created a new xml file for single listitem namedlist_item.xml. Also make sure that you have created a EditText above the listview which will be used to search the listview.

activity_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" >
     
    <!-- Editext for Search -->
    <EditText android:id="@+id/inputSearch"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Search products.."
        android:inputType="textVisiblePassword"/>
  
    <!-- List View -->
    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
  
</LinearLayout>


list_item.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" >
     
    <!-- Single ListItem -->
     
    <!-- Product Name -->
    <TextView android:id="@+id/product_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold"/>   
</LinearLayout>


3. Now open your MainActivity.java and paste the following code to create a simple ListView.
In the following code i stored all the list data in an array called products[] and attached to listview 
using simple ArrayAdapter.

MainActivity.java
package king.muchbeer.androidlistviewwithsearch;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
     
    // List view
    private ListView lv;
     
    // Listview Adapter
    ArrayAdapter<String> adapter;
     
    // Search EditText
    EditText inputSearch;
     
     
    // ArrayList for Listview
    ArrayList<HashMap<String, String>> productList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // Listview Data
        String products[] = {"Dell Inspiron""HTC One X""HTC Wildfire S""HTC Sense""HTC Sensation XE",
                                "iPhone 4S""Samsung Galaxy Note 800",
                                "Samsung Galaxy S3""MacBook Air""Mac Mini""MacBook Pro"};
         
        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
         
        // Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
        lv.setAdapter(adapter);
         
        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {
             
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                MainActivity.this.adapter.getFilter().filter(cs);  
            }
             
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub
                 
            }
             
            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                         
            }
        });
    }   
}

Android ListView



Enabling Search Functionality

4. Search functionality can be enabled by writing simple lines of code. All you need to do is adding addTextChangedListener to EditText. Once user enters a new data in EditText we need to get the text from it and passing it to array adapter filter. All the following code in your MainActivity.java
MainActivity.java
inputSearch.addTextChangedListener(new TextWatcher() {
     
    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);  
    }
     
    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub
         
    }
     
    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub                         
    }
});
5. Finally add the following property in your AndroidManifest.xml file to hide the keyboard 
on loading Activity.

AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="king.muchbeer.androidlistviewwithsearch"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



Image of final output