尝试调用虚拟方法“ Context android.content.Context.getApplicationContext()”

时间:2019-03-07 14:57:11

标签: geofencing

我正在研究地理围栏。我已经在我的主要活动中创建了google api客户端,并在另一个片段中使用了GoogleApiClient的对象。现在,我收到此异常,应用程序崩溃了。

这是完整的错误详细信息。

2019-03-07 20:01:56.197 10473-10473/com.example.foodtag E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
    at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
    at com.example.foodtag.MainActivity.getGeofencePendingIntent(MainActivity.java:184)
    at com.example.foodtag.CameraFragment.addFence(CameraFragment.java:228)
    at com.example.foodtag.CameraFragment.access$000(CameraFragment.java:72)
    at com.example.foodtag.CameraFragment$1.onClick(CameraFragment.java:163)

这是我的片段类。

public class CameraFragment extends Fragment implements
    AdapterView.OnItemSelectedListener, ResultCallback {
    MainActivity help = new MainActivity();
     @Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_camera, container, false);
    mStorageRef = FirebaseStorage.getInstance().getReference();
    ActivityCompat.requestPermissions((Activity) getContext(),
            new String[]{Manifest.permission.CAMERA}, 0);
    geofencingClient = LocationServices.getGeofencingClient(getContext());
     tag.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


                help.populateGeofenceList(); // 
                Toast.makeText(getContext(), "populated", Toast.LENGTH_SHORT).show();



            addFence(); // error in this method
       }

    });
    return view;
}

这是方法定义:

private void addFence() {

    if (!MainActivity.mClient.isConnected()) {
        Toast.makeText(getContext(), "MClient Not connected", Toast.LENGTH_SHORT).show();
        return;
    }
    try {
        if (ActivityCompat.checkSelfPermission((Activity)getContext(), Manifest.permission.ACCESS_FINE_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.

            ActivityCompat.requestPermissions((Activity)getContext(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
            return;
        }
        LocationServices.GeofencingApi.addGeofences(MainActivity.mClient,
                help.getGeofencingRequest(), //error calling this method which is written in my main activity
               help.getGeofencePendingIntent()
        ).setResultCallback(this);

    }catch (SecurityException securityException){
        Log.e(TAG,"security exception");
    }

}

我的主要活动是这样的

 public class MainActivity extends AppCompatActivity implements
    AdapterView.OnItemSelectedListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LoaderManager.LoaderCallbacks<Cursor>, LocationListener {
    public static final int GEOFENCE_RADIUS = 250;


private static final String LOG_TAG = "MainActivity ";
private static final int MAX_LENGTH = 20;

public double latitude, longitude;
LocationManager locationManager;
public List<Geofence> mGeofenceList = new ArrayList<>();
public static GoogleApiClient mClient;
private Geofencing mGeofencing;
private boolean mIsEnabled;
private CheckBox mRingerPermissionCheckBox;
private static final int PLACE_PICKER_REQUEST = 109;

String Id;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (SaveSharedPreference.getPassword(getApplicationContext()).length() == 0) {
        Intent i = new Intent(getApplicationContext(), Userlogin.class);
        startActivity(i);
    }
    setupViewPager();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions((Activity)this,
                new String[]{Manifest.permission.CAMERA},0);
        return;
    }
    Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);

    onLocationChanged(location);

   // Toast.makeText(this, ""+longitude+latitude, Toast.LENGTH_LONG).show();

    buildGoogleApiClient();
    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);

        //geofencingClient = LocationServices.getGeofencingClient(this);

        // Toast.makeText(this, ""+geofencingClient, Toast.LENGTH_LONG).show();

    }
}

 public synchronized void buildGoogleApiClient() {
    mClient = new GoogleApiClient.Builder(getBaseContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mClient.connect();
    mGeofencing = new Geofencing(mClient,this);
   Toast.makeText(this, ""+mClient, Toast.LENGTH_SHORT).show();
}


private  void setupViewPager(){
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());

    adapter.addFragment(new HomeFragment());
    adapter.addFragment(new CameraFragment());
    adapter.addFragment(new ProfileFragment());
    ViewPager viewPager = (ViewPager) findViewById(R.id.container);
    viewPager.setAdapter(adapter);

    final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    tabLayout.getTabAt(0).setIcon(R.drawable.ic_food);
    tabLayout.getTabAt(1).setIcon(R.drawable.ic_camera);
    tabLayout.getTabAt(2).setIcon(R.drawable.ic_account);
   /* tabLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch()
            {
                case 1:
                Intent i=new Intent( MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(i,0);
            }
        }
    });*/

}
public static String random() {
    Random generator = new Random();
    StringBuilder randomStringBuilder = new StringBuilder();
    int randomLength = generator.nextInt(MAX_LENGTH);
    char tempChar;
    for (int i = 0; i < randomLength; i++){
        tempChar = (char) (generator.nextInt(96) + 32);
        randomStringBuilder.append(tempChar);
    }
    return randomStringBuilder.toString();
}
public void populateGeofenceList(){



   mGeofenceList.add(new Geofence.Builder()
    .setRequestId(random())
    .setCircularRegion(latitude,longitude,GEOFENCE_RADIUS)
    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
            .build());
         Id = random();

   // Toast.makeText(this, ""+mGeofenceList, Toast.LENGTH_SHORT).show();
}

public GeofencingRequest getGeofencingRequest(){
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

public PendingIntent getGeofencePendingIntent(){
    Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);

    return PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
}



@NonNull
@Override
public Loader<Cursor> onCreateLoader(int i, @Nullable Bundle bundle) {
    return null;
}

@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) {

}

@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {

}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

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

    Log.i(LOG_TAG,"Api connection successful");
   // Toast.makeText(this , "onConnected", Toast.LENGTH_SHORT).show();


}

@Override
public void onConnectionSuspended(int i) {
    Log.i(LOG_TAG,"API Client connection suspended.");

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    Log.i(LOG_TAG,"API Connection client suspended.");
    Toast.makeText(this , "onConectionFailed", Toast.LENGTH_SHORT).show();

}

@Override
public void onResume() {
    super.onResume();

    buildGoogleApiClient();


}

@Override
public void onStop() {
    super.onStop();
    try {
        if (mClient.isConnecting() || mClient.isConnected()) {
            mClient.disconnect();
        }
    }catch (NullPointerException n){
        Toast.makeText(this, ""+ n, Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onLocationChanged(Location location) {

    latitude=location.getLatitude();
    longitude = location.getLongitude();

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

}

请帮助我!

0 个答案:

没有答案