0

I am trying to get current location but it not getting on real device but worked on emulator

This is my error --->

Process: in.co.getonlinerecharge.cab.bw_driver, PID: 28061 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference at in.co.getonlinerecharge.cab.bw_driver.activity.HomeActivity.Send_Data_Fragment(HomeActivity.java:143) at in.co.getonlinerecharge.cab.bw_driver.activity.HomeActivity.onNavigationItemSelected(HomeActivity.java:215);

package in.co.getonlinerecharge.cab.bw_driver.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
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.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import in.co.getonlinerecharge.cab.bw_driver.AppController;
import in.co.getonlinerecharge.cab.bw_driver.R;
import in.co.getonlinerecharge.cab.bw_driver.fragment.EarningFragment;
import in.co.getonlinerecharge.cab.bw_driver.fragment.HomeFragment;
import in.co.getonlinerecharge.cab.bw_driver.fragment.ProfileFragment;
import in.co.getonlinerecharge.cab.bw_driver.fragment.RatingFragment;
import in.co.getonlinerecharge.cab.bw_driver.helper.ToastHelper;
import in.co.getonlinerecharge.cab.bw_driver.utils.Constans;
import in.co.getonlinerecharge.cab.bw_driver.utils.Utils;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private BottomNavigationView bottomNavigation;
    private Switch switch1;
    private TextView txt_on_off;
    private Toolbar toolbar;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    LocationRequest mLocationRequest;
    double slat, slong;
    String add;
    Geocoder geocoder;
    List<Address> addresses = null;
    String address = "", city = "", state = "", country = "", postalCode = "", knownName = "";
    //double clat,clang;
    String pincode, location, calt, clong;

protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
View.OnClickListener mOnClickListener;
private FragmentManager fragmentManager = getSupportFragmentManager();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    bottomNavigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    bottomNavigation.inflateMenu(R.menu.bottom_menu);
    bottomNavigation.setOnNavigationItemSelectedListener(this);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    switch1 = (Switch) toolbar.findViewById(R.id.switch1);
    txt_on_off = (TextView) toolbar.findViewById(R.id.txt_on_off);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    } else {
        Toast.makeText(this, "Not Connected!", Toast.LENGTH_SHORT).show();
    }

    switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean ischacked) {
            if (!ischacked) {
                txt_on_off.setText("OFF");
                Snackbar.make(findViewById(android.R.id.content), "You need to turn on first", Snackbar.LENGTH_LONG)
                        .setAction("Undo", mOnClickListener)
                        .setActionTextColor(Color.RED)
                        .show();

            } else {


                txt_on_off.setText("ON");
                Send_Data_Fragment();
                Send_Location();
                Timer timer = new Timer();
                TimerTask hourlyTask = new TimerTask() {
                    @Override
                    public void run() {
                        Send_Location();
                    }
                };
                timer.schedule (hourlyTask, 0l, 1000*5*60);
            }

        }
    });

}

private void Send_Data_Fragment() {
    if (!calt.isEmpty() && !clong.isEmpty())

    {

//            HomeFragment fragment = new HomeFragment();
//            Bundle bundle = new Bundle();
//            bundle.putDouble("clat", Double.parseDouble(calt));
//            bundle.putDouble("clong", Double.parseDouble(clong));
//            fragment.setArguments(bundle);
           // ToastHelper.make(getApplicationContext(), true, "data has been transferd");
            Fragment fragment = new HomeFragment();//Get Fragment Instance
            Bundle data = new Bundle();//Use bundle to pass data
            data.putDouble("clat",Double.parseDouble(calt));
            data.putDouble("clong",Double.parseDouble(clong));
            //put string, int, etc in bundle with a key value
            fragment.setArguments(data);
            fragmentManager.beginTransaction().replace(R.id.main_container, fragment).commit();
        }
        else
            {
                ToastHelper.make(getApplicationContext(), true, "Please reconnect");
            }
}

private void Send_Location() {

    if (!pincode.isEmpty() && !location.isEmpty() && !calt.isEmpty() && 

!clong.isEmpty()) {
//            final ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
//            progressDialog.show();
//            progressDialog.setMessage(getString(R.string.please_wait));
            Call<ResponseBody> call = AppController.getInstance().getApiInterface().postLocation(Utils.getSharedPreference(getApplicationContext()).getString(Constans.PREFERENCE_DRIVER_UID, ""),
                    location, pincode, calt, clong);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                   // progressDialog.dismiss();
                   // ToastHelper.make(getApplicationContext(), true, pincode + " " + location + " " + calt + " " + clong);
                    String responseString = null;
                    try {
                        responseString = response.body().string();
                        JSONObject jsonObject = new JSONObject(responseString);
                        //ToastHelper.make(getApplicationContext(), true, jsonObject.getString("data"));
//                        if (jsonObject.getBoolean("status")) {
//                            ToastHelper.make(getApplicationContext(), true, jsonObject.getString("data"));
//                        }
                        Utils.getSharedPreference(getApplicationContext()).edit().putString(Constans.PREFERENCE_DRIVER_CLAT,calt);
                        Utils.getSharedPreference(getApplicationContext()).edit().putString(Constans.PREFERENCE_DRIVER_CLONG,clong);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                ToastHelper.make(getApplicationContext(), true, "Please reconnect");
            }
        });

    } else {
        ToastHelper.make(getApplicationContext(), true, "Please reconnect");
    }
}


