Already managing a GoogleApiClient with id 0 error despite implementing onPause() - java

When clicked on a Cardview, my application will display a start an activity which will display nearby places in a Recycler view. But whenever I clicked on the cardview I'm having the error shown below. Miraculously when I comment out nearByPlace("restaurant") in NearbyActivity.java the program does not crash. So is it possible because the nearByPlace("restaurant") is also using the same id and how do i fix it
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.sunshine/com.example.android.sunshine.MainActivity}: java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0
Error Logcat
ItemOneFragment.Java
private void init() {
mGeoDataClient = Places.getGeoDataClient(getActivity(), null);
// Construct a PlaceDetectionClient.
mPlaceDetectionClient = Places.getPlaceDetectionClient(getActivity(), null);
mGoogleApiClient = new GoogleApiClient
.Builder(getActivity())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(getActivity(), 0, this)
.build();
SessionData.setSessionId("0");
mSearchText.setOnItemClickListener(mAutocompleteClickListener);
placeAutocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(), mGeoDataClient, LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(placeAutocompleteAdapter);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
cardShopMall = (CardView) getView().findViewById(R.id.textViewShopMall);
cardShopMall.setOnClickListener(cardShopMallOnClickListener);
if (isServicesOK()) {
getLocationPermission();
}
if (mLocationPermissionsGranted) {
getDeviceLocation();
init();
}
}
CardView.OnClickListener cardShopMallOnClickListener = new CardView.OnClickListener(){
#Override
public void onClick(View view) {
String type = "shopping_mall";
Intent i = new Intent(getContext(),NearbyActivity.class);
i.putExtra("type",type);
i.putExtra("latitude",latitude);
i.putExtra("longitude",longitude);
startActivity(i);
}
};
NearbyActivity.Java
IGoogleAPIService mServiceNear;
private GoogleApiClient mGoogleApiClient;
public NearbyActivity() {
Retrofit retrofit1 = RetrofitClient2.getClient("https://maps.googleapis.com/");
mServiceNear = retrofit1.create(IGoogleAPIService.class);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, 2 ,this)
.build();
Intent intent = getIntent();
String type = intent.getExtras().getString("type");
latitude = intent.getExtras().getDouble("latitude");
longitude = intent.getExtras().getDouble("longitude");
try {
nearByPlace("restaurant");
} catch (Exception e) {
e.printStackTrace();
}
}
private void nearByPlace(final String type) {
String url = getUrl(latitude,longitude,type);
Log.d(TAG,"underURL# nearByPlace : " + url);
mServiceNear.getNearByPlaces(url)
.enqueue(new Callback<MyPlaces>() {
#Override
public void onResponse(Call<MyPlaces> call, retrofit2.Response<MyPlaces> response) {
try {
if (response.isSuccessful()){
Log.d(TAG,"responnse : ok");
try {
if (response.body() != null){
for (int i=0;i<response.body().getResults().length;i++){
Results googlePlace = response.body().getResults()[i];
String placeName = googlePlace.getName();
String vicinity = googlePlace.getVicinity();
Log.d(TAG,"nearByPlaces: " + placeName);
ListItem item = new ListItem(
googlePlace.getName(),
googlePlace.getVicinity()
);
listItems.add(item);
}
}else {
Toast.makeText(getApplicationContext(),"No Nearby " + type,Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
adapter = new MyAdapter(listItems,NearbyActivity.this);
recyclerView.setAdapter(adapter);
}
}catch (Exception e){
e.getMessage();
}
}
#Override
public void onFailure(Call<MyPlaces> call, Throwable t) {
}
});
}
private String getUrl(double latitude, double longitude, String restaurant) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location="+latitude+","+longitude);
googlePlacesUrl.append("&radius="+5000);
googlePlacesUrl.append("&type="+restaurant);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key="+getResources().getString(R.string.GoogleAPiKey));
Log.d(TAG,"getURL : " + googlePlacesUrl.toString());
return googlePlacesUrl.toString();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.stopAutoManage(this);
mGoogleApiClient.disconnect();
}
}

Yes you have correctly implemented onPause for your Activity but not for your Fragment.
In your init method inside your Fragment you create a new GoogleApiClient. This differs from the one in your Activity, in which - as mentioned before - you correctly implemented onPause.
Therefore the solution to your issue should be implementing onPause for your Fragment.
I hope this will resolve your issue

Related

Broadcast manager not working in Fragment

I have a BroadcastReceiver which is used to receive data from a BLE device. The same code is working fine in an Activity but not in Fragment.
Here is the code:
public class HomeFragment extends Fragment implements LocationListener {
Session session;
TextView textViewName;
TextView textViewSteps;
TextView textViewCalories;
TextView textViewDistance;
TextView textViewFimos;
ImageView imageViewInfo;
public static final String TAG = "StepCounter";
private UARTService mService = null;
private BluetoothDevice evolutionDevice = null;
private static final int UART_PROFILE_CONNECTED = 20;
private static final int UART_PROFILE_DISCONNECTED = 21;
private int mState = UART_PROFILE_DISCONNECTED;
MyDatabase myDatabase;
LocationManager service;
private LocationManager locationManager;
private String provider;
double latitude, longitude;
List<Byte> listBytes = new ArrayList<>();
int rowNumber = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_home, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
init(view);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
service_init();
}
private void init(View view) {
session = new Session(getActivity());
myDatabase = new MyDatabase(getActivity());
service = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 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.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
textViewName = view.findViewById(R.id.textViewName);
textViewSteps = view.findViewById(R.id.textViewSteps);
textViewCalories = view.findViewById(R.id.textViewCalories);
textViewDistance = view.findViewById(R.id.textViewDistance);
textViewFimos = view.findViewById(R.id.textViewFimos);
imageViewInfo = view.findViewById(R.id.imageViewInfo);
try {
textViewName.setText("Hi, " + session.getUser().getUser().getName());
} catch (Exception e) {
}
}
private void service_init() {
System.out.println("---->>>>");
Intent bindIntent = new Intent(getActivity().getApplicationContext(), UARTService.class);
getActivity().bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder rawBinder) {
mService = ((UARTService.LocalBinder) rawBinder).getService();
Log.d(TAG, "onServiceConnected mService= " + mService);
if (!mService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
getActivity().finish();
}
}
public void onServiceDisconnected(ComponentName classname) {
mService = null;
}
};
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UARTService.ACTION_GATT_CONNECTED);
intentFilter.addAction(UARTService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(UARTService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(UARTService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(UARTService.DEVICE_DOES_NOT_SUPPORT_UART);
return intentFilter;
}
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final Intent mIntent = intent;
//*********************//
if (action.equals(UARTService.ACTION_GATT_CONNECTED)) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
System.out.println("------- Device Connected: " + evolutionDevice.getName() + " - " + evolutionDevice.getAddress());
mState = UART_PROFILE_CONNECTED;
}
});
}
//*********************//
if (action.equals(UARTService.ACTION_GATT_DISCONNECTED)) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
System.out.println("------- Device Disconnected");
mState = UART_PROFILE_DISCONNECTED;
mService.close();
evolutionDevice = null;
}
});
}
//*********************//
if (action.equals(UARTService.ACTION_GATT_SERVICES_DISCOVERED)) {
mService.enableTXNotification();
}
//*********************//
if (action.equals(UARTService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UARTService.EXTRA_DATA);
List<Byte> byteList = Bytes.asList(txValue);
combineArrays(byteList);
}
//*********************//
if (action.equals(UARTService.DEVICE_DOES_NOT_SUPPORT_UART)) {
System.out.println("------- Device doesn't support UART. Disconnecting");
mService.disconnect();
}
}
};
#Override
public void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 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.
return;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
Log.d(TAG, "onResume");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
try {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(UARTStatusChangeReceiver);
} catch (Exception ignore) {
Log.e(TAG, ignore.toString());
}
getActivity().unbindService(mServiceConnection);
mService.stopSelf();
mService = null;
}
The complete code in the same ay with a few changes in working fine in Activity. Any idea what might be the blocker.? Do I need to do something else in the fragment to receive the data from the Local Broadcast Manager.?
Please try this way :
Create class BroadcastHelper
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hossam";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And in your fragment :
private Receiver receiver;
private boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "Test":
Toast.makeText(getActivity(), "message", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
}
And to send your broadcast this this code :
BroadcastHelper.sendInform(context, "Test");
Or if you want to send data with it use :
Intent intent = new Intent("intent");
intent.putExtra("desc", desc);
intent.putExtra("name", Local_name);
intent.putExtra("code", productCode);
BroadcastHelper.sendInform(getActivity(), "Test" , intent);
I have a fragment where I do something similar. I put my code to setup the service in onCreateView and have a register and unregister in onPause() and onResume. Works good for me.
Can you check modify register receiver in service_init()
as
getActivity().registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
and for unregisterer receiver
getActivity().unregisterReceiver(UARTStatusChangeReceiver);

