Monday 31 July 2017

Dialog with MultipleChoice ListView

ScreenShots:





strings.xml:

<resources>     <string name="app_name">Dialog with Multiple Choice</string>     <string-array name="ITEMS">         <item>Item1</item>         <item>Item2</item>         <item>Item3</item>         <item>Item4</item>         <item>Item5</item>     </string-array> </resources>
activity_main.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">
    <Button         android:id="@+id/button_dialogList"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Dialog List" />     <TextView         android:id="@+id/textview"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginLeft="10dp"         android:layout_marginTop="20dp"         android:textSize="30sp"         android:textStyle="bold" /> </LinearLayout>
MainActivity.java:
package com.ramsandroid.dialogwithmultiplechoice; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements View.OnClickListener {     ArrayList<Integer> selectedItems;     TextView textView;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         selectedItems = new ArrayList<>();         textView = (TextView) findViewById(R.id.textview); Button button_dialogList = (Button) findViewById(R.id.button_dialogList);         button_dialogList.setOnClickListener(this);     }     @Override    public void onClick(View v) {   AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);         builder.setTitle("Select Item");         builder.setMultiChoiceItems(R.array.ITEMS, null, new DialogInterface.OnMultiChoiceClickListener() {             @Override             public void onClick(DialogInterface dialog, int which, boolean isChecked) {                 if (isChecked) {                     selectedItems.add(which);                 } else
if (selectedItems.contains(which)) {           selectedItems.remove(Integer.valueOf(which));                 }             }         });         builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {             @Override             public void onClick(DialogInterface dialog, int which) {                 for (Integer i : selectedItems) {     String[] ITEMS = getResources().getStringArray(R.array.ITEMS);                     textView.append(ITEMS[i] + "\n");               }             }         });         builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {             @Override       public void onClick(DialogInterface dialog, int which) {                 selectedItems.clear();             }         });         builder.create().show();     } }

Tuesday 20 June 2017

Bottom NavigationView Example

Download Complete Project Here :BottomNavigationView.zip

screenshot:


build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion
25
   
buildToolsVersion "25.0.2"
   
defaultConfig {
        applicationId
"com.ramsandroid.bottomnavigationviewexample"
       
minSdkVersion 15
       
targetSdkVersion 25
       
versionCode 1
       
versionName "1.0"
       
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
       
vectorDrawables.useSupportLibrary = true
   
}
    buildTypes {
        release {
            minifyEnabled
false
           
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       
}
    }
}

dependencies {
    compile fileTree(
dir: 'libs', include: ['*.jar'])
    androidTestCompile(
'com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude
group: 'com.android.support', module: 'support-annotations'
   
})
    compile
'com.android.support:appcompat-v7:25.1.1'
   
compile 'com.android.support:design:25.1.1'
   
compile 'com.android.support:support-vector-drawable:25.1.1'
   
testCompile 'junit:junit:4.12'
}


strings.xml:

<resources>
    <string name="app_name">Bottom NavigationView Example</string>
    <string name="title_home">Home</string>
    <string name="title_dashboard">Search</string>
    <string name="title_notifications">Notifications</string>
</resources>


create navigation.xml file under menu folder and keep following code and you can icons from downloaded project
  

<?xml version="1.0" encoding="utf-8"?>
<
menu xmlns:android="http://schemas.android.com/apk/res/android">

    <
item
       
android:id="@+id/navigation_home"
       
android:icon="@drawable/home"
       
android:title="@string/title_home" />

    <
item
       
android:id="@+id/navigation_dashboard"
       
android:icon="@drawable/search"
       
android:title="@string/title_dashboard" />

    <
item
       
android:id="@+id/navigation_notifications"
       
android:icon="@drawable/notifications"
       
android:title="@string/title_notifications" />

</
menu>


activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:id="@+id/container"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:orientation="vertical"
   
tools:context="com.ramsandroid.bottomnavigationviewexample.MainActivity">

    <
FrameLayout
       
android:id="@+id/content"
       
android:layout_width="match_parent"
       
android:layout_height="0dp"
       
android:layout_weight="1">

        <
TextView
           
android:id="@+id/message"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_marginBottom="@dimen/activity_vertical_margin"
           
android:layout_marginLeft="@dimen/activity_horizontal_margin"
           
