Matthew Vedua Matthew Vedua - 3 months ago 9
Android Question

How do i get the activity?

I am requesting permission during run-time, and for the method

requestPermissions()
I need to pass through an activity. However, when I call it in
onClick()
I cannot just pass through
this
. So, how do I pass it through?

The place where I need the activity is in
onRequestPermissionsResult()
, in
case locationPerm:


public class LoginActivity extends AppCompatActivity implements LocationListener {

final int locationPerm = 0;
final int cameraPerm = 1;

Context context;
Activity activity;

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

context = this;


int locationPermissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);

int cameraPermissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);

if (locationPermissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, locationPerm);
}

if (cameraPermissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, cameraPerm);
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case locationPerm: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the

} else { // permission denied,
new AlertDialog.Builder(this)
.setTitle("Location Permission")
.setMessage("Message")
.setPositiveButton("Set a custom location later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(/* NEED ACTIVITY HERE */, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, locationPerm);
}
})
.setNegativeButton("Re-Prompt Request", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
})
.show();
}
return;
}
case cameraPerm: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the

} else { // permission denied,

}
return;
}
}
}


Sorry if this is a simple fix, I am fairly new to Android App Development.

Answer

Simple answer is "this" refers to the Button here. In order to pass the activity there are two ways:

  • LoginActivity.this [For sure]

  • getApplicationcontext() [In case to pass the application context]