OnLocationChanged() is not automatically called. The location is not stored in the database

I have a gpsTracker java class which contains the onLocationChanged() method. I want to link my MainActivity's OnCreate function with this onLocationChanged() method.
public void onLocationChanged(Location newlocation) {
Log.d("latitude", "old" + Double.toString(this.location.getLatitude()));
Log.d("Longitude", "old " +
Double.toString(this.location.getLatitude()));
Log.i("info","LOCATION CHANGED");
Log.d("latitude", "NEW: CHANGED TO KOLKATA" +
Double.toString(newlocation.getLatitude()));
Log.d("Longitude", "NEW: CHANGED TO KOLKATA " +
Double.toString(newlocation.getLatitude()));
this.location = newlocation;
JSONObject locationChange = new JSONObject();
getLocationName(location.getLatitude(), location.getLongitude());
try {
locationChange.put("userid",
PreferenceManager.getInstance().getUserId());
locationChange.put("location", addressString);
locationChange.put("connection",
PreferenceManager.getInstance().getConnectAllow() ? "1" : "0");
locationChange.put("connection", "0");
locationChange.put("notification",
PreferenceManager.getInstance().getPushNotiAllow() ? "0" : "1");
Log.d(TAG, "LOCATION CHANGED BY GPS FUNCTION: " + locationChange);
RequestHandler.getInstance().postWithHeader(null,
getString(R.string.baseurl) + getString(R.string.settings),
locationChange, this,
AppConstants.ApiRequestCodeKey.SAVE_APP_SETTINGS);
}catch (JSONException e) {
e.printStackTrace();
}
}
public void getLocationName(double latitude, double longitude) {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
addressString = addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ";
} catch (IOException e) {
e.printStackTrace();
}
}>
The onCreate function in the MainActivity() contains this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_frame);
utils.mixpanelTrack(this, "Reached Home Page");
homeFragObj = this;
initViews();
initSetup();
initListeners();
loadData();
>
To receive every location change in your Activiy, it´s the best option to use Broadcasts. Create a instance variable of BroadcastReceiver:
BroadcastReceiver mReceiver;
In onCreate() add this receiver:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_frame);
IntentFilter filter = new IntentFilter();
filter.addAction("LOCATION_CHANGE");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String latitude = intent.getExtras().getString("LATITUDE");
String longitude= intent.getExtras().getString("LONGITUDE");
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
}
Don´t forget to unregister the receiver if Activity closes:
#Override
protected void onDestroy() {
if (mReceiver != null) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
mReceiver = null;
}
super.onDestroy();
}
And on OnLocationChange in your Utils class, send the Broadcast after you have the coordinates like this:
Intent intent=new Intent(context,YourActivity.class);
intent.setAction("LOCATION_CHANGE");
intent.putExtra("LATITUDE",Double.toString(latitude));
intent.putExtra("LONGITUDE",Double.toString(longitude));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
What you need is the context that you can pass via your constructor of your Utils class, for example, if you create an instance in your Activity:
MyUtils utils = new MyUtils(this);
This is just a basic answer, there are some things you have to be aware of.
Class A{
Context ctx;
public A(Context ctx){
this.ctx=ctx;
}
//your rest code
}
In MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_frame);
utils.mixpanelTrack(this, "Reached Home Page");
homeFragObj = this;
initViews();
initSetup();
initListeners();
loadData();
A a=new A(this);//Making an Obj
a.onLocationChanged(location);//your method invocation
Hope this helps.

