i'm currently working on android maps by following this tutorial http://developer.android.com/training/location/retrieve-current.html, and i keep getting error.there are 4 warnings and i tried to fix it but when i run it again the error message fatal exception still showing
here's the warning messages:
1. the message servicesConnected() from the type LokasiKampus is never used locally
2. the value of local variable kampus is not used
3. the value of local variable laboratorium is not used
4.the value of local variable myCurrentLocation is not used
here's my Java code
package ninth.example.dteinformationcenter;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class LokasiKampus extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
static final LatLng Kampus = new LatLng (-7.775038, 110.373253);
static final LatLng Laboratorium = new LatLng (-7.765437, 110.374496);
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap map;
private GooglePlayServicesClient myLocationClient;
public static class ErrorDialogFragment extends DialogFragment {
private Dialog mDialog;
public ErrorDialogFragment() {
super();
mDialog = null;
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
public void show(FragmentManager supportFragmentManager, String tag) {
// TODO Auto-generated method stub
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
switch(resultCode) {
case Activity.RESULT_OK : break;
}
}
}
**private boolean servicesConnected()** {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d("Location Updated", "Google Play Services is available");
return true;
} else {
Dialog ErrorDialog = GooglePlayServicesUtil
.getErrorDialog(resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (ErrorDialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(ErrorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lokasi_kampus);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.lokasikampus)).getMap();
if (map != null) {
**Marker kampus = map.addMarker(new MarkerOptions().position(Kampus)
.title("Kampus "));
Marker laboratorium = map.addMarker(new MarkerOptions().position(Laboratorium)
.position(Laboratorium)
.title("Laboratorium")
);**
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Kampus, 18));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
LocationClient myLocationClient = new LocationClient(this,this,this);
**Location myCurrentLocation;
myCurrentLocation = myLocationClient.getLastLocation();**
}
#Override
public void onConnected(Bundle dataBundle) {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
Toast.makeText(this, "Disconnected, please re-connect", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch(IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStart() {
super.onStart();
myLocationClient.connect();
}
#Override
protected void onStop() {
myLocationClient.disconnect();
super.onStop();
}
}
this is the error message
FATAL EXCEPTION: main
Process: ninth.example.dteinformationcenter, PID: 1443
java.lang.RuntimeException: Unable to start activity ComponentInfo{ninth.example.dteinformationcenter/ninth.example.dteinformationcenter.LokasiKampus}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
at com.google.android.gms.internal.hb.cn(Unknown Source)
at com.google.android.gms.internal.jg.b(Unknown Source)
at com.google.android.gms.internal.jg$c.cn(Unknown Source)
at com.google.android.gms.internal.jf.getLastLocation(Unknown Source)
at com.google.android.gms.internal.jg.getLastLocation(Unknown Source)
at com.google.android.gms.location.LocationClient.getLastLocation(Unknown Source)
at ninth.example.dteinformationcenter.LokasiKampus.onCreate(LokasiKampus.java:112)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
Related
I am using a separate class to get user's location. How to get user's location by calling interface in my activity.I cant understand How can i get user's location' latitude and longitude in my activity? It is giving me null pointer exception when i create object of class and call method
My Activity
public class missingPerson extends AppCompatActivity implements OnLocationUpdateListener {
OnLocationUpdateListener lu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_missing_person);
final LocationHandler locationHandler = new LocationHandler(missingPerson.this,lu);
locationHandler.getDeviceLocation();
}
#Override
public void onLocationChanged(Location location) {
Location location1 = location;
String latitute = String.valueOf(location1.getLatitude());
Log.i("No Result", latitute);
}
#Override
public void onError(String error) {
}
}
Class for location
package com.example.fizatanveerkhan.citycops;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.List;
public class LocationHandler {
private Activity activity;
private FusedLocationProviderClient mFusedLocationProviderClient;
private Location mLastKnownLocation;
private LocationCallback mLocationCallback;
private LocationRequest mLocationRequest;
private OnLocationUpdateListener onLocationUpdateListener;
private boolean updateStartedInternally = false;
private boolean isconnected = false;
public LocationHandler(Activity activity, final OnLocationUpdateListener onLocationUpdateListener) {
this.activity = activity;
this.onLocationUpdateListener = onLocationUpdateListener;
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity);
createLocationRequest();
getDeviceLocation();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
mLastKnownLocation = location;
if (onLocationUpdateListener != null) {
onLocationUpdateListener.onLocationChanged(location);
if(updateStartedInternally){
stopLocationUpdate();
}
}
}
}
};
}
public boolean isConnected() {
return isconnected;
}
public void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(activity, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
isconnected = true;
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = (Location) task.getResult();
if (mLastKnownLocation == null) {
updateStartedInternally = true;
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
} else if (mLastKnownLocation != null){
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
// This message appears in logcat with latitute still it say that
// onLocationUpdateListener.onLocationChanged is invoked on null object
// reference
Log.e("Location", String.valueOf(mLastKnownLocation.getLatitude()));
onLocationUpdateListener.onLocationChanged(mLastKnownLocation);
}
}
else {
onLocationUpdateListener.onError("Can't get Location");
}
}
}) ;
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
onLocationUpdateListener.onError(e.getMessage());
}
}
public void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
updateStartedInternally = false;
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
private void stopLocationUpdate() {
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
//other new Methods but not using right now..
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);//set the interval in which you want to get locations
mLocationRequest.setFastestInterval(5000);//if a location is available sooner you can get it (i.e. another app is using the location services)
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
And this is Interface
import android.location.Location;
public interface OnLocationUpdateListener {
void onLocationChanged(Location location);
void onError(String error)
}
Error
I/AssistStructure: Flattened final assist data: 4848 bytes, containing 1 windows, 15 views
E/Location: 37.4219983
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fizatanveerkhan.citycops, PID: 14006
java.lang.NullPointerException: Attempt to invoke interface method 'void
com.example.fizatanveerkhan
.citycops.OnLocationUpdateListener.onLocationChanged
(android.location.Location)' on a null object reference
at com.example.fizatanveerkhan.citycops.
LocationHandler$2.onComplete(LocationHandler.java:88)
at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os
.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 14006 SIG: 9
Application terminated.
final LocationHandler locationHandler = new LocationHandler(missingPerson.this,lu);
What is this "lu" that you pass as second argument during instance? I don't see it anywhere.
public LocationHandler(Activity activity, final OnLocationUpdateListener onLocationUpdateListener) {
//........
}
LocationHandler take OnLocationUpdateListener and set
this.onLocationUpdateListener = onLocationUpdateListener;
Then, you call
onLocationUpdateListener.onLocationChanged(mLastKnownLocation);
If you pass "lu" (that maybe is null), is pretty clear that object's onLocationUpdateListener is null.
I am building an android app and on the main layout i have 3 Image Buttons which when clicked they must each open a new activity.
When I run the app and pressed on them the app crushes. this is the code i am using:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton converterbtn = (ImageButton)findViewById(R.id.btnConvert);
ImageButton placesbtn = (ImageButton)findViewById(R.id.imagBtnPlace);
ImageButton weatherbtn = (ImageButton)findViewById(R.id.imgbtnweather);
//Open Weather Activity
if (weatherbtn.isPressed() == true) {
weatherbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), weather_mainActivity.class);
startActivity(intent);
}
}); //Open Currency Activity
}else if (converterbtn.isPressed() == true) {
converterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), CurrencyConverter_MainActivity.class);
startActivity(intent1);
}
});//Open Places Activity
} else if (placesbtn.isPressed()) {
placesbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), Places_mainActivity.class);
startActivity(intent1);
}
});
}
}
Manifest.xml
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
Any ideas why that happens? All the other posts ive checked are doing it with this way but on mine it doesnt seem to work.
Android Monitor log
01-08 03:00:58.288 22447-22447/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
01-08 03:01:01.127 1236-1547/? D/AudioFlinger: mixer(0xf4480000) throttle end: throttle time(56)
01-08 03:01:01.151 1550-21914/? D/OpenGLRenderer: endAllStagingAnimators on 0x7f0b1b83d400 (RippleDrawable) with handle 0x7f0b1b8bb540
01-08 03:01:01.192 1550-1954/? D/GraphicsStats: Buffer count: 3
Weather_MainActivity.java
package com.android.example.cwapp;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
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.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.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class weather_mainActivity extends AppCompatActivity {
public static final String TAG = weather_mainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
LocationManager locationManager;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
#InjectView(R.id.humidityValue)TextView mHumidityValue;
#InjectView(R.id.precipValue)TextView mPrecipValue;
#InjectView(R.id.summaryLabel)TextView mSummaryLabel;
#InjectView(R.id.iconImageView)ImageView mIconImageView;
#InjectView(R.id.refreshImageView)ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#InjectView(R.id.locationLabel)TextView mLocation;
public double latitude /*= 34.7720*/;
public double longitude /*= 32.4297*/;
//Location Manager
private boolean checkLocation() {
if (!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private final LocationListener locationListenerBest = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "6180f6e1b6747c1da3cb4638ea9d2961";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
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()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
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() {
float temp = mCurrentWeather.getTemperature();
String temp2 = Float.toString((temp - 32) * (5 / 9));
mTemperatureLabel.setText(temp2 + "");
mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
mLocation.setText(mCurrentWeather.getTimeZone());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather 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");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
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_weather dialog = new AlertDialogFragment_weather();
dialog.show(getFragmentManager(), "error_dialog");
}
};
RUN Log
01-09 21:29:30.827 5610-5610/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.827 5610-5610/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.864 5610-5627/? E/art: Thread attaching while runtime is shutting down: Binder_2
01-09 21:29:30.869 5614-5614/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.870 5614-5614/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.916 1548-1596/? E/InputDispatcher: channel '6ba3a14 com.android.example.cwapp/com.android.example.cwapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-09 21:29:31.830 5633-5633/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:31.830 5633-5633/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:32.033 1195-1309/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
01-09 21:29:33.170 1921-2145/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xedc344f0
01-09 21:30:01.551 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819a240
01-09 21:30:02.902 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8310
01-09 21:30:04.739 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819b580
01-09 21:30:06.655 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8380
01-09 21:30:08.253 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1bed700
01-09 21:30:09.115 5641-5641/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.example.cwapp, PID: 5641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.example.cwapp/com.android.example.cwapp.Places_mainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.android.example.cwapp.Places_mainActivity.onCreate(Places_mainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
01-09 21:30:11.307 1548-1601/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1c8f020
01-09 21:30:11.326 1548-1937/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
Add CurrentWeather.class activity in your mainfest like this
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
<activity android:name=".CurrentWeather"/>
You should display your stack trace, but you don't need View.OnClickListner, not sure if that's causing it, but just have weatherbtn.setOnClickListener(new OnClickListener() {...
Other than that, there isn't anything wrong with how you're calling your activity.
I've ha problem: I 'm implementing a secondary Activity that give to me user's position. From Page1.java, through a button, open Track.java when I would like to show the coordinates of the user's location. The problem is when I click on this button: the application is closed!
This is the code of Page1.java:
package com.example.giacomob.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Giacomo B on 05/08/2015.
*/
public class Page1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
// String dato1 = getIntent().getExtras().getString("NomeDati1");
//Intent intent = getIntent(); // Point 1
// Bundle bundle = intent.getExtras(); // Point 2
// String data1 = bundle.getString("NomeDati1"); // Point 3
String dato1 = getIntent().getExtras().getString("NomeDati1"); //preleva la stringa
Toast.makeText(this, dato1, Toast.LENGTH_SHORT).show(); //PROVA: questo mi fa comparire una specie di label notifica trasparente con il valore di "data1"
Log.d("TAG", "data1:" + dato1); //credo sia una specie di debug
// String salve = getIntent().getExtras().getString("ciao");
// System.out.println("questo è il valore della prima variabile" +salve);
//FARE CONTROLLO IN CASO IL FILE XML E' VUOTO E QUINDI LA STRINGA E' VUOTA
String[] arr = dato1.split("\\|");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " => " + arr[i]);
}
final ArrayList <String> listp = new ArrayList<String>();
for (int i = 0; i < arr.length; ++i) {
listp.add(arr[i]);
}
// recupero la lista dal layout
final ListView mylist = (ListView) findViewById(R.id.listView1);
// creo e istruisco l'adattatore
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listp);
// inietto i dati
mylist.setAdapter(adapter);
Button b_load=(Button)findViewById(R.id.button_send2);
b_load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openTrack = new Intent(Page1.this, Track.class);
startActivity(openTrack);
}
});
}
This is the code of Track.java:
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
And this is the code of the xml file associate to Track.java, called "activity_track.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="In attesa di essere localizzati..."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:id="#+id/locationText"/>
</RelativeLayout>
This is LogCat's code:
08-08 00:04:23.801 2217-2217/com.example.giacomob.myapplication I/art﹕ Not late-enabling -Xcheck:jni (already on)
08-08 00:04:24.035 2217-2234/com.example.giacomob.myapplication I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398620, error=EGL_SUCCESS
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Root element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ ----------------------------
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ [ 08-08 00:04:25.762 2217: 2217 I/System.out ]
Current Element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Coordinata X : 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Naziome : Italia
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Paese : Cannole
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Via : Piazza San Vincenzo
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 0 => 1
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1 => 2
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 2 => Italia
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 3 => Cannole
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 4 => Piazza San Vincenzo
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa511b960, error=EGL_SUCCESS
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398900, error=EGL_SUCCESS
08-08 00:04:26.893 2217-2217/com.example.giacomob.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.giacomob.myapplication, PID: 2217
java.lang.RuntimeException: Unable to resume activity {com.example.giacomob.myapplication/com.example.giacomob.myapplication.Track}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at com.example.giacomob.myapplication.Track.onResume(Track.java:39)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2978)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This is the update of Track.java
package com.example.giacomob.myapplication;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
// private LocationManager locationManager=null;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
private static final int MIN_DIST = 20;
private static final int MIN_PERIOD = 30000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
// LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
I don't understand the reason for witch the app is closed! Please, help me! Thanks
You never instantiate your LocationManager reference. This must be done in onCreate like this:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
The app crashes due to a Null Pointer Exception.
The answer of andrewdleach is correct; and the exact line to add in onCreate is this:
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
EDIT:
ok, try to use this
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener
{
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (locationManager == null)
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
{
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
if (locationManager != null)
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
I was writing an app to read heart rate and step count using an android wear device. The heart rate sensor works properly but the step count is causing an issue. However, on commenting the listener for Step Counter and registering a null in onResume() the app works with heart rate sensor. I'm not getting any log regarding this otherwise I would have posted it here. Here's the code that I'm using
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.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import java.nio.ByteBuffer;
import java.util.List;
public class MainActivity extends Activity {
private SensorManager mSensorManager;
private TextView mTextViewHeart, mTextViewStep;
private Sensor mHeartRateSensor, mStepCounterSensor;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextViewHeart = (TextView) stub.findViewById(R.id.value_heart);
mTextViewStep = (TextView) stub.findViewById(R.id.value_step);
}
});
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(heartListener, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(stepListener, mStepCounterSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(heartListener, mHeartRateSensor);
}
SensorEventListener heartListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
if (event.values.length > 0) {
if (event.values[0] > 0.0f) {
mTextViewHeart.setBackgroundResource(android.R.color.holo_green_light);
mTextViewHeart.setText(Float.toString(event.values[0]));
sendToHandheld(Math.round(event.values[0]), Sensor.TYPE_HEART_RATE);
}
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
SensorEventListener stepListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
if (event.values.length > 0) {
mTextViewStep.setBackgroundResource(android.R.color.holo_green_light);
mTextViewStep.setText(Float.toString(event.values[0]));
sendToHandheld(Math.round(event.values[0]), Sensor.TYPE_STEP_COUNTER);
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
private void sendToHandheld(final int val, final int type) {
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i = 0; i < nodes.size(); i++) {
final Node node = nodes.get(i);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), "/" + type, ByteBuffer.allocate(4).putInt(val).array());
Log.d("Sending", type + ":" + val);
}
}
}
});
}
}
Update
Got the log somehow
06-15 11:46:02.342 3355-3355/com.hsc.fit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.hsc.fit, PID: 3355
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setBackgroundResource(int)' on a null object reference
at com.hsc.fit.MainActivity$3.onSensorChanged(MainActivity.java:92)
at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:405)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Fixed it. The WatchViewStub's setOnLayoutInflatedListener() is called after onResume(), and my Sensor gets registered in onResume(). Since my text view is used in the listener of the sensor, and it wasn't assigned a refrence yet, I was getting a NullPointerException. I moved the sensor registertion inside WatchViewStub's listener and it works now.
This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 8 years ago.
I have a dialog fragment named ShareId and a service named
SendMapDataService.When i called the SendMapDataService from ShareId
got error cant create handler inside thread that has not called
looper.prepare....
ShareId
package dialog;
import com.rosaloves.bitlyj.Url;
import static com.rosaloves.bitlyj.Bitly.*;
import java.util.Calendar;
import updatedata.GPSTracker;
import updatedata.SendMapDataService;
import com.example.map.LocationSendActivity;
import com.example.map.R;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ShareId extends DialogFragment {
Button ok,cancel;
public static EditText et;
private double latt,lngt;
public static String sid,lat,lng,time;
ProgressDialog pDialog;
GPSTracker gps;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.shareid, container, false);
ok=(Button)V.findViewById(R.id.button1);
cancel=(Button)V.findViewById(R.id.button2);
et=(EditText)V.findViewById(R.id.editText1);
getDialog().setTitle("Enter Share_id");
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sid=et.getText().toString();
if(sid.length() == 0 ){
Toast.makeText(getActivity(),"Please enter share_id",Toast.LENGTH_SHORT).show();
}else{
new ShareTask().execute();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getDialog().dismiss();
}
});
return V;
}
class ShareTask extends AsyncTask<String, String, String>{
StringBuffer sbf2=new StringBuffer();
boolean b=false;
int ch;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Application. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Create download Url
Url url = as("adeveloper962", "R_38e071119c3048db892f3aca82b03392")
.call(shorten("http://map.rhaasoft.net//locationfile/download.php"));
String ul = url.getShortUrl();
sbf2.append("Click for download LocationMapping file"+" "+ul+"\n");
//Create location Url
gps = new GPSTracker(getActivity());
if(gps.canGetLocation()){
Log.e("Shareid", "hello");
b=true;
//get Time
time= java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
//get latitude longitude
latt = gps.getLatitude();
lat=String.valueOf(latt);
lngt= gps.getLongitude();
lng=String.valueOf(lngt);
//add link
Uri.Builder ur=Uri.parse("http://myapp.com/?").buildUpon();
ur.appendQueryParameter("la", lat);
ur.appendQueryParameter("ln", lng);
ur.appendQueryParameter("ti", time);
ur.appendQueryParameter("id", sid);
ur.build();
//shorting url
Url url1 = as("adeveloper962", "R_38e071119c3048db892f3aca82b03392")
.call(shorten(ur.toString()));
String ul1 = url1.getShortUrl();
//append
sbf2.append("Click for show location"+" "+ul1);
}else{
b=false;
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
public void run() {
if(b == true){
getDialog().dismiss();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Location Shareing");
intent.putExtra(Intent.EXTRA_TEXT, sbf2.toString());
startActivity(Intent.createChooser(intent, "Select Application for share"));
//Send continue data
ch=LocationSendActivity.state;
if(ch == 0 || ch ==1){
LocationSendActivity.i=1;
LocationSendActivity.u_id=sid;
getActivity().startService(new Intent(getActivity(),SendMapDataService.class));
}else{
LocationSendActivity.i=0;
getActivity().stopService(new Intent(getActivity(),SendMapDataService.class));
}
}else{
getDialog().dismiss();
gps.showSettingsAlert();
}
}
});
}
}
}
SendMapDataService..
package updatedata;
import java.util.Calendar;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.map.FunctionCall;
import com.example.map.LocationSendActivity;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
public class SendMapDataService extends Service {
private Handler handler;
private String id1,lat1,lng1,time1;
private double lat,lng;
GPSTracker gps;
private long total,val,min;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
gps=new GPSTracker(getApplicationContext());
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
id1=LocationSendActivity.u_id;
// Log.e("Myid", String.valueOf(LocationSendActivity.u_id));
// get time from time interval
if(min == 1){
val=15;
}else if(min == 2){
val=30;
}else if(min == 3){
val=60;
}else if(min == 4){
val=5*60;
}else if(min == 5){
val=10*60;
}
else{
val=15;
}
total=(long) (val*1000);
// Log.e("Seconds", String.valueOf(total));
// Start handler
handler=new Handler();
handler.postDelayed(runn, 1000);
// Looper.loop();
return START_STICKY;
}
Runnable runn = new Runnable() {
#Override
public void run() {
gps=new GPSTracker(getApplicationContext());
if(gps.canGetLocation()){
lat = gps.getLatitude();
lng = gps.getLongitude();
time1=java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
lat1=String.valueOf(lat);
lng1=String.valueOf(lng);
new SendUpdatedData(id1,lat1,lng1,time1).execute();
handler.postDelayed(this, total);
}else{
gps.showSettingsAlert();
}
}
};
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runn,null);
Toast.makeText(this, "Data Send Service Destroyed", Toast.LENGTH_LONG).show();
}
class SendUpdatedData extends AsyncTask<String, String, String>{
String id2,lat2,lng2,time2;
int success,val,update;
public SendUpdatedData(String id, String lat,String lng,String time) {
// TODO Auto-generated constructor stub
this.id2=id;
this.lat2=lat;
this.lng2=lng;
this.time2=time;
}
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
FunctionCall fc=new FunctionCall();
JSONObject jo=fc.sendUpdateData(id2,lat2,lng2,time2);
try{
success=jo.getInt("success");
update=jo.getInt("update");
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url){
if (success==1){
if(update == 1){
Toast.makeText(getApplication(),"Data Updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplication(),"New Data Inserted", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getApplication(),"Data Not Send", Toast.LENGTH_SHORT).show();
}
}
}
}
LogCat....
02-06 12:16:43.740: W/System.err(15622): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
02-06 12:16:43.740: W/System.err(15622): at android.os.Handler.<init>(Handler.java:121)
02-06 12:16:43.740: W/System.err(15622): at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:137)
02-06 12:16:43.750: W/System.err(15622): at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:137)
02-06 12:16:43.750: W/System.err(15622): at android.location.LocationManager._requestLocationUpdates(LocationManager.java:708)
02-06 12:16:43.750: W/System.err(15622): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:630)
02-06 12:16:43.750: W/System.err(15622): at updatedata.GPSTracker.getLocation(GPSTracker.java:65)
02-06 12:16:43.750: W/System.err(15622): at updatedata.GPSTracker.<init>(GPSTracker.java:44)
02-06 12:16:43.750: W/System.err(15622): at dialog.ShareId$ShareTask.doInBackground(ShareId.java:96)
02-06 12:16:43.750: W/System.err(15622): at dialog.ShareId$ShareTask.doInBackground(ShareId.java:1)
02-06 12:16:43.750: W/System.err(15622): at android.os.AsyncTask$2.call(AsyncTask.java:185)
02-06 12:16:43.750: W/System.err(15622): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-06 12:16:43.750: W/System.err(15622): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-06 12:16:43.750: W/System.err(15622): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
02-06 12:16:43.750: W/System.err(15622): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
02-06 12:16:43.750: W/System.err(15622): at java.lang.Thread.run(Thread.java:1096)
Just call Looper.prepare(); above the line where you got exception..