Thursday, 27 September 2018

Android Adding Banner Ads into Apps Admob




1) Add Internet Permission

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

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

2) Add Dependency In Your Gradle File

   implementation 'com.google.android.gms:play-services-ads:15.0.1' 

3) Create Your App Id On Admob Site
   
  Create your app id on admob site
  
   * Don't Use Your Unit Id For Tesing, Other Wise Your Admob Account Will Suspend By Admob Policy

      Use Dummy Id Which Provided By Admob For Testing
      From: 

4) Layout File File

 <?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=".MainActivity">


    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"/>

</RelativeLayout>

5) Java File

 import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {

    private AdView mAdView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Add Your App ID From Admob
        MobileAds.initialize(this,
                "ca-app-pub-1824429213524177~7047017369");

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    }


}



Monday, 24 September 2018

Android Tutorial - Retrofit POST Request




1) Add this dependency on your grdule.build(Module File)

      implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

2) Add Internet Permission On Manifest.xml File

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


3) Api.interface for creating a method

   in retrofit url is define in two parts 
    
    i)  base url (on my code  base url is "https://reqres.in/api/") 
    
   ii) route (on my code "users" is a route)

   complete url is "https://reqres.in/api/users"

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {


    @FormUrlEncoded
    @POST("users")
    Call<ResponseBody>  post_data(
            @Field("name") String name,
            @Field("job") String job
    );
}



4) RetrofitClient.class 


   import retrofit2.Retrofit;
   import retrofit2.converter.gson.GsonConverterFactory;

  public class RetrofitClient {
      private String BASE_URL = "https://reqres.in/api/";
      private static RetrofitClient mInstance;
      private Retrofit retrofit;

      private RetrofitClient(){
          retrofit = new Retrofit.Builder()
                  .baseUrl(BASE_URL)
                  .addConverterFactory(GsonConverterFactory.create())
                  .build();
      }

      public static synchronized RetrofitClient getmInstance(){
          if(mInstance == null) {
              mInstance = new RetrofitClient();
          }
          return mInstance;
      }

      public Api getApi(){
          return retrofit.create(Api.class);
      }
  }    

5) Activity XML Layout File

 <?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=".Post">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:padding="20dp">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_name"
            android:hint="Name"
            android:textStyle="bold"
            android:textColor="#000000"
            android:textSize="25dp"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_job"
            android:hint="Job"
            android:textStyle="bold"
            android:textColor="#000000"
            android:textSize="25dp"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btn_post"
            android:text="Post"/>
    </LinearLayout>

</RelativeLayout>


6) Activity Java File

package com.example.admin.retrofitget;

import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Post extends AppCompatActivity {

    EditText et_name, et_job;
    Button btn_post;

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

        et_name = (EditText)findViewById(R.id.et_name);
        et_job = (EditText)findViewById(R.id.et_job);

        btn_post = (Button)findViewById(R.id.btn_post);

        final Call<ResponseBody> call = RetrofitClient
                .getmInstance()
                .getApi()
                .post_data(et_name.getText().toString(),
                        et_job.getText().toString());


        btn_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String res = response.body().toString();
                            showMessage("Success", response.body().string());
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        showMessage("Error", t.getMessage());
                    }
                });
            }
        });

    }

    public void showMessage(String title,String Message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    }

}

Friday, 21 September 2018

Android Retrofit Get Example – Fetching JSON from URL

1) Add this dependency on your grdule.build(Module File)

      implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

2) Add Internet Permission On Manifest.xml File

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

3) Data.class for getting and reading data ()
    

public class Data {
    private String id;
    private String name;
    private String username;
    private String email;


    public Data(String id, String name, String username, String email) {
        this.id = id;
        this.name = name;
        this.username = username;
        this.email = email;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getUsername() {
        return username;
    }

    public String getEmail() {
        return email;
    }
}


This class property is base upon your JSON data format
my JSON Data  format is 

{
     "id":"1",
     "name" :"Abcd",
      "username":"xyz",
     "email":"abc@xyz.com"
}


4) Api.interface for creating a method

   in retrofit url is define in two parts 
    
    i)  base url (on my code  base url is "https://jsonplaceholder.typicode.com/") 
    
   ii) route (on my code "users" is a route)

   complete url is "https://jsonplaceholder.typicode.com/users"

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {

    String BASE_URL = "https://jsonplaceholder.typicode.com/";

    @GET("users")
    Call<List<Data>> getData();
}


5) Get.XML activity layout file

 <?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=".Get">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list_item">

    </ListView>

</RelativeLayout> 

5) Get.java activity java file
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Get extends AppCompatActivity {

    ListView list_item;

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

        list_item = (ListView)findViewById(R.id.list_item);

        Retrofit get_retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = get_retrofit.create(Api.class);

        Call<List<Data>> call = api.getData();

        call.enqueue(new Callback<List<Data>>() {
            @Override
            public void onResponse(Call<List<Data>> call, Response<List<Data>> response) {

                //Toast.makeText(getApplicationContext(), String.valueOf(response.body()), Toast.LENGTH_LONG).show();
                List<Data> data = response.body();

                String[] data_arr = new String[data.size()];


                for (int i =0; i< data.size(); i++){
                    data_arr[i] = data.get(i).getId() + "\n"
                            + data.get(i).getName() + "\n" +
                            data.get(i).getUsername() + "\n" +
                            data.get(i).getEmail();
                }

                list_item.setAdapter(
                        new ArrayAdapter<String>(
                                getApplicationContext(),
                                android.R.layout.simple_list_item_1,
                                data_arr
                        )
                );

            }

            @Override
            public void onFailure(Call<List<Data>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "Error : \n" +t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

}

Android GPS Tracking



1) Add Permission On Manifest File
    
    Add permission on manifest.xml file to access all network and GPS

    /* this will added in your project file by default if you choose Maps Activity whrn project was                created */
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    // add this permission to access all networks like mobile and GPS
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


2) XML Layout 
 It Will Create By Default when you choose  maps activity
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MapsActivity" />


2) Java File
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

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

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    private LocationListener locationListener;
    private LocationManager locationManager;

    private final long MIN_Time = 1000; // 1 second
    private final long MIN_Dist = 5; // 5 Meter

    private LatLng latLng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

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


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

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Mijas in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.addMarker(new MarkerOptions().position(latLng).title("My Position"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            }

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

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        try {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_Time,                MIN_Dist, locationListener);
        } catch (SecurityException ex){
            ex.printStackTrace();
        }


    }

}

Android Studio - Get Current Latitude And Longitude

1. Add this dependencies in your gradle file     implementation 'com.google.android.gms:play-services-location:18.0.0' 2. Add this p...