How to call a condition on a view?

I have two activities in first activity, I have two text views fromLocation and toLocation. On click of from and to text view I am calling next activity in which I have a map and I choose a location which I am storing in string and showing on text view. This choose location I want to show on fromLocation text view of first activity onClick of a layout of useLocation in second activity on the basis of which text view is choose. If onClick of fromLocation the address should show on fromLocation text view and onClick of toLocation address should show on toLocation. This will be onResume method of first activity.
Now I am getting the address on both text views when I choose address for first time onClick on fromLocation text view.
How to do this..?
GoSendActivity(FirstActivity)
public class GoSend extends AppCompatActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private GoogleMap mGoogleMap;
private MarkerOptions markerOptions;
private LinearLayout ll;
private TextView additionalContactFrom,additionalContactTo,txt_from,txt_to;
private LinearLayout linearLayoutFrom,linearLayoutTo;
private ImageView next;
private Toolbar toolbar;
private EditText locdetailsFrom,locdetailsTo,itemDetails;
private Intent i;
private LatLng currentLocation,curentpoint,center;
private GPSTracker gps;
double latitude,longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
public void setUI() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("COURIER");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
locdetailsFrom = (EditText) findViewById(R.id.editText_from_details);
locdetailsFrom.setText(GoSendData.instance.getmFromLocationDetails());
locdetailsTo = (EditText) findViewById(R.id.editText_to_details);
locdetailsTo.setText(GoSendData.instance.getmToLocationDetails());
itemDetails = (EditText) findViewById(R.id.editText_ItemDetail);
txt_from = (TextView) findViewById(R.id.Text_from);
txt_to = (TextView) findViewById(R.id.Text_to);
additionalContactFrom = (TextView) findViewById(R.id.contactDetailsFrom);
additionalContactTo = (TextView) findViewById(R.id.contactDetailsTo);
linearLayoutFrom = (LinearLayout) findViewById(R.id.LinearLayoutFrom);
linearLayoutTo = (LinearLayout) findViewById(R.id.LinearLayoutTo);
next = (ImageView) findViewById(R.id.imageView_next);
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
/// GoSendData.instance.addressType=0;
startActivity(i);
}
});
txt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
//GoSendData.instance.addressType=1;
startActivity(i);
}
});
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (linearLayoutFrom.getVisibility() == View.GONE) {
linearLayoutFrom.setVisibility(View.VISIBLE);
} else {
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
additionalContactTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (linearLayoutTo.getVisibility() == View.GONE) {
linearLayoutTo.setVisibility(View.VISIBLE);
} else {
linearLayoutTo.setVisibility(View.GONE);
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), GoSendDetailsActivity.class);
startActivity(i);
}
});
}
#Override
public void onResume() {
int LocationClick;
super.onResume(); // Always call the superclass method first
txt_from.setText(GoSendData.instance.mFromLocation);
txt_to.setText(GoSendData.instance.mToLocation);
}
private void setupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mGoogleMap.addMarker(markerOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
setupMap();
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
ChooseFromMapActivity(second activity)
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center,curentpoint;
private LinearLayout markerLayout,useLocation;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude,longitude;
private GPSTracker gps;
Intent intent;
double x, y;
StringBuilder str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
SetUpUI();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(ChooseFromMapActivity.this,GoSend.class);
startActivity(intent);
}
});
}
private void SetUpUI(){
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("CHOOSE FROM MAP");
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
GoSendData.instance.mFromLocation=addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ";
GoSendData.instance.mToLocation=addresses.get(0).getAddressLine(0)+addresses.get(0).getAddressLine(1)+"";
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
If i understand correctly.. You should launch second activity as startActivityForResult and after choosing location on map return it as a result.
The first activity should now this value from the method onActivityResult
http://developer.android.com/training/basics/intents/result.html
Click on first textview launch second activity with requestcode
Second activity after choosing location finishes with setResult, where you store chosen location
Get the result in onActivityResult of first activity and set it to textView
the same for second textview. Use different requestcodes for different textview, which you should check in onActivityResult to determine which textView data was chosen in second activity

getLastLocation returns a null value

I have followed this guide https://developer.android.com/training/location/retrieve-current.html#permissions, and I'm not able to receive the last location.
I need the location just one time.
Here my code:
public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
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 GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private double mLatitude;
private double mLongitude;
#Bind(R.id.timeLabel) TextView mTimeLabel;
#Bind(R.id.temperatureLabel) TextView mTemperatureLabel;
#Bind(R.id.humidityValue) TextView mHumidityValue;
#Bind(R.id.precipValue) TextView mPrecipValue;
#Bind(R.id.summaryLabel) TextView mSummaryLabel;
#Bind(R.id.iconImageView) ImageView mIconImageView;
#Bind(R.id.refreshImageView) ImageView mRefreshImageView;
#Bind(R.id.progressBar) ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mProgressBar.setVisibility(View.INVISIBLE);
buildGoogleApiClient();
//mLatitude = 37.8267;
//mLongitude = -122.423;
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(mLatitude, mLongitude);
}
});
getForecast(mLatitude, mLongitude);
}
private void getForecast(double latitude, double longitude) {
String apiKey = "48fb6c0ca3567d0b17bf99b400ef5606";
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()) {
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) {
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() {
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 = getResources().getDrawable(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.setTime(jsonDay.getLong("time"));
day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
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.getInt("time"));
current.setSummary(currently.getString("summary"));
current.setTemperature(currently.getInt("temperature"));
current.setIcon(currently.getString("icon"));
current.setPrecipChance(currently.getDouble("precipProbability"));
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);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mLatitude = mLastLocation.getLatitude();
mLongitude = mLastLocation.getLongitude();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
`
getLastLocation() has a high tendency to return null. It also does not request a new location, so even if you get a location, it could be very old, and not reflect the current location. Better to register a listener, even if you just unregister after you get the first onLocationChanged() callback.
This question gets asked a lot, and usually is marked as a duplicate of questions like this one
However, in your case, it also looks like you just forgot to call connect():
buildGoogleApiClient();
mGoogleApiClient.connect(); //added
You can use the code in this answer as a reference for registering for location callbacks, which is suggested if you want to get an accurate current location.
Edit: Since you need only one location, here is a slightly modified version of that code, which requests location updates, and then un-registers for location updates after the first location comes in.
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private double mLatitude;
private double mLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//no need to do a null check here:
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
//remove location updates if you just need one location:
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}

Variable is initialized but appears to be null in onClick method

public class PickUpFragment extends SherlockFragment implements OnMarkerDragListener, OnCameraChangeListener
{
View rootView;
private SupportMapFragment fragment;
private GoogleMap map;
private MySupportMapFragment itsMySupportMapFragment;
RelativeLayout progress_rl;
RelativeLayout map_rl;
Button button;
public LatLng latlng;
TextView tv;
public String address = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_pickup, container, false);
progress_rl= (RelativeLayout)rootView.findViewById(R.id.progress);
map_rl = (RelativeLayout)rootView.findViewById(R.id.map_container);
//button.setOnClickListener(pickup);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
itsMySupportMapFragment = new MySupportMapFragment();
MapViewCreatedListener mapViewCreatedListener = new MapViewCreatedListener() {
#Override
public void onMapCreated() {
initPlacesGoogleMapCtrl();
}
};
itsMySupportMapFragment.itsMapViewCreatedListener = mapViewCreatedListener;
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.map, itsMySupportMapFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Marker marker;
Location loc;
public void initPlacesGoogleMapCtrl() {
// Map ready, get it.
map = itsMySupportMapFragment.getMap();
// Do what you want...
map.setOnCameraChangeListener(this);
map.moveCamera(CameraUpdateFactory.zoomTo(15));
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSherlockActivity().getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider
latlng = new LatLng(location.getLatitude(),location.getLongitude());
if(loc == null)
{
loc = location;
map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
//marker = map.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(),location.getLongitude())).draggable(true));
try {
tv = (TextView) rootView.findViewById(R.id.map_address);
Geocoder geo = new Geocoder(PickUpFragment.this.getSherlockActivity().getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.isEmpty()) {
tv.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
String addr = "";
if(addresses.get(0).getFeatureName() != null || addresses.get(0).getFeatureName().equals("null"))
{
addr += addresses.get(0).getFeatureName();
}
if(addresses.get(0).getThoroughfare() != null || addresses.get(0).getThoroughfare().equals("null") && !addresses.get(0).getThoroughfare().equals(addresses.get(0).getFeatureName()))
{
addr += " " + addresses.get(0).getThoroughfare();
}
if(addresses.get(0).getLocality() != null || addresses.get(0).getLocality().equals("null"))
{
addr += ", " + addresses.get(0).getLocality();
}
address = addr + ", " + addresses.get(0).getAdminArea();
tv.setText(address);
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
public void pickup(View v, Activity act)
{
Sync sync = new Sync();
String ad = tv.getText().toString();
sync.makeBooking(latlng, ad, getActivity());
RelativeLayout progress_rl = (RelativeLayout)act.findViewById(R.id.progress);
progress_rl.setVisibility(getView().VISIBLE);
RelativeLayout map_rl = (RelativeLayout)act.findViewById(R.id.map_container);
map_rl.setVisibility(getView().GONE);
ProgressBar spinner = (ProgressBar) progress_rl.findViewById(R.id.progress_bar);
spinner.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
#Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragEnd(Marker arg0) {
}
#Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onCameraChange(CameraPosition arg0) {
try
{
latlng = arg0.target;
tv = (TextView) rootView.findViewById(R.id.map_address);
Async async = new Async();
async.execute();
}
catch(Exception e)
{
}
}
private class Async extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... arg0) {
try
{
Geocoder geo = new Geocoder(PickUpFragment.this.getSherlockActivity().getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latlng.latitude, latlng.longitude, 1);
if (addresses.isEmpty()) {
}
else {
if (addresses.size() > 0) {
String addr = "";
if(addresses.get(0).getFeatureName() != null && !addresses.get(0).getFeatureName().equals("null"))
{
addr += addresses.get(0).getFeatureName();
}
if(addresses.get(0).getThoroughfare() != null && !addresses.get(0).getThoroughfare().equals("null") && !addresses.get(0).getThoroughfare().equals(addresses.get(0).getFeatureName()))
{
addr += " " + addresses.get(0).getThoroughfare();
}
if(addresses.get(0).getLocality() != null && !addresses.get(0).getLocality().equals("null"))
{
addr += ", " + addresses.get(0).getLocality();
}
address = addr + ", " + addresses.get(0).getAdminArea();
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch(IOException e)
{
}
return null;
}
#Override
protected void onPreExecute()
{
tv.setText("Waiting for Location");
}
#Override
protected void onPostExecute(String result)
{
tv.setText(address);
}
}
}
The TextView tv is initialized the method initPlacesGoogleMapCtrl(). When I debug and step through line by line I can see that it was the correct value.
But when I try to use this value in pickup() it's null even though it was initialized earlier.
rootView and all the other class variables that are set throughout the running of the app are all null in the pickup method.
Any idea why it would be initialized and then suddenly it's null?

Categories