android:layout_marginRight="@dimen/activity_horizontal_margin"
           
android:layout_marginTop="@dimen/activity_vertical_margin"
           
android:text="@string/title_home" />

    </
FrameLayout>

    <
android.support.design.widget.BottomNavigationView
       
android:id="@+id/navigation"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_gravity="bottom"
       
android:background="?android:attr/windowBackground"
       
app:menu="@menu/navigation" />

</
LinearLayout>

MainActivity.java:
package com.ramsandroid.bottomnavigationviewexample;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;
    @Override
   
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
           
= new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
       
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                    return true;
                case R.id.navigation_notifications:

                    mTextMessage.setText(R.string.title_notifications);
                    return true;
            }
            return false;
        }

    };



}

Thursday 16 February 2017

Service Example with Getting Running Services from the device

MyService.java:
 package com.ramsandroid.demo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(getApplicationContext(),
        "service created",Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent,  int flags, 
                                           int startId) {
        Toast.makeText(getApplicationContext(),
             "service started",Toast.LENGTH_SHORT).show();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),
              "service stopped",Toast.LENGTH_SHORT).show();

    }
}



activity_main.java:
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ramsandroid.demo.MainActivity">


    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="27dp"
        android:text="Switch"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    
</RelativeLayout>


MainActivity.java:
 package com.ramsandroid.demo;

import android.app.ActivityManager;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActivityManager am = (ActivityManager)
                  this.getSystemService(ACTIVITY_SERVICE);

        List<ActivityManager.RunningServiceInfo> rs = 
                  am.getRunningServices(Integer.MAX_VALUE);

        Switch aSwitch=(Switch)findViewById(R.id.switch1);

        for(ActivityManager.RunningServiceInfo runningServiceInfo:rs){

            String sname = runningServiceInfo.service.getClassName();
            Log.d("MainActivity",sname);

            if(sname.equals("com.ramsandroid.demo.MyService")){
                aSwitch.setChecked(true);
            }
        }


        aSwitch.setOnCheckedChangeListener
               (new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged
                  (CompoundButton compoundButton, boolean b) {
                Intent intent=
                   new Intent(getApplicationContext(),MyService.class);

                if(b){
                    startService(intent);
                }else{
                    stopService(intent);
                }
            }
        });
    }

    
}

Wednesday 17 August 2016

HttpURLConnection with JSON Parsing Android Example (Android Studio Project)

Download this project here : HttpURLConnection with JSONParsing

Most Network - Connected Android apps use HTTP to send and receive data.
The Android platform includes the HttpURLConnection client.

Before performing network related operations we need to check whether device is connected to network or not and then proceed to perform network operations.

Screenshot of the output:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ramsandroid.httpurlconnection">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textSize="20sp"/>
    </ScrollView>
</RelativeLayout>

MainActivity.java:
package com.ramsandroid.httpurlconnection;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textview);

        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            MyAsync myAsync = new MyAsync();
            myAsync.execute();
        } else {
            AlertDialog.Builder builder = new AlertDialog.
                                                  Builder(MainActivity.this);
            builder.setTitle("Alert!");
            builder.setMessage("Please check your network connection");
            builder.setPositiveButton("OK", 
                                              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            });
            builder.create().show();
        }
    }

    class MyAsync extends AsyncTask<Void, Void, String> {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "downloading", "please wait");
        }

        @Override
        protected String doInBackground(Void... voids) {
            String result = null;
            try {
                URL url = new URL("http://api.androidhive.info/contacts/");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                result = inputStreamToString(in);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressDialog.dismiss();
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("contacts");
                for (int i = 0; i < jsonArray.length(); i++) {
                    String id = jsonArray.getJSONObject(i).getString("id");
                    String name = jsonArray.getJSONObject(i).getString("name");
                    String email = jsonArray.getJSONObject(i).getString("email");

                    String mobile = jsonArray.getJSONObject(i).getJSONObject("phone").getString("mobile");

                    textView.append(id + "\n");
                    textView.append(name + "\n");
                    textView.append(email + "\n");
                    textView.append(mobile + "\n\n");

                }

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

        }
    }

    private String inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();

        InputStreamReader isr = new InputStreamReader(is);

        BufferedReader rd = new BufferedReader(isr);

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return answer.toString();
    }
}