@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.btm_action_home:
            //Utils.replaceFragment(new HomeFragment(), HomeFragment.class.getName(), false, true, getSupportFragmentManager(), R.id.main_container);
            Send_Data_Fragment();
            break;
        case R.id.btm_action_earning:
            Utils.replaceFragment(new EarningFragment(), EarningFragment.class.getName(), false, true, getSupportFragmentManager(), R.id.main_container);
            break;
        case R.id.btm_action_ratings:
            Utils.replaceFragment(new RatingFragment(), RatingFragment.class.getName(), false, true, getSupportFragmentManager(), R.id.main_container);
            break;
        case R.id.btm_action_account:
            Utils.replaceFragment(new ProfileFragment(), ProfileFragment.class.getName(), false, true, getSupportFragmentManager(), R.id.main_container);
            break;
    }
    return true;
}

@Override
protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();

}



@Override
protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}


@Override
public void onConnected(@Nullable Bundle bundle) {
    settingRequest();



}



@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this, "Connection Suspended!", Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Toast.makeText(this, "Connection Failed!", Toast.LENGTH_SHORT).show();
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, 90000);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    } else {
        Log.i("Current Location", "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

private void settingRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);    // 10 seconds, in milliseconds
    mLocationRequest.setFastestInterval(1000);   // 1 second, in milliseconds
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                    builder.build());

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

        @Override
        public void onResult(@NonNull LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result.getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All location settings are satisfied. The client can
                    // initialize location requests here.
                    getLocation();
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // Location settings are not satisfied, but this can be fixed
                    // by showing the user a dialog.
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(HomeActivity.this, 1000);
                    } catch (IntentSender.SendIntentException e) {
                        // Ignore the error.
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way
                    // to fix the settings so we won't show the dialog.
                    break;
            }
        }

    });
}

private void getLocation() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
    } else {
        /*Getting the location after aquiring location service*/
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);

        if (mLastLocation != null) {
// 



       _progressBar.setVisibility(View.INVISIBLE);
//                _latitude.setText("Latitude: " + String.valueOf(mLastLocation.getLatitude()));
//                _longitude.setText("Longitude: " + String.valueOf(mLastLocation.getLongitude()));
                //ToastHelper.make(this,true,mLastLocation.getLatitude()+"  "+mLastLocation.getLongitude());
                Geocoder geocoder = new Geocoder(getApplicationContext());
                String Addr=null;

            try
            {
                List<Address> addresses = geocoder.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
                Address obj = addresses.get(0);
                 add = obj.getAddressLine(0);
                String currentAddress = obj.getSubAdminArea() + ","
                        + obj.getAdminArea();
                double latitude = obj.getLatitude();
                double longitude = obj.getLongitude();
                String currentCity= obj.getSubAdminArea();
                String currentState= obj.getAdminArea();
                add = add + "\n" + obj.getCountryName();
                add = add + "\n" + obj.getCountryCode();
                add = add + "\n" + obj.getAdminArea();
                add = add + "\n" + obj.getPostalCode();
                add = add + "\n" + obj.getSubAdminArea();
                add = add + "\n" + obj.getLocality();
                add = add + "\n" + obj.getSubThoroughfare();
                pincode = obj.getPostalCode();
                location = obj.getAdminArea()+" "+obj.getSubAdminArea()+" "+obj.getLocality();
                calt = String.valueOf(mLastLocation.getLatitude());
                clong = String.valueOf(mLastLocation.getLongitude());
               // ToastHelper.make(getApplicationContext(),true,obj.getSubAdminArea() + ","
                 //       + obj.getAdminArea());

            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            /*if there is no last known location. Which means the device has no data for the loction currently.
            * So we will get the current location.
            * For this we'll implement Location Listener and override onLocationChanged*/
            Log.i("Current Location", "No data for location found");

            if (!mGoogleApiClient.isConnected())
                mGoogleApiClient.connect();

            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) HomeActivity.this);
        }
    }
}

@Override
public void onLocationChanged(Location location) {
    if (location != null)
    {
        double slatg =location.getLatitude();
            double slong  = location.getLongitude();
//            clat = slatg;
//            clang = slong;
            try {

            addresses = geocoder.getFromLocation(slatg,slong, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
        } catch (IOException e) {
            e.printStackTrace();
        }
        address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        city = addresses.get(0).getLocality();
        state = addresses.get(0).getAdminArea();
        country = addresses.get(0).getCountryName();
        postalCode = addresses.get(0).getPostalCode();
        knownName = addresses.get(0).getFeatureName();
        //ToastHelper.make(getApplicationContext(),true,""+city);

    }

    try {
        if (location != null)



        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (LocationListener) this);

    } catch (Exception e) {
        e.printStackTrace();
    }
}


 }

I used following permissions in my manifest file

<uses-permission android:name="in.co.getonlinerecharge.cab.bw_cab.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Tejas Shukla
  • 144
  • 7
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – AskNilesh Oct 12 '17 at 07:20
  • 1
    @tejas-shukal, First of all, don't post whole bunch of code. Just the required one for location info. Second of all, check if you have given permission for accessing location info from your manifest. – O_o Oct 12 '17 at 07:27

0 Answers0