I was wondering if anyone can help me with this. I am trying to add auto-completion to my app with the Google Places API. I am following a tutorial and the following code is what I am having a problem with:
URL googlePlaces = new URL(
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" +
URLEncoder.encode(args[0], "UTF-8") +
"&types=geocode&language=en&sensor=true&key=" +
getResources().getString(R.string.googleAPIKey));
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
The line "getResources()" is coming back with a "cannot resolve to a type" error because of the "R.string.googleAPIKey". I will put in my whole code down below:
package com.multinav;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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 MainActivity extends FragmentActivity {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (googleMap == null){
// Try to obtain the map from the SupportMapFragment.
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (googleMap != null){
setUpMap();
}
}
}
private void setUpMap() {
// Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// Set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("BAAMMMM!"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Main extends Activity {
/** Called when the activity is first created. */
public ArrayAdapter<String> adapter;
public AutoCompleteTextView textview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.item_list);
final AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count%3 == 1) {
adapter.clear();
GetPlaces task = new GetPlaces();
//now pass the argument in the textview to the task
task.execute(textView.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args)
{
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try
{
URL googlePlaces = new URL(
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" +
URLEncoder.encode(args[0], "UTF-8") +
"&types=geocode&language=en&sensor=true&key= +
getResources().getString(R.string.googleAPIKey));
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
//take Google's legible JSON and turn it into one big string.
while ((line = in.readLine()) != null) {
sb.append(line);
}
//turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
//now get the JSON array that's inside that object
JSONArray ja = new JSONArray(predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
//add each entry to our array
predictionsArr.add(jo.getString("description"));
}
}
catch (IOException e)
{
Log.e("MultiNAV", "GetPlaces : doInBackground", e);
}
catch (JSONException e)
{
Log.e("MultiNAV", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
//then our post
#Override
protected void onPostExecute(ArrayList<String> result){
Log.d("MultiNAV", "onPostExecute : " + result.size());
//update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.item_list);
adapter.setNotifyOnChange(true);
//attach the adapter to textview
textview.setAdapter(adapter);
for (String string : result){
Log.d("MultiNAV", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("MultiNAV", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
}
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
When Im trying to run the app it crashes and I get this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivityMaps}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
Here is the code for the app:
package com.example.myapplication;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivityMaps extends FragmentActivity implements
OnMapReadyCallback {
GoogleMap map;
ArrayList<LatLng> markerPoints;
TextView tvDistanceDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
// Initializing
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
MapFragment fm = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
fm.getMapAsync(this);
// Getting Map for the SupportMapFragment
}
public void onMapReady(GoogleMap googleMap) {
// Enable MyLocation Button in the Map
// 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.
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
map.setMyLocationEnabled(true);
// Setting onclick event listener for the map
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Already two locations
if (markerPoints.size() > 1) {
markerPoints.clear();
map.clear();
}
// Adding new item to the ArrayList
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if (markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker
(BitmapDescriptorFactory.HUE_GREEN));
} else if (markerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_R
ED));
}
// Add new marker to the Google Map Android API V2
map.addMarker(options);
// Checks, whether start and end locations are captured
if (markerPoints.size() >= 2) {
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output
+ "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new
InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exceptiondownloadingurl", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>
{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer,
List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String...
jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result)
{
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if (result.size() < 1) {
Toast.makeText(getBaseContext(), "No Points",
Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) { // Get distance from the list
distance = (String) point.get("distance");
continue;
} else if (j == 1) { // Get duration from the list
duration = (String) point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
tvDistanceDuration.setText("Distance:" + distance + ", Duration:" +
duration);
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}}
Thanks In advance!
MapFragment fm = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
fm.getMapAsync(this);// fm is null
you have no fragment with map id in activity_main layout correct your activity_main layout and add MapFragment to a FrameLayout in activity_main the id of FrameLayout must be map
I just got the permissions handled through the library Let, but I still can't get a longitude and latitude in my android app. I'm using a service called GPS_Service.java. Also I'm not 100% sure my permissions aren't the issue. The call to the google API in GPS_Service still is underlined with the warning that it requires permissions which might be rejected. Is that supposed to go away even with third party libraries? Would this still be an issue because on my device the app has location permissions enabled?
here is my main activity:
package com.example.paxie.stormy.ui;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.canelmas.let.AskPermission;
import com.canelmas.let.DeniedPermission;
import com.canelmas.let.Let;
import com.canelmas.let.RuntimePermissionListener;
import com.canelmas.let.RuntimePermissionRequest;
import com.example.paxie.stormy.GPS_Service;
import com.example.paxie.stormy.R;
import com.example.paxie.stormy.weather.Current;
import com.example.paxie.stormy.weather.Day;
import com.example.paxie.stormy.weather.Forecast;
import com.example.paxie.stormy.weather.Hour;
import com.google.android.gms.maps.model.LatLng;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements RuntimePermissionListener {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
private Forecast mForecast;
private double mLatitude;
private double mLongitude;
private BroadcastReceiver broadcastReceiver;
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private Context mContext;
#BindView(R.id.timeLabel)
TextView mTimeLabel;
#BindView(R.id.temperatureLabel)
TextView mTemperatureLabel;
#BindView(R.id.humidityValue)
TextView mHumidityValue;
#BindView(R.id.precipValue)
TextView mPrecipValue;
#BindView(R.id.summaryLabel)
TextView mSummaryLabel;
#BindView(R.id.iconImageView)
ImageView mIconImageView;
#BindView(R.id.refreshImageView)
ImageView mRefreshImageView;
#BindView(R.id.progressBar)
ProgressBar mProgressBar;
#BindView(R.id.locationLabel)
TextView mLocationlabel;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Let.handle(this, requestCode, permissions, grantResults);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast();
}
});
getForecast();
Log.d(TAG, "Main UI code is running!");
}
private void getForecast() {
checkGPS();
String apiKey = "1621390f8c36997cb1904914b726df52";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + mLatitude + "," + mLongitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e)
{
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(this, "Network is currently unavailable!", Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mLocationlabel.setText(mLatitude + " " + mLongitude);
Current current = mForecast.getCurrent();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("At " + current.getFormattedTime() + " it will be:");
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ContextCompat.getDrawable(this, current.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrent(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonDay = data.getJSONObject(i);
Day day = new Day();
day.setSummary(jsonDay.getString("summary"));
day.setIcon(jsonDay.getString("icon"));
day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
day.setTime(jsonDay.getLong("time"));
day.setTimeZone(timezone);
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getDouble("temperature"));
hour.setIcon(jsonHour.getString("icon"));
hour.setTime(jsonHour.getLong("time"));
hour.setTimeZone(timezone);
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current();
current.setHumidity(currently.getDouble("humidity"));
current.setTime(currently.getLong("time"));
current.setIcon(currently.getString("icon"));
current.setPrecipChance(currently.getDouble("precipProbability"));
current.setSummary(currently.getString("summary"));
current.setTemperature(currently.getDouble("temperature"));
current.setTimeZone(timezone);
Log.d(TAG, current.getFormattedTime());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
#OnClick(R.id.hourlyButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
startActivity(intent);
}
#AskPermission({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
private void checkGPS() {
GPS_Service gps_service = new GPS_Service(this);
gps_service.getLocation();
mLatitude = gps_service.getLatitude();
mLongitude = gps_service.getLongitude();
}
#Override
public void onShowPermissionRationale(List<String> permissionList, RuntimePermissionRequest permissionRequest) {
}
#Override
public void onPermissionDenied(List<DeniedPermission> deniedPermissionList) {
}
}
And here is my GPS_Service.java:
package com.example.paxie.stormy;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.canelmas.let.AskPermission;
import com.canelmas.let.DeniedPermission;
import com.canelmas.let.Let;
import com.canelmas.let.RuntimePermissionListener;
import com.canelmas.let.RuntimePermissionRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import java.util.ArrayList;
import java.util.List;
/**
* Created by paxie on 10/27/16.
*/
public class GPS_Service extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
private static final int RC_GPS_PERMS = 124;
public String[] perm = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
public GPS_Service(Context c) {
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void getLocation() {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In that case enable your GPS and go to google maps and hit the location button, wait until google maps locate u and then go back and test in ur app. This should work because if u are using the first time ur phone without never been conected to GPS it gives u that problem
It is looking for specifically "LastKnownLocation", I had this issue as well. Move about 3 meters and try again. If there is no 'last known location' then it sends a null value.
What I did was set a few if statements for my application. If the GPS Provider was spitting out null values, then use the Network Provider location coordinates, and if that was spitting out null values then I just displayed a message saying "To Wait" or "Try again later". Eventually your GPS Provider will pick up location values after it has been activated for a while.
newLoc = _locationManager.GetLastKnownLocation(_locationProvider);
if (newLoc != null)
{
_latitudeUser = newLoc.Latitude;
_longitudeUser = newLoc.Longitude;
_locationText.Text = string.Format("{0:f6},{1:f6}", newLoc.Latitude, newLoc.Longitude);
}
else
{
_locationProvider = LocationManager.NetworkProvider;
newLoc = _locationManager.GetLastKnownLocation(_locationProvider);
if (newLoc != null)
{
_latitudeUser = newLoc.Latitude;
_longitudeUser = newLoc.Longitude;
_locationText.Text = string.Format("{0:f6},{1:f6}", newLoc.Latitude, newLoc.Longitude);
}
else
{
_locationText.Text = string.Format("We currently cannot determine your location, please try again later.");
}
I have made a class that have a method and a locaton listener. The locationListener will be executed every 2 seconds , gets the lat longs and will pass it to the Async Task. The Async Task class will pass the lat longs to Google Road Api to get snapped lat longs and will pass the lat longs to postExecute()
The PostExecute() should draw the polylines But it does not..
Please See the below code.:
MapsActivity.java
package com.example.akshay.roadsapi;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
final String URL = "https://roads.googleapis.com/v1/snapToRoads?path=";
final String KEY = "API KEY HERE";
int i = 0;
AsyncTask<Void, Void, LatLng> latLng1 = null;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
BackgroundTask backgroundTask = new BackgroundTask(MapsActivity.this, latLng, URL, KEY, activity, mMap);
backgroundTask.execute();
/*mMap.addMarker(new MarkerOptions().position(latLng1));*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
BackgroundTask.java
package com.example.akshay.roadsapi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Created by Akshay on 9/8/2015.
*/
public class BackgroundTask extends AsyncTask<Void, Void, LatLng> {
Context CONTEXT;
LatLng LATLNGS;
String URL;
String KEY;
Double LAT = null;
Double LONG = null;
GoogleMap map;
Activity ACTIVITY;
myInt myInt = null;
int flag = 0;
LatLng prev;
LatLng latlng;
public BackgroundTask(Context context, LatLng LATLNGS, String URL, String KEY, Activity ACTIVITY, GoogleMap map) {
this.CONTEXT = context;
this.LATLNGS = LATLNGS;
this.URL = URL;
this.KEY = KEY;
this.ACTIVITY = ACTIVITY;
this.map = map;
}
#Override
protected LatLng doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet();
HttpResponse response = null;
HttpEntity entity = null;
InputStream inputStreamReader = null;
BufferedReader bufferedReader = null;
String line = null;
StringBuilder strin = new StringBuilder();
try {
get.setURI(new URI(URL + LATLNGS.latitude + "," + LATLNGS.longitude + "&interpolate=false&key=" + KEY));
response = client.execute(get);
entity = response.getEntity();
inputStreamReader = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStreamReader));
while ((line = bufferedReader.readLine()) != null) {
strin.append(line + "\n");
}
Log.e("============", strin.toString());
JSONObject ob = new JSONObject(strin.toString());
JSONArray array = ob.getJSONArray("snappedPoints");
for (int i = 0; i <= array.length(); i++) {
JSONObject object = array.getJSONObject(i).getJSONObject("location");
LAT = object.getDouble("latitude");
LONG = object.getDouble("longitude");
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
latlng= new LatLng(LAT, LONG);
return latlng;
}
#Override
protected void onPostExecute(LatLng latLng) {
super.onPostExecute(latLng);
/* MarkerOptions markerOptions = new MarkerOptions().position(latLng);
map.addMarker(markerOptions);*/
if (flag == 0) {
prev = latLng;
flag = 1;
}
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18);
/* Marker marker = map.addMarker(new MarkerOptions().position(latLng));*/
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.add(prev, latLng).color(Color.BLUE).width(50).visible(true);
map.addPolyline(polylineOptions);
map.animateCamera(cameraUpdate);
prev = latLng;
latLng = null;
}
}
I am getting the Json Array From GOOGLE API and getting the lats long values successfully but polyline is not Drawn..
Please Help
Thanks
google map is loading on emulator givin error that application is stopped unfortunately following is my code package com.ayesha.MIT;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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 Spot_Location_Screen extends FragmentActivity implements
LocationListener {
Database_Table_Operations database;
ArrayList<String> locations = new ArrayList<String>();
ArrayList<String> latitude = new ArrayList<String>();
ArrayList<String> longitude = new ArrayList<String>();
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
Intent intent;
String[] mPlaceType = null;
String[] mPlaceTypeName = null;
double mLatitude = 0;
double mLongitude = 0;
Button btnFind;
Button doneButton;
boolean isFound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.spot_location_screen);
mPlaceType = getResources().getStringArray(R.array.place_type);
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
mSprPlaceType.setAdapter(adapter);
btnFind = (Button) findViewById(R.id.btn_find);
doneButton = (Button) findViewById(R.id.doneButton);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mGoogleMap = fragment.getMap();
mGoogleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
database = new Database_Table_Operations(getApplicationContext());
if (getIntent().getStringExtra("Update") != null) {
if (getIntent().getStringExtra("Update").equals("true")) {
addMarker(getIntent().getStringExtra("Date"));
}
}
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
if (location != null) {
onLocationChanged(location);
}
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (checkInternetConnection(getApplicationContext())) { // browser
// key
mGoogleMap.clear();
locations.clear();
latitude.clear();
longitude.clear();
int selectedPosition = mSprPlaceType
.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + 33.6000 + "," + 73.0333);
sb.append("&radius=20000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyAVhTyd9GXAkJ9VJ1S7OD9ldrBsQgOH69c");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
}
}
});
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (checkInternetConnection(getApplicationContext())) {
if (getIntent().getStringExtra("Update").equals("true")) {
database.open();
String myDate = getIntent().getStringExtra("Date");
locations.add(database.getLocation(myDate));
latitude.add(database.getLatitude(myDate));
longitude.add(database.getLongitude(myDate));
intent = new Intent(Spot_Location_Screen.this,
Locations_List_View_Screen.class);
intent.putStringArrayListExtra("Locations",
locations);
intent.putStringArrayListExtra("Latitude", latitude);
intent.putStringArrayListExtra("Longitude",
longitude);
intent.putExtra("Date",
getIntent().getStringExtra("Date"));
intent.putExtra("Update", getIntent()
.getStringExtra("Update"));
database.close();
startActivity(intent);
finish();
} else {
if (locations.size() != 0) {
intent = new Intent(Spot_Location_Screen.this,
Locations_List_View_Screen.class);
intent.putStringArrayListExtra("Locations",
locations);
intent.putStringArrayListExtra("Latitude",
latitude);
intent.putStringArrayListExtra("Longitude",
longitude);
intent.putExtra("Date", getIntent()
.getStringExtra("Date"));
intent.putExtra("Update", getIntent()
.getStringExtra("Update"));
startActivity(intent);
finish();
}
}
}
}
});
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends
AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(
String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
latitude.add(String.valueOf(lat));
double lng = Double.parseDouble(hmPlace.get("lng"));
longitude.add(String.valueOf(lng));
String name = hmPlace.get("place_name");
String vicinity = hmPlace.get("vicinity");
locations.add(name + ", " + vicinity);
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
mGoogleMap.addMarker(markerOptions);
}
if (locations.size() > 1) {
int median = locations.size();
median = median / 2;
LatLng myLatLng = new LatLng(Double.parseDouble(latitude
.get(median)),
Double.parseDouble(longitude.get(median)));
mGoogleMap.animateCamera(CameraUpdateFactory
.newLatLng(myLatLng));
} else if (locations.size() == 1) {
LatLng myLatLng = new LatLng(
Double.parseDouble(latitude.get(0)),
Double.parseDouble(longitude.get(0)));
mGoogleMap.animateCamera(CameraUpdateFactory
.newLatLng(myLatLng));
}
}
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
intent = new Intent(Spot_Location_Screen.this,
SetMeetup_Screen.class);
startActivity(intent);
finish();
}
return super.onKeyDown(keyCode, event);
}
public void addMarker(String date) {
database.open();
MarkerOptions markerOptions = new MarkerOptions();
final LatLng latLng = new LatLng(Double.parseDouble(database
.getLatitude(date)), Double.parseDouble(database
.getLongitude(date)));
markerOptions.position(latLng);
markerOptions.title("Your saved location:\n"
+ database.getLocation(date));
mGoogleMap.addMarker(markerOptions);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
database.close();
}
}, 2500);
}
public boolean checkInternetConnection(Context context) {
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
isFound = true;
} else {
isFound = false;
}
return isFound;
}
}
Google Android Map API is not able to run Google Maps on the Android emulator. You must use an Real Android device for testing your app.
Refer this link to run Google Map on emulator.
hey ma problem is solved but the emulator is not working with Google maps I think its about the device problem but before it was also not working with the blue stacks for that I've changed the package name
right click the package from
src folder->refactor->rename
and
change the package name then change the package name in the manifest then click the on the project
ctrl+shiftz+o
it will change the package name throughout your project..
then again create the browser key and android key with new package name and it will load the map.....
and don forget to turn on the API's in Google console... and also check the minimum SDK version if its 9 then go to SSDK manager and install API 9 by clicking the obsolete option there...
I am trying to push data to a server after taking values from the accelerometer.
In that I am using JsonObject from google.
There seems to be some problem with this object. As soon as I put instantiate one object from this my application throws an error: Unfortunately appname has stopped.
My MainActivity code:
package com.example.accelerometerdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
public class MainActivity extends Activity implements SensorEventListener {
private static final String MSG_TAG_1 = "MainActivity";
private static final String MSG_TAG_2 = "place_holder";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2, test;
RelativeLayout layout;
int i = 0;
//For preparing file
String[] paramName = { "device_id", "timestamp", "sensor_type",
"sensor_value" };
String URLStr = "http://209.129.244.7/sensors";
java.util.Date date = new java.util.Date();
#Override
public final void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //refer layout file code below
//get the sensor service
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//get the accelerometer sensor
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//If sensor not available
if (mAccelerometer == null){
System.out.println("no temperature sensor");
}
//get layout
layout = (RelativeLayout)findViewById(R.id.relative);
//get textviews
title=(TextView)findViewById(R.id.name);
tv=(TextView)findViewById(R.id.xval);
tv1=(TextView)findViewById(R.id.yval);
tv2=(TextView)findViewById(R.id.zval);
test = (TextView)findViewById(R.id.testval);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy)
{
// Do something here if sensor accuracy changes.
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
i++;
if (i < 5) {
getAccelerometer(event);
} else {
onPause();
}
}
}
public final void getAccelerometer(SensorEvent event)
{
// Many sensors return 3 values, one for each axis.
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
String t = "This is a test value";
//display values using TextView
title.setText(R.string.app_name);
tv.setText("X axis" +"\t\t"+x);
tv1.setText("Y axis" + "\t\t" +y);
tv2.setText("Z axis" +"\t\t" +z);
test.setText("Testing" +"\t\t" +event.values[2]);
JsonObject jo = new JsonObject();
try {
//formatting the file
jsonObject_x.put("sensor_value", 78);
jo.addProperty("device_id", "nexus_test_dev"); //Long type
jo.addProperty("timestamp", date.getTime()); //Long type
jo.addProperty("sensor_type", "Accelerometer_x"); //String type
jo.addProperty("sensor_value", 78); //Double type
//String[] paramName = { "device_id", "timestamp", "sensor_type", "sensor_value" };
//{"device_id":"test", "timestamp": 1373566899100, "temp": 123}
String[] paramVal = { "aeron_test_p", String.valueOf(date.getTime()),
"temp", "121" };
//Displaying readings in LOGCAT
for(String s : paramVal){
Log.d(MSG_TAG_1, s);
}
try {
httpPostSensorReading(URLStr, jo.toString());
Log.d(MSG_TAG_2, "Test");
} catch (Exception e) {e.printStackTrace();
}
} catch (JsonIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String httpPostSensorReading(String urlStr, String jsonString) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
// Create the form content
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(jsonString);
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
#Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause()
{
super.onPause();
mSensorManager.unregisterListener(this);
}
}
The moment I add this
JsonObject jo = new JsonObject();
The application throws an error "Unfortunately appname hsa stopped.
SOme issue with JsonObject. I used JSONObject then it was working fine.
Thanks,
I am sure you need to use not constructor for JsonObject, but JsonObjectBuilder to create JsonObject:
JsonObject jo = Json.createObjectBuilder()
.add("device_id", "nexus_test_dev")
.build();
Here is link on javadoc:
http://docs.oracle.com/javaee/7/api/javax/json/JsonObjectBuilder.html
Could not find class 'com.google.gson.JsonObject', referenced from method com.example.accelerometerdemo.MainActivity.getAccelerometer
You need to copy the gson.jar to your projects libs folder. Clean and build and t should work.
Note: Android's current build tools (Eclipse and command-line) expect that JARs are in a libs/ directory. It will automatically add those JARs to your compile-time build path