ANDROID:GETTING GPS LATITUDE AND LONGITUDE VALUES THROUGH THINGSPEAK AND UPDATING THE LOCATION IN MAP

Here we will have two activities as MainActivity and GPS activity.

Main activity includes two textviews and two buttons.On clicking Button1,it gets the latitude and longitude values through Thingspeak and displays in two Textviews.On clicking button2,it sends the values of latitude and longitude to GPS activity through Intent.

GPS activity displays the google map with the obtained values from MainActivity.

MainActivity.java:

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
/**
 * Created by SHAHEER on 3/12/2018.
 */
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "UsingThingspeakAPI";
    private static final String THINGSPEAK_CHANNEL_ID = "444xxx";//replace your channel id
    private static final String THINGSPEAK_API_KEY = "EE90JXIIxxxxxx"; //replace your read key
    private static final String THINGSPEAK_API_KEY_STRING = "EE90JXIIxxxx";//replace your read key
    /* Be sure to use the correct fields for your own app*/
    private static final String THINGSPEAK_FIELD1 = "field1";
    private static final String THINGSPEAK_FIELD2 = "field2";
    private static final String THINGSPEAK_UPDATE_URL = "https://api.thingspeak.com/update?";
    private static final String THINGSPEAK_CHANNEL_URL = "https://api.thingspeak.com/channels/";
    private static final String THINGSPEAK_FEEDS_LAST = "/feeds/last?";
    TextView t1,t2;
    Double v1;
    Double v2;
    Button b1;
    Button b2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1=(TextView)findViewById(R.id.textView2);
        t2=(TextView)findViewById(R.id.textView3);
        b1=(Button)findViewById(R.id.button3) ;
        b2=(Button) findViewById(R.id.button2);
        t2.setText("");
        b1.setOnClickListener(new View.OnClickListener()
                              {
                                  @Override
                                  public void onClick(View v) {

                                      try {
                                          new FetchThingspeakTask().execute();
                                      } catch (Exception e) {
                                          Log.e("ERROR", e.getMessage(), e);
                                      }
                                  }
                              });
        b2.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick (View v){
                Intent myIntent = new Intent(MainActivity.this, MapsActivity.class);
                myIntent.putExtra("value1",v1 );
                myIntent.putExtra("value2",v2 );
                startActivity(myIntent);
            }
        });
    }
    class FetchThingspeakTask extends AsyncTask<Void, Void, String> {
        protected void onPreExecute() {
            t2.setText("Fetching Data from Server.Please Wait...");
        }
        protected String doInBackground(Void... urls) {
            try {
                URL url = new URL(THINGSPEAK_CHANNEL_URL + THINGSPEAK_CHANNEL_ID +
                        THINGSPEAK_FEEDS_LAST + THINGSPEAK_API_KEY_STRING + "=" +
                        THINGSPEAK_API_KEY + "");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                try {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line).append("\n");
                    }
                    bufferedReader.close();
                    return stringBuilder.toString();
                }
                finally{
                    urlConnection.disconnect();
                }
            }
            catch(Exception e) {
                Log.e("ERROR", e.getMessage(), e);
                return null;
            }
        }
        protected void onPostExecute(String response) {
            if(response == null) {
                Toast.makeText(MainActivity.this, "There was an error", Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject channel = (JSONObject) new JSONTokener(response).nextValue();
                v1 = channel.getDouble(THINGSPEAK_FIELD1);
                v2=channel.getDouble(THINGSPEAK_FIELD2);
                    t1.setText(v1.toString());
                    t2.setText(v2.toString());
                 } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

 

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"
    tools:context="com.example.shaheer.gps.MainActivity">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout">
        <Button
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="Get Location"
            android:id="@+id/button2"
            android:layout_alignTop="@+id/textView3"
            android:layout_alignParentStart="true" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Get Attributes"
            android:id="@+id/button3"
            android:layout_gravity="right"
            android:layout_below="@+id/linearLayout"
            android:layout_alignParentStart="true"
            android:layout_marginStart="62dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView3"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="58dp" />
        </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true">
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView2"
        android:layout_marginTop="95dp"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/textView3" />
    </LinearLayout>
</RelativeLayout>

 

GpsActivity.java:

import android.content.Intent;
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;
    Double lat;
    Double lon;
    @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);
        Intent mIntent = getIntent();
        lat = mIntent.getDoubleExtra("value1", 0);
        lon = mIntent.getDoubleExtra("value2", 1);
    } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(lat,lon);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Nagercoil"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

activity_maps.xml:

<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="com.example.shaheer.gps.MapsActivity"/>
 

AndroidManifest.xml:

Add under <manifest> tag,

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

Leave a Reply

Your email address will not be published. Required fields are marked *