Tuesday 1 March 2016

Finding Current Location Example using Android Studio with Android 6.0 Runtime Permissions

Output Screen Shots:

Example Code :
------------------
Note : Before to understand this example please go through Android 6.0 Runtime permissions tutrials below
http://ramsandroid4all.blogspot.in/2015/12/requesting-permissions-at-run-time-in.html

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ramsandroid.findingcurrentlocation">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

MainActivity.java:
package com.ramsandroid.findingcurrentlocation;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    static final int REQUEST_LOCATION = 1;
    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        getLocation();
    }

    void getLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        } else {
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            if (location != null) {
                double latti = location.getLatitude();
                double longi = location.getLongitude();

                ((TextView) findViewById(R.id.textView)).
                        setText("Current Location is :" + latti + "," + longi);
            } else {
                ((TextView) findViewById(R.id.textView)).
                        setText("Unable to find current location . Try again later");
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case REQUEST_LOCATION:
                getLocation();
                break;
        }
    }

}


 

Wednesday 6 January 2016

Google Maps Android Example in Android Studio (with updated code Android 6.0)


Step 1 : Setup Google Play Services support in Android Studio as follows

  • open build.gradle(Module: app) file under Gradle Scripts and add google play service support under dependencies as follows.
build.gradle(Module: app):

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.ramsandroid.mapsv2example"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.android.gms:play-services:8.4.0'
}


Step 2 : Generate SHA-1 fingerprint certificate key in Android Studio by following the steps given 
              below.
  • 1.Open Android Studio
  • 2.Open Your Project
  • 3.Click on Gradle (From Right Side Panel, you will see Gradle Bar)
  • 4.Click on Refresh (Click on Refresh from Gradle Bar, 
  •                     you will see List Gradle scripts of your Project)
  • 5.Click on Your Project (Your Project Name form List (root))
  • 6.Click on Tasks
  • 7.Click on android
  • 8.Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)


Step 2 : Generate google maps api key by using following steps:
  • sigin into following web site by using your google account user name and password https://console.developers.google.com
  • Next from top right corner of the web site you can one drop down box from that select create new project option and create new one by providing project name. 
  • Next select google api's option and next uder google maps apis select Google Maps Android API and enable this api by selecting enable api option.
  • Next select credentials option from left side of the web site.
  • Next under New credentials select API key option next select Android Key and next select Add Package name and fingerprint and in next window provide your application package name SHA-1 certificate fingerprint key from Android Studio after click create button. next maps api  key will be generated next we are going to use this key in side application by using following procudure.
Step 3 :Insert following code into the AndroiManifest.xml file as follows

AndroidManifest.xml:

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

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!--
     The following two permissions are not required to use
     Google Maps Android API v2, but are recommended.
    -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <permission
        android:name="your app package name.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="your app package name.permission.MAPS_RECEIVE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <meta-data
            android:name="com.google.android.gms.version"

            android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="place maps api key here" />
    </application>

</manifest>

Step 4 : Insert following code into your xml layou file

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Step 5 : If you want to see your current location in the map using marker add following in the activity as follows

MainActivity.java:

package com.ramsandroid.mapsv2example;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
    GoogleMap map;
    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(this);

        //  map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;


        // map.setMyLocationEnabled(true);


    }

    @Override
    public void onLocationChanged(Location location) {

        map.clear();
        LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());


        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(currentLocation);
        markerOptions.title("i'm here");

        map.addMarker(markerOptions);

        // map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 17.0f));

        map.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 17.0f));
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}




Tuesday 5 January 2016

Snackbar in Android (Material design)

Screen Shot:

This is Android Studio Project:

Include following dependency in your build.gradle file

build.gradle:
 apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.ramsandroid.snackbarexample"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.0.1'
}



activity_main.java:
<?xml version="1.0" encoding="utf-8"?>
<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="com.ramsandroid.snackbarexample.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Snack Bar"
        android:id="@+id/button_snackbar"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp" />
</RelativeLayout>

MainActivity.java:
package com.ramsandroid.snackbarexample;

import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button snackBarButton = (Button) findViewById(R.id.button_snackbar);
        snackBarButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                Snackbar snackbar = Snackbar.make(v, "Snackbar working", Snackbar.LENGTH_LONG);
                snackbar.show();

            }
        });
    }
}