Wednesday, 30 November 2016

Fused location provider api example

The best thing about Fused location provider API is that you not need to worry about location updates it gives you always latest and accurate location and updates location after a interval or on location change .
One more thing about Fused location provider API is you don't need to think about best location provider because it automatically choose best one suited for your hardware of  your android device.

Now Lets start with coding. like every post i am going to make a module of our all steps to complete code.

    1. In this step we will create a new project in Android studio.
    2. we will add Google Play service in our build.gradle.
    3. In third step we will modify manifest file of our project to add location permission.
    4. we will add two TextView to our activity_main.xml to show latitude and longitude.  
    5. This will be our final step in this we will start and complete our MainAcitvity.java.

      • So lets start with coding open your Android studio and go to File-->>New Project.

                
           select an Empty Activity and left everything as default.
          • Open build.gradle(Module:app) from project explorer and add google play services to it. in simple copy below line of code and paste it under dependency of build.gradle(Module:app) like below image.

                         compile 'com.google.android.gms:play-services:8.1.0' 


            • Open manifest file and add location permission for  that you need to copy and  paste below code to your manifest file above <application tag like show in picture below.

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


            •  you need to add one more line to manifest but this will be inside <application> so just copy and   paste below code to manifest.this is version number of your gms.


            <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
            

                 Now here my manifest looks like below image.


            • Now open your activity_main.xml and add two TextView like below code.

            <?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=".MainActivity">
            
                <TextView
                    android:id="@+id/textView"
                    android:layout_margin="20dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Latitude"
                    android:layout_centerVertical="true"
                    android:layout_centerHorizontal="true" />
            
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Longitude"
                    android:id="@+id/textView2"
                    android:layout_above="@+id/textView"
                    android:layout_centerHorizontal="true" />
            
            
            </RelativeLayout>
            

            • Now open your MainActivity.java here we will implement three interface 
            1. ConnectionCallbacks
            2. OnConnectionFailedListener
            3. LocationListener

            public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
                    GoogleApiClient.OnConnectionFailedListener, LocationListener{
            

            • After implement of these three interface android studio will show you an error click on error and click on implement methods.this will implement four method to your class like below code.
             
            @Override
                public void onConnected(Bundle bundle) {
                    
                }
            
                @Override
                public void onConnectionSuspended(int i) {
            
                }
            
                @Override
                public void onLocationChanged(Location location) {
            
                }
            
                @Override
                public void onConnectionFailed(ConnectionResult connectionResult) {
            
                }
            

            • Now i am going to add two TextView, GoogleApiClient, LocationRequest, Location and two string varriable to our MainActivity.java class like below code. just copy and paste these codes above your onCreate() method.

                TextView txtOutputLat, txtOutputLon;
                Location mLastLocation;
                private GoogleApiClient mGoogleApiClient;
                private LocationRequest mLocationRequest;
                String lat,lon;
            

            • Now we will make a method to build GoogleApiClient , name of method will be buildGoogleApiClient(). in this method we will build GoogleApiClient and will add these to GoogleApiClient . 
            • OnConnectionFailedListener
            • Api(LocationServices.API)
            • ConnectionCallbacks
                  Here is my snippet of  buildGoogleApiClient().

            synchronized void buildGoogleApiClient() {
                    mGoogleApiClient = new GoogleApiClient.Builder(this)
                            .addConnectionCallbacks(this)
                            .addOnConnectionFailedListener(this)
                            .addApi(LocationServices.API)
                            .build();
            
            
                }
            

              • we also need to override onStart() and onDestroy() method of activity. in onStart() method we will connect GoogleApiClient and in onDestroy() we will disconnect it like below code.


              @Override
                  protected void onStart() {
                      super.onStart();
                      mGoogleApiClient.connect();
                  }
              
                  @Override
                  protected void onDestroy() {
                      super.onDestroy();
                      mGoogleApiClient.disconnect();
                  }
              

              • Now inside onConnected() we will create object of  LocationRequest, add priority of  accuracy  and will set interval to get location update and after that will make a request to get  last Location like below code. just copy and paste this code inside onConnected() method.in my code i am setting accuracy to High and interval is 10 second.

               mLocationRequest = LocationRequest.create();
                      mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                      mLocationRequest.setInterval(10000); // Update location every second
              
                      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
              
              
                      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                              mGoogleApiClient);
                      if (mLastLocation != null) {
                          lat = String.valueOf(mLastLocation.getLatitude());
                          lon = String.valueOf(mLastLocation.getLongitude());
              
                      }
              

              • Everything is set now we are going to complete  last few step. I am going to make a method called updateUI()and in this method i will set value of latitude and longitude to  TextView and make a call of this updateUI()method in onConnected() and onLocationChange(). here is updateUI() method.

              void updateUI() {
                      txtOutputLat.setText(lat);
                      txtOutputLon.setText(lon);
                  }
              

              • we have finished all the step here is my complete MainActivity.java class.

              import android.location.Location;
              import android.support.v7.app.AppCompatActivity;
              import android.os.Bundle;
              import android.util.Log;
              import android.view.View;
              import android.widget.Button;
              import android.widget.TextView;
              
              import com.google.android.gms.common.ConnectionResult;
              import com.google.android.gms.common.api.GoogleApiClient;
              import com.google.android.gms.location.LocationListener;
              import com.google.android.gms.location.LocationRequest;
              import com.google.android.gms.location.LocationServices;
              
              public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
                      GoogleApiClient.OnConnectionFailedListener, LocationListener {
              
              
                  TextView txtOutputLat, txtOutputLon;
                  Location mLastLocation;
                  private GoogleApiClient mGoogleApiClient;
                  private LocationRequest mLocationRequest;
                  String lat, lon;
              
              
                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.activity_main);
              
              
                      txtOutputLat = (TextView) findViewById(R.id.textView);
                      txtOutputLon = (TextView) findViewById(R.id.textView2);
              
              
                      buildGoogleApiClient();
                  }
              
              
                  @Override
                  public void onConnected(Bundle bundle) {
              
              
                      mLocationRequest = LocationRequest.create();
                      mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                      mLocationRequest.setInterval(100); // Update location every second
              
                      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
              
              
                      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                              mGoogleApiClient);
                      if (mLastLocation != null) {
                          lat = String.valueOf(mLastLocation.getLatitude());
                          lon = String.valueOf(mLastLocation.getLongitude());
              
                      }
                      updateUI();
                  }
              
                  @Override
                  public void onConnectionSuspended(int i) {
              
                  }
              
                  @Override
                  public void onLocationChanged(Location location) {
                      lat = String.valueOf(location.getLatitude());
                      lon = String.valueOf(location.getLongitude());
                      updateUI();
                  }
              
                  @Override
                  public void onConnectionFailed(ConnectionResult connectionResult) {
                      buildGoogleApiClient();
                  }
              
                  synchronized void buildGoogleApiClient() {
                      mGoogleApiClient = new GoogleApiClient.Builder(this)
                              .addConnectionCallbacks(this)
                              .addOnConnectionFailedListener(this)
                              .addApi(LocationServices.API)
                              .build();
              
              
                  }
              
                  @Override
                  protected void onStart() {
                      super.onStart();
                      mGoogleApiClient.connect();
                  }
              
                  @Override
                  protected void onDestroy() {
                      super.onDestroy();
                      mGoogleApiClient.disconnect();
                  }
              
                  void updateUI() {
                      txtOutputLat.setText(lat);
                      txtOutputLon.setText(lon);
                  }
              }
              

              Monday, 28 November 2016

              Error:java.lang.OutOfMemoryError: GC overhead limit exceeded :app:transformClassesWithDexForRelease FAILED

              Error:java.lang.OutOfMemoryError: GC overhead limit exceeded :app:transformClassesWithDexForRelease FAILED

              -

              Add this to your android closure in your build.gradle file:
              dexOptions {
                  javaMaxHeapSize "4g"
              }
              
              
              Network topology-
              http://www.studytonight.com/computer-networks/network-topology-types

              Thursday, 24 November 2016

              Get Asynctask response using interface callback in activity and fragment

              Asynctask-

              public class ConfirmKitAsync extends AsyncTask<String,String,String > {
              
                  static MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                  String url;
                  RestUserId restUserId;
                  ProgressDialog progressDialog;
                  IConfirmKitListener responseListener;
                  Context context;
                  //   String path = null;
                  public interface IConfirmKitListener {
                      public void callbackConfirmKit(String response);
                  }
                  public void setConfirmKitListener (IConfirmKitListener listener){
                      this.responseListener = listener;
                  }
              
                  public ConfirmKitAsync(Context context, String url, RestUserId restUserId) {
              
                      this.context = context;
                      this.url = url;
                      this.restUserId = restUserId;
                 //   path = Uri.parse(url).getPath();   
                 //   responseListener = (IConfirmKitListener) context;    
                  }
              
                  @Override    
                  protected void onPreExecute() {
                      super.onPreExecute();
                      progressDialog = new ProgressDialog(context);
                      progressDialog.setMessage("Loading...");
                      progressDialog.setCanceledOnTouchOutside(false);
                      progressDialog.setCancelable(false);
                      progressDialog.show();
                  }
              
                  @Override    
                  protected String doInBackground(String... strings) {
                      String responseString = null;
                      if (isCancelled()) {
                          return null;
                      } else {
                          try {
                              Request.Builder builder = new Request.Builder().url(url);
                              RequestBody body = RequestBody.create(JSON,
                                      new Gson().toJson(restUserId));
              
                              builder.post(body);
                              OkHttpClient client = CommonTask.getCommonOkHttpCient();
                              client.setConnectTimeout(2, TimeUnit.MINUTES);
                              client.setReadTimeout(5, TimeUnit.MINUTES);
                              Response response = client.newCall(builder.build()).execute();
                              responseString = response.body().string();
              
                              return responseString;
                          } catch (SocketTimeoutException e) {
              
                          } catch (Exception e) {
                              e.printStackTrace();
                          }
                      }
                      return responseString;
                  }
              
                  @Override    
                  protected void onPostExecute(String result) {
                      if (result != null) {
                          super.onPostExecute(result);
                          try {
                              responseListener.callbackConfirmKit(result);
                          } catch (Exception e) {
                              e.printStackTrace();
                          }
                      }
                      if (progressDialog != null && progressDialog.isShowing()) {
                          progressDialog.dismiss();
                      }
                  }
              }



              for Activity-

              ConfirmKitAsync async= new ConfirmKitAsync (context,  url, restUserId);
              async.execute();

              for Fragment-

              ConfirmKitAsync async= new ConfirmKitAsync(context,  uri, restUserId);
              async.setConfirmKitListener(this);
              async.execute();
              
              
              
              
              
              
              Callback-
              
              
              
              
              @Override
              public void callbackConfirmKit(String jsonStr) {
                  try {
                      if (jsonStr != null && jsonStr.length() > 0) {
              
                          JSONObject jsonObj = new JSONObject(jsonStr);
                          JSONObject jObj = jsonObj.getJSONObject("Data");
                          jsonArray = jObj.getJSONArray("RestWeapon");
              
                          for (int i = 0; i < jsonArray.length(); i++) {
                         }
                       }
                      }
                  catch (JSONException e){
                   e.getMessage();
                  }
              }



              Thursday, 13 October 2016

              Shared Preference implementation

              We can save user information local to the application using shared preferences.  This information persist till the application is install in your device. 


              public class MySharedPreference {

                  private static MySharedPreference mInstance=null;
                  private static final String PREFS_NAME = "MY_PREFS";
                  private static String PREFS_USER_KEY = "PREFS_USER_NAME";
                  SharedPreferences mSharedPreferences=null;
                  SharedPreferences.Editor editor=null;

                  public MySharedPreference(Context context) {
                      this.mSharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                      this.editor = mSharedPreferences.edit();
                  }

                  public static MySharedPreference getInstance(Context context){
                      if(context!=null) {
                          if (mInstance == null) {
                              mInstance = new MySharedPreference(context);
                          }
                      }
                      return mInstance;
                  }

                  public String getUserSharedPref() {
                      return this.mSharedPreferences.getString(PREFS_USER_KEY,null);
                  }

                  public void setUserSharedPref(String userName) {
                      editor.putString(PREFS_USER_KEY, userName);
                      editor.commit();
                  }
              }

              //******************************************************************//
              Save your preferences-

              MySharedPreference mPref= MySharedPreference.getInstance(context);
              mPref.setUserSharedPref(userName.getText().toString());

              //*****************************************************************//
              Get Preference Value-
              String str= MySharedPreference.getInstance(context).getUserSharedPref();


              Monday, 26 September 2016

              Make edit text not editable but clickable programmatically

              apply -
                   editText.setFocusable(false);
                   editText.setClickable(true);

              but if you want to edit text not editable and not clickable then apply
                  editText.setEnable(false);


              Wednesday, 29 June 2016

              Create custom actionBar

               android:textColorHint="@color/hint_color"
               android:background="@android:color/transparent"

              To do so, follow those 2 simple steps:

              1. Java Code

              getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
              getSupportActionBar().setCustomView(R.layout.actionbar);
              Where R.layout.actionbar is the following XML.

              2. 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="wrap_content"
                  android:layout_gravity="center"
                  android:orientation="vertical">

              <TextView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center"
                  android:text="YOUR ACTIVITY TITLE"
                  android:textColor="#ffffff"
                  android:textSize="24sp" />
              </LinearLayout>

              Saturday, 25 June 2016

              Most asked interview programs

              Program 1-    Upcasting and Downcasting

              package com.sanjay.java.basic;

              class Parent {

              /*Parent() {
              System.out.println("Parent constructor.");
              }*/

              public void show() {
              System.out.println("I am Parent class method.");
              }

              }

              public class Child extends Parent {
              /*
              Child() {
              System.out.println("Child constructor.");
              }*/

              public void show() {
              System.out.println("I am Child class method.");
              }

              static void check(Parent p) {

              Child t = (Child) p;
              t.show();
              System.out.println("Down casting done");
              }

              /**
              * @param args
              */
              public static void main(String[] args) {
              // TODO Auto-generated method stub
              System.out.println("*********Down casting*************");
              // CastingTest test=(CastingTest) new Parent(); //Exception in thread
              // "main" java.lang.ClassCastException: at run time
              Parent b = new Child();
              Child.check(b);

              System.out.println("*********up casting*************");
              Parent obj = new Child();
              obj.show();

              }

              }

              Output-
              *********Down casting*************
              I am Child class method.
              Down casting done
              *********up casting*************
              I am Child class method.


              Program 2-  Reverse Sentence

              package com.sanjay.java.basic;

              public class ReverseSentence {

              public String doReverse(String str) {

              String revStr = "";
              String sp[] = str.split(" ");

              for (int i = sp.length - 1; i >= 0; i--) {
              revStr = revStr + sp[i]+" ";
              }

              return revStr;

              }

              public static void main(String arg[]) {
              String str = "I live in delhi";
              ReverseSentence obj = new ReverseSentence();
              String reverse=obj.doReverse(str);
              System.out.println("Reverse sentence = " + reverse);
              }
              }

              Output-  
              Reverse sentence = delhi in live I 

              Program 3-      Reverse String

              package com.sanjay.java.basic;

              public class ReverseString {

              /**
              * @param args
              */
              public static void main(String[] args) {
              // TODO Auto-generated method stub

              String str="My Name is sanjay verma";
              String rev="";
              for(int i=str.length()-1;i>=0;i--){
              rev=rev+str.charAt(i);
              }
              System.out.println(rev);
              }

              }

              Output-
              amrev yajnas si emaN yM


              Program- 4  Comosition Uses [ Using composition achieve inheritance ]

              package com.sanjay.java.basic;

              class Test {
              public void name() {

              System.out.println("I am android profesional.");

              }
              }

              final class MyComposition {

              public void show() {
              System.out.println("I am Composition method.");
              }
              }


              public class CompositionTest extends Test {

              MyComposition composition;

              public void display() {

              composition = new MyComposition();
              composition.show();
              }

              /**
              * @param args
              */
              public static void main(String[] args) {
              // TODO Auto-generated method stub

              CompositionTest obj = new CompositionTest();

              obj.display();
              obj.name();

              }

              }

              Output-
              I am Composition method.
              I am android profesional.

              Program 5-  Prime Number check

              package com.sanjay.java.basic;

              public class PrimeNumber {

              public void checkPrime(int num) {
              int j = 2;
              // for (int i = 0; i <= num; i++) {
              // while(num<=500){
              while (j < num) {
              if (num % j == 0) {
              break;
              } else {
              j++;
              }

              }
              // }
              if (num == j) {
              System.out.println("Prime number -" + num);
              } else {
              System.out.println("Number is not prime");
              }
              // }
              }

              /**
              * @param args
              */
              public static void main(String[] args) {
              // TODO Auto-generated method stub

              PrimeNumber obj = new PrimeNumber();
              obj.checkPrime(23);
              }
              }

              Output-
              Prime number -23

              Program- 6  Palindrome Check

              package com.sanjay.java.basic;

              public class PalindromeChek {
              // static String mString = "madam";

              private boolean isPalindrome(String str) {

              int i = str.length() - 1;
              int j = 0;

              while (i > j) {

              if (str.charAt(i) != str.charAt(j)) {
              return false;
              }
              i--;
              j++;

              }
              return true;

              }

              private void integerValueCheck(int n) {
              int r, temp, sum = 0;

              // int n = 454;

              temp = n;

              while (n > 0) {

              r = n % 10;
              sum = (sum * 10) + r;
              n = n / 10;

              }
              if (sum == temp) {
              System.out.println("Number is palindrome");
              } else {
              System.out.println("Number not palindrome");
              }
              }

              /**
              * @param args
              */
              public static void main(String[] args) {
              // TODO Auto-generated method stub
              // ********************* STRING CHECK********************************
              PalindromeChek obj = new PalindromeChek();
              boolean b = obj.isPalindrome("aman");

              //System.out.println("string check " + b);
              if (b) {
              System.out.println("String is palindrome");
              } else {
              System.out.println("String not palindrome");
              }
              // **********************INTEGER CHECK*******************************

              obj.integerValueCheck(425124);

              }

              }

              Output-
              String is palindrome
              Number is palindrome

              Program -7  (Armstrong number check)

              package com.sanjay.java;

              public class ArmStrongNumber {

              void getArmStrong(int num) {
              int n, sum = 0;
              int rem, cube;
              n = num;
              while (n > 0) {
              rem = n % 10;
              cube = rem * rem * rem;
              sum = sum + cube;
              n = n / 10;
              }
              if (sum == num) {
              System.out.println("Armstrong number =" + sum);
              }else{
              System.out.println("Number not an ArmStrong");
              }
              }

              public static void main(String[] args) {
              // TODO Auto-generated method stub
              ArmStrongNumber obj = new ArmStrongNumber();
              obj.getArmStrong(153);
                              obj.getArmStrong(155);
              }


              }
              Output-
              Armstrong number =153
              Number not an ArmStrong



              Program -8  (One interface can extends more than one interface)

              package com.sanjay.java;
              interface printable{
              void print();
              }
              interface scannable  {
              void scan();
              }
              interface functional extends scannable , printable{
              void work();
              }

              class A6 implements functional {
              public void print(){System.out.println("print");}
              public void scan(){System.out.println("scan");}
              public void work(){System.out.println("work");}
              public static void main(String args[]){
              A6 obj = new A6();
              obj.print();
              obj.scan();
              obj.work();
               }
              }

              Output-
                  print
                 scan
                 work

              Program -9  (Count number occurrence in array)


              public class NumberOccurrance {
              public static void main(String[] args) {
              // TODO Auto-generated method stub
                     int[] arr={2,3,4,2,5,6,2,1,3,2,8,9};
                     int[] solArr=new int[12];
              /**
              *  Here i am creating solArr with 12 length, it initialized all index with 0 value.
              * ___________________________________________________
              * |_0_|_1_|_2_|_3_|_4_|_5_|_6_|_7_|_8_|_9_|_10_|_11_|
              arr[i]=  2   3   4   2   5   6   2   1   3   2   8     9
                 
                 solArr[arr[i]]= 
                                solArr[arr[0]]=> solArr[2]=1
                                solArr[arr[1]]=> solArr[3]=1
                                solArr[arr[2]]=> solArr[4]=1
                                solArr[arr[3]]=> solArr[2]=1+1 = 2
                                solArr[arr[4]]=> solArr[5]=1
                                solArr[arr[5]]=> solArr[6]=1
                                solArr[arr[6]]=> solArr[2]=2+1 = 3
                                solArr[arr[7]]=> solArr[1]=1
                                solArr[arr[8]]=> solArr[3]=1+1 = 2
                                solArr[arr[9]]=> solArr[2]=3+1 = 4
                                .
              
                                .
                                So if same number is already in solArr index then increment by 1 in below code.
              */
                     for(int i=0;i<arr.length;i++){
                     solArr[arr[i]]+=1;
                     }
              System.out.println("Array elements and it's count");

                         for (int j = 0; j < solArr.length; j++) {
                             System.out.println("element "+j +" count "+solArr[j]);
                   }
                     if(solArr[2]>=solArr[3]){
              System.out.println(2);
              }else{
              System.out.println(1);
              }
              }
              }
              Output-


              index 0  count 0
              index 1  count 1
              index 2  count 4
              index 3  count 2
              index 4  count 1
              index 5  count 1
              index 6  count 1
              index 7  count 0
              index 8  count 1
              index 9  count 1
              index 10  count 0
              index 11  count 0
              2