Wednesday 24 September 2014

How to Make Android Map Scrollable Inside a ScrollView Layout

package com.technomobs.Utils;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.google.android.gms.maps.SupportMapFragment;

public class MyMapFragment extends SupportMapFragment {
private OnTouchListener mListener;

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstance) {
        View layout = super.onCreateView(layoutInflater, viewGroup, savedInstance);

        TouchableWrapper frameLayout = new TouchableWrapper(getActivity());

        frameLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));

        ((ViewGroup) layout).addView(frameLayout,
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        return layout;
    }

    public void setListener(OnTouchListener listener) {
    mListener = listener;
    }

    public interface OnTouchListener {
    public abstract void onTouch();
    }

    public class TouchableWrapper extends FrameLayout {

      public TouchableWrapper(Context context) {
        super(context);
      }

      @Override
      public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
         mListener.onTouch();
                break;
          case MotionEvent.ACTION_UP:
         mListener.onTouch();
                break;
        }
        return super.dispatchTouchEvent(event);
      }
    }
}

...............................................

Then  create layout using following code


<?xml version="1.0" encoding="UTF-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sv_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- other child views //-->
     <fragment
        android:tag="fragment_map"
       android:id="@+id/fragment_map"
       android:layout_width="match_parent"
       android:layout_height="175dp"
       android:layout_marginTop="@dimen/activity_horizontal_margin"
       class="com.technomobs.Utils.MyMapFragment"/>
</ScrollView>

.................................


Inside map activity that uses the map,



package com.technomobs.main;
import com.technomobs.Utils.MyMapFragment ;
import com.google.android.gms.maps.GoogleMap;
import android.widget.ScrollView;

public class MyMapActivty extends MapActivity {
    private ScrollView mScrollView;
    private GoogleMap mMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_my_map);

        mMap = ((MyMapFragment ) getSupportFragmentManager().findFragmentById(R.id.fragment_map)).getMap();
        mScrollView = (ScrollView) findViewById(R.id.sv_container);

       ((MyMapFragment ) getSupportFragmentManager().findFragmentById(R.id.fragment_map)).setListener(new WorkaroundMapFragment.OnTouchListener() {
          @Override
          public void onTouch() {
              mScrollView.requestDisallowInterceptTouchEvent(true);
          }
     });
   }
}

Sunday 21 September 2014

Check EditText View Empty or Not in Android

public class Util
{


public static boolean isEmpty(EditText etText) {
   if (etText.getText().toString().trim().length() > 0) {
       return false;
   } else {
       return true;
   }
}


}


..........................


public class MainActivity
  extends Activity
{

EditText sample;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createaccount);
sample=(EditText)findViewById(R.id.sample);
if(Util.emailValidator(sample)){
                                                // edittext box empty
                                                      }
                                                        else{



                                                         }

Hide Keyboard in android

public class Util
{


public static void onHideKeyboard(Activity context)
{
try{
InputMethodManager imm = (InputMethodManager) context
           .getSystemService(Context.INPUT_METHOD_SERVICE);

   if (imm.isAcceptingText()) {
     
    imm.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), 0);
   } else {
       //Log.e("Software Keyboard was not shown","no");
   }
}catch(Exception e)
{

}
}

}


..........................


Call in Activity

String name="abcd@gmail.com";

public class MainActivity
  extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createaccount);


//Hide Keyboard in android
Util.onHideKeyboard(MainActivity.this);


}

}

email Validation in Android

public class Util
{


public static boolean emailValidator(String email)
{
   Pattern pattern;
   Matcher matcher;
   final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
   pattern = Pattern.compile(EMAIL_PATTERN);
   matcher = pattern.matcher(email);
   return matcher.matches();
}


}


..........................


Call in Activity

public class MainActivity
  extends Activity
{

String emailSample="abcd@gmail.com"
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(Util.emailValidator(emailSample)){
                                                // email format is correct
                                                      }
                                                        else{

                                                         }


}

}


Set Font in android

publi class Util{
public static void setFont(TextView textview, String font) {

Typeface myTypeface = Typeface.createFromAsset(textview.getContext().getAssets(), font);
textview.setTypeface(myTypeface);

}

}
........................................................

In side Activity Class the following code

put HelveticaNeue-Medium.ttf font type into assets

assets->create folder fonts ->HelveticaNeue-Medium.ttf


TextView name=(TextView)findViewById(R.id.name);
//set font
Util.setFont(name, "fonts/HelveticaNeue-Medium.ttf");

Network Availability check in Android

public static boolean isNetworkAvailable(Context act) {
        ConnectivityManager connectivityManager
              = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

if(isNetworkAvailable(MainActivity.this)
{
//connection avilable
}
else{
//no connection

}

GPS Tracker in Android

class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

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

        return location;
    }
   
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }    
    }
   
    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
       
        // return latitude
        return latitude;
    }
   
    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
       
        // return longitude
        return longitude;
    }
   
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
   
    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
     
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");
 
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
 
        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
//                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                mContext.startActivity(intent);
            }
        });
 
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
 
        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
   
   
   
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}



...............................................

Calling in Activity


GPSTracker gPSTracker;

        gPSTracker=new GPSTracker(getActivity());
//Locate current location
if (gPSTracker.canGetLocation())
{
stringLatitude = String.valueOf(gPSTracker.getLatitude());
stringLongitude = String.valueOf(gPSTracker.getLongitude());
//String place=gPSTracker.getLocality(getApplicationContext());
Double locationLatitude=Double.parseDouble(stringLatitude);
Double locationLongitude=Double.parseDouble(stringLongitude);
}