Related
I have a class which checks the location permission and show the dialog if not granted and its working fine if I run it separately but when I try to use it in another class it gave me the exception
"Attempt to invoke virtual method
'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference"
This is my class :
public class LocSettingActivity extends AppCompatActivity {
private static final int REQUEST_CHECK_SETTINGS = 0x1;
private static GoogleApiClient mGoogleApiClient;
private static final int ACCESS_FINE_LOCATION_INTENT_ID = 3;
private static final String BROADCAST_ACTION = "android.location.PROVIDERS_CHANGED";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc_setting);
initGoogleAPIClient(this);//Init Google API Client
}
/* Initiate Google API Client */
private void initGoogleAPIClient(Context context) {
//Without Google API Client Auto Location Dialog will not work
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
/* Check Location Permission for Marshmallow Devices */
public void checkPermissions(Context context) {
initGoogleAPIClient(context);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(context,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
requestLocationPermission();
else
showSettingDialog();
} else
showSettingDialog();
}
/* Show Popup to access User Permission */
public void requestLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(LocSettingActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(LocSettingActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION_INTENT_ID);
} else {
ActivityCompat.requestPermissions(LocSettingActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION_INTENT_ID);
}
}
/* Show Location Access Dialog */
public void showSettingDialog() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);//Setting priotity of Location request to high
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);//5 sec Time interval for location update
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient to show dialog always when GPS is off
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(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.
// updateGPSStatus("GPS is Enabled in your device");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(LocSettingActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
// 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;
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case RESULT_OK:
Log.e("Settings", "Result OK");
// updateGPSStatus("GPS is Enabled in your device");
//startLocationUpdates();
break;
case RESULT_CANCELED:
Log.e("Settings", "Result Cancel");
// updateGPSStatus("GPS is Disabled in your device");
break;
}
break;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(gpsLocationReceiver, new IntentFilter(BROADCAST_ACTION));//Register broadcast receiver to check the status of GPS
checkPermissions(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
//Unregister receiver on destroy
if (gpsLocationReceiver != null)
unregisterReceiver(gpsLocationReceiver);
}
//Run on UI
public Runnable sendUpdatesToUI = new Runnable() {
public void run() {
showSettingDialog();
}
};
// Broadcast receiver to check status of GPS
private BroadcastReceiver gpsLocationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
//If Action is Location
if (intent.getAction().matches(BROADCAST_ACTION)) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//Check if GPS is turned ON or OFF
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.e("About GPS", "GPS is Enabled in your device");
// updateGPSStatus("GPS is Enabled in your device");
} else {
//If GPS turned OFF show Location Dialog
new Handler().postDelayed(sendUpdatesToUI, 10);
// showSettingDialog();
// updateGPSStatus("GPS is Disabled in your device");
checkPermissions(context);
Log.e("About GPS", "GPS is Disabled in your device");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
//Method to update GPS status text
private void updateGPSStatus(Context context,String status) {
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
/* On Request permission method to check the permisison is granted or not for Marshmallow+ Devices */
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
try {
switch (requestCode) {
case ACCESS_FINE_LOCATION_INTENT_ID: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//If permission granted show location dialog if APIClient is not null
if (mGoogleApiClient == null) {
initGoogleAPIClient(this);
showSettingDialog();
} else
showSettingDialog();
} else {
// updateGPSStatus("Location Permission denied.");
Toast.makeText(LocSettingActivity.this, "Location Permission denied.", Toast.LENGTH_SHORT).show();
simpleAlertGps();
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void simpleAlertGps() {
try {
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).create();
alertDialog.setTitle("");
alertDialog.setMessage("Your Gps Must Be On For Better Result");
alertDialog.setButton(android.app.AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
/*Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);*/
checkPermissions(LocSettingActivity.this);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(LocSettingActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
And here I'm getting it in other class
LocSettingActivity locSettingActivity = new LocSettingActivity();
public void onResume() {
super.onResume();
locSettingActivity.checkPermissions(this);
}
public void openTuckLocation(View view) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
in=new Intent(PagerMainActivity.this, MapsActivityLocation.class);
}
else {
locSettingActivity.checkPermissions(this);
return;
}
}
insted of
locSettingActivity.checkPermissions(this);
use
locSettingActivity.checkPermissions(getApplicationContext);
Or
locSettingActivity.checkPermissions(ActivityName.this);
as sometimes context can also give error
I've written an application which should take picture and record video and then show it on the screen. When trying it on phone the camera won't work but works in emulator.
When executing the app this is what exactly happens:
Every time I clicked on the button to open the camera, the app stopped and the error it display is Appname has stopped, Open app again
When I clicked on Open app again it return to normal state
I have granted the camera permission in my program
below is my code:
public class EventActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
public static final String KEY_MENU_TYPE = "menutype";
//public static final String KEY_PREF_USER_DETAILS = "prefUserDetails";
private static final String TAG = EventActivity.class.getSimpleName();
private static final String SERVER_IMAGE_PATH = "http://edo.com/imageupload/";
private static final String SERVER_PATH = "http://edo.com/";
String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private EditText event, eventDescription, name;
private TextView attachmentStatus;
private static final int TAKE_PICTURE = 1;
private static final int PERMISSION_ALL = 3;
private Uri capturedImageUri;
private Uri videoUri;
private String mediaFile;
private String videoFile;
private static final int MY_SOCKET_TIMEOUT_MS = 5000;
private String[] serverData;
private static final int REQUEST_VIDEO_CAPTURE = 300;
private boolean isImage;
private String locationResult;
String menutype = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
Intent intent = getIntent();
/* ActionBar mBar = getSupportActionBar();
if(mBar != null){
mBar.setDisplayHomeAsUpEnabled(true);
}*/
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = createLocationRequest();
Button photoVideoButton = (Button)findViewById(R.id.take_image_video);
photoVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showOptionDialog();
}
});
attachmentStatus = (TextView)findViewById(R.id.file_status);
event = (EditText)findViewById(R.id.enter_event);
eventDescription =(EditText)findViewById(R.id.enter_event_description);
name = (EditText)findViewById(R.id.name);
Button cancelUploadButton = (Button) findViewById(R.id.cancel_upload);
assert cancelUploadButton != null;
cancelUploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resetViewControls();
}
});
Button sendToServerButton = (Button) findViewById(R.id.send_to_server);
assert sendToServerButton != null;
sendToServerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String eventValue = event.getText().toString().trim();
String eventDescriptionValue = eventDescription.getText().toString();
String nameValue = name.getText().toString();
String locationValue = "";
if(TextUtils.isEmpty(eventValue) || TextUtils.isEmpty(eventDescriptionValue) || TextUtils.isEmpty(nameValue)){
Toast.makeText(EventActivity.this, getString(R.string.send_to_server_error), Toast.LENGTH_LONG).show();
return;
}
if(locationResult == null || locationResult.equals("")){
locationValue = "";
}else{
locationValue = locationResult;
}
if(TextUtils.isEmpty(mediaFile) && TextUtils.isEmpty(videoFile)){
Toast.makeText(EventActivity.this, "Please attach a photo or video", Toast.LENGTH_LONG).show();
return;
}
if(!TextUtils.isEmpty(mediaFile) && isImage){
// send the information to remote server
Bitmap storeBitmap = BitmapFactory.decodeFile(mediaFile);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(storeBitmap, 640, 420, true);
String imageBasedString = convertBitmapToBaseImageString(resizedBitmap);
serverData = new String[]{eventValue, eventDescriptionValue, nameValue, imageBasedString, locationValue};
sendCapturedImageToServer(serverData);
//move stored video to a new folder
String photoPath = getMovedFilePath(mediaFile, eventValue);
moveFileToNewDestination(mediaFile, photoPath);
}else if(!TextUtils.isEmpty(mediaFile) && !isImage){
//Store the video to your server
uploadVideoToServer(videoFile, eventValue, eventDescriptionValue, nameValue, locationValue);
//move stored video to a new folder
String photoPath = getMovedFilePath(videoFile, eventValue);
moveFileToNewDestination(videoFile, photoPath);
}else{
// Image or video is missing. Show message to user
Toast.makeText(EventActivity.this, getString(R.string.upload_image_or_video), Toast.LENGTH_LONG).show();
}
}
});
this.menutype = intent.getStringExtra(KEY_MENU_TYPE);
if (this.menutype == null) {
this.menutype = "";
}
}
public void goBack(View view) {
Intent intent;
if (this.menutype.equals("PRE")) {
intent = new Intent(this, PreElectionMenuActivity.class);
} else if (this.menutype.equals("ACC")) {
intent = new Intent(this, AccreditationMenuActivity.class);
} else if (this.menutype.equals("ELE")) {
intent = new Intent(this, VotingMenuActivity.class);
} else if (this.menutype.equals("INC")) {
intent = new Intent(this, IncidentMenuActivity.class);
} else {
intent = new Intent(this, HomeActivity.class);
}
startActivity(intent);
}
private String getMovedFilePath(String filePath, String eventName){
int indexPosition = filePath.lastIndexOf(".");
String fileExtension = filePath.substring(indexPosition, filePath.length());
String newFilename = eventName + fileExtension;
return getFileDestinationPath(newFilename);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == TAKE_PICTURE) {
capturedImageUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = "";
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
Log.d(TAG, "Capture image path" + mediaFile);
attachmentStatus.setText("Image file has been attached");
isImage = true;
}
}
if (requestCode == REQUEST_VIDEO_CAPTURE) {
videoUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else{
videoFile = getRealPathFromURIPath(videoUri, EventActivity.this);
Log.d(TAG, "Captured video path " + videoUri);
Log.d(TAG, "New path " + videoFile);
attachmentStatus.setText("Video file has been attached");
isImage = false;
}
}
}
}
private void resetViewControls(){
event.setText("");
eventDescription.setText("");
name.setText("");
attachmentStatus.setText(R.string.attached_file);
}
#Override
protected void onResume() {
super.onResume();
if(capturedImageUri != null){
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
}
}
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
private String convertBitmapToBaseImageString(Bitmap bitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
return Base64.encodeToString(byte_arr, 0);
}
private void sendCapturedImageToServer(String[] photoDetails){
Map<String, String> params = new HashMap<String,String>();
params.put("EVENT", photoDetails[0]);
params.put("EVENT_DESCRIPTION", photoDetails[1]);
params.put("NAME", photoDetails[2]);
params.put("CAPTURE_IMAGE", photoDetails[3]);
params.put("EVENT_LOCATION", photoDetails[4]);
GsonRequest<ServerObject> serverRequest = new GsonRequest<ServerObject>(
Request.Method.POST,
SERVER_IMAGE_PATH,
ServerObject.class,
params,
createRequestSuccessListener(),
createRequestErrorListener());
serverRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(EventActivity.this).addToRequestQueue(serverRequest);
}
private Response.Listener<ServerObject> createRequestSuccessListener() {
return new Response.Listener<ServerObject>() {
#Override
public void onResponse(ServerObject response) {
try {
Log.d(TAG, "Json Response " + response.getSuccess());
if(!TextUtils.isEmpty(response.getSuccess()) && response.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
};
};
}
private Response.ErrorListener createRequestErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
}
public static void getAddressFromLocation(final double lat, final double lon, final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(lat, lon, 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality() + ", " + address.getCountryName() ;
Log.d(TAG, "The converted Address " + result);
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to GeoCoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
#SuppressLint("HandlerLeak")
private class GeoCoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationResult = bundle.getString("address");
Log.d(TAG, "Location Result " + locationResult);
break;
default:
locationResult = null;
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
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();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.d(TAG, "Connection method has been called");
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
else{
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
getAddressFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), EventActivity.this, new GeoCoderHandler());
}
}
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_ALL: {
// If request is cancelled, the result arrays are empty.
if(grantResults[0] == PackageManager.PERMISSION_DENIED){
Toast.makeText(EventActivity.this, "Sorry!!!, you can't use this app without granting this permission", Toast.LENGTH_LONG).show();
finish();
}
if (grantResults[1] == PackageManager.PERMISSION_DENIED || grantResults[2] == PackageManager.PERMISSION_DENIED) {
// permission was denied, show alert to explain permission
showPermissionAlert();
}else{
//permission is granted. Get current location values
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
}
}
}
}
private void showPermissionAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permission_request_title);
builder.setMessage(R.string.app_permission_notice);
builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(EventActivity.this, R.string.permission_refused, Toast.LENGTH_LONG).show();
}
});
builder.show();
}
protected LocationRequest createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private boolean isLocationEnabled(){
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
return false;
}
return true;
}
private void showLocationAlert(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_enable));
dialog.setPositiveButton(getResources().getString(R.string.network_location), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
EventActivity.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private void moveFileToNewDestination(String fromPath, String toPath){
File fromFile = new File(fromPath);
File toFile = new File(toPath);
if(!toFile.exists()){
try {
toFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fromStream = null;
FileOutputStream toStream = null;
try {
fromStream = new FileInputStream(fromFile);
toStream = new FileOutputStream(toFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] sourceByte = new byte[1024];
int index;
try {
while((index = fromStream.read(sourceByte)) > 0){
if (toStream != null) {
toStream.write(sourceByte, 0, index);
}
}
Log.d(TAG, "Video successfully moved to a new location");
} catch (IOException e) {
e.printStackTrace();
}
}
private String getFileDestinationPath(String filename){
String filePathEnvironment = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
File directoryFolder = new File(filePathEnvironment + "/events/");
if(!directoryFolder.exists()){
directoryFolder.mkdir();
}
Log.d(TAG, "Full path " + filePathEnvironment + "/events/" + filename);
return filePathEnvironment + "/events/" + filename;
}
private void uploadVideoToServer(String pathToVideoFile, String eventName, String eventDescription, String eventCoverage, String eventLocation){
File videoFile = new File(pathToVideoFile);
RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
RequestBody event = RequestBody.create(MediaType.parse("text/plain"), eventName);
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), eventDescription);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), eventCoverage);
RequestBody location = RequestBody.create(MediaType.parse("text/plain"), eventLocation);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_PATH)
.addConverterFactory(GsonConverterFactory.create())
.build();
VideoInterface vInterface = retrofit.create(VideoInterface.class);
Call<ResultObject> serverCom = vInterface.uploadVideoToServer(vFile, event, description, name, location);
serverCom.enqueue(new Callback<ResultObject>() {
#Override
public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
ResultObject result = response.body();
if(!TextUtils.isEmpty(result.getSuccess()) && result.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResultObject> call, Throwable t) {
Log.d(TAG, "Error message " + t.getMessage());
}
});
}
private void showOptionDialog(){
final Dialog dialog = new Dialog(EventActivity.this);
dialog.setTitle("SELECT ACTION TO COMPLETE");
dialog.setContentView(R.layout.image_video_layout);
final TextView takePhoto = (TextView)dialog.findViewById(R.id.take_photo);
final TextView recordVideo = (TextView)dialog.findViewById(R.id.record_video);
dialog.show();
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Take a picture");
if(isLocationEnabled()){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
}else{
showLocationAlert();
}
dialog.dismiss();
}
});
recordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Record a video");
Intent videoCaptureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if(videoCaptureIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(videoCaptureIntent, REQUEST_VIDEO_CAPTURE);
}
dialog.dismiss();
}
});
}
private boolean gps_enabled;
private boolean network_enabled;
I have a main activity that displays login option, if the user clicked login with FB button, I will call fblogin();, and if the login success then I will do intent to open home activity.
right now, the home activity seems to open twice. (i can see it appear twice, stacked)
private void Fblogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends"));
LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("LoginActivity", response.toString());
Log.d("LoginActivity", object.toString());
String jsonresult = String.valueOf(object);
System.out.println("JSON Result" + jsonresult);
String str_firstname=null,str_id=null;
try {
str_firstname=object.getString("name");
str_id = object.getString("id");
String str_email = object.getString("email");
Intent home = new Intent(MainActivity.this , HomeActivity.class);
home.putExtra("name", str_firstname);
home.putExtra("URL", "https://graph.facebook.com/" + str_id + "/picture?width="+PROFILE_PIC_SIZE+"&height="+PROFILE_PIC_SIZE);
startActivity(home);
} catch (JSONException e) {
e.printStackTrace();
Log.d("xxxx","aa");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
in my main activity, i call this in my on create FacebookSdk.sdkInitialize(getApplicationContext());
, iI also check for initial login status `
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);}
but I think that initial check has nothing to do with it becauseI tried to delete it too but it still happening.`
and in my Home Activity, I have not write any facebook related codes yet.
EDIT : I PUT WHOLE CODE (MainActivity)
import ...
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static Boolean IsLoggedFB = false; //general state of fb logged
public static Boolean IsLoggedManual =false; //status boolean if logged in by email (manual)
public static Boolean IsLoggedGM = false; //general state of google gmail logged
String ID_HNBS; //IDhnbs created when first Registered
String Email;
TextView Fpassword;
Button Daftar;
EditText email, password;
Button LoginEmail;
LoginButton fb_button;
SignInButton gplus_button;
MainActivity myContext;
static String personName;
private boolean mIntentInProgress;
FragmentManager fragmentManager;
private CallbackManager callbackmanager;
//for G+
private GoogleSignInOptions gso;
private static final int PROFILE_PIC_SIZE = 30;
private GoogleApiClient mGoogleApiClient;
private ConnectionResult mConnectionResult;
private boolean mSignInClicked;
static final int RC_SIGN_IN = 0;
/* Is there a ConnectionResult resolution in progress? */
private boolean mIsResolving = false;
LinearLayout tv;
/* Should we automatically resolve ConnectionResults when possible? */
private boolean mShouldResolve = false;
public static final String MyPREFERENCES = "xpp";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
IsLoggedManual = sharedpreferences.getBoolean("IsLoggedManual", false); // get value of last login status
IsLoggedGM = sharedpreferences.getBoolean("IsloggedGM", false); // get value of last login GM
Daftar = (Button) findViewById(R.id.buttonDaftarEmail);
LoginEmail = (Button) findViewById(R.id.buttonLoginEmail);
fb_button = (LoginButton)findViewById(R.id.fblogin_button);
//Initializing google signin option
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
gplus_button = (SignInButton) findViewById(R.id.sign_in_button);
gplus_button.setSize(SignInButton.SIZE_STANDARD);
gplus_button.setScopes(gso.getScopeArray());
//Initializing google api client
mGoogleApiClient = new GoogleApiClient.Builder(this)
//.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
Daftar.setOnClickListener(this);
LoginEmail.setOnClickListener(this);
fb_button.setOnClickListener(this);
gplus_button.setOnClickListener(this);
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone())
{
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
}
Log.d("TAG", "ACCESS TOKEN STATUS" + AccessToken.getCurrentAccessToken() + " --- profile=" + Profile.getCurrentProfile());
//CHECK IF ALREADY LOGGED BY FB
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
} else if ( IsLoggedManual ) { //IF already LOGGED IN MANUAL (SHAREDPREF)
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.buttonDaftarEmail) {
Intent intent = new Intent(MainActivity.this, UserRegistration.class);
startActivity(intent);
} else if (v.getId() == R.id.buttonLoginEmail) {
Intent intent_signin = new Intent(MainActivity.this, LoginManual.class);
startActivity(intent_signin);
} else if (v.getId() == R.id.fblogin_button) {
Fblogin();
} else if (v.getId() == R.id.sign_in_button) //google sign in button
{
Intent intent_Gsignin = new Intent(MainActivity.this, GSignIn.class);
startActivity(intent_Gsignin);
}
}
private void onSignInClicked() {
// User clicked the sign-in button, so begin the sign-in process and automatically
// attempt to resolve any errors that occur.
mShouldResolve = true;
mGoogleApiClient.connect();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
private void Fblogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends"));
LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
Log.d("LoginActivity", response.toString());
Log.d("LoginActivity", object.toString());
String jsonresult = String.valueOf(object);
System.out.println("JSON Result" + jsonresult);
String str_firstname=null,str_id=null;
try {
str_firstname=object.getString("name");
str_id = object.getString("id");
String str_email = object.getString("email");
Intent home = new Intent(MainActivity.this , HomeActivity.class);
home.putExtra("name", str_firstname);
home.putExtra("URL", "https://graph.facebook.com/" + str_id + "/picture?width="+PROFILE_PIC_SIZE+"&height="+PROFILE_PIC_SIZE);
startActivity(home);
} catch (JSONException e) {
e.printStackTrace();
Log.d("xxxx","aa");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
//After the signing we are calling this function
private void handleSignInResult(GoogleSignInResult result) {
//If the login succeed
if (result.isSuccess()) {
//Getting google account
GoogleSignInAccount acct = result.getSignInAccount();
//tv= (LinearLayout) tv.findViewById(R.id.layoutfragmentlogin);
//tv.setVisibility(View.GONE); //hide include , so include now show nothing
Intent Home=new Intent(this,HomeActivity.class);
Home.putExtra("name",acct.getDisplayName());
Home.putExtra("email", acct.getEmail());
Home.putExtra("URL",acct.getPhotoUrl());
startActivity(Home);
} else {
//If login fails
Toast.makeText(this, "Login Failed on silentsign in", Toast.LENGTH_LONG).show();
}
}
//#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
Toast.makeText(myContext, "User is connected!", Toast.LENGTH_LONG).show();
}
//#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(callbackmanager!=null) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
Log.d("ani", "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
}
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further.
if (resultCode != this.RESULT_OK) {
mShouldResolve = false;
}
mIsResolving = false;
mGoogleApiClient.connect();
}
}
//#Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
//prefs.edit().putBoolean("Islogin",false).commit();
//DO Nothing..
/*
//==========Below is Trying to connect if googleUser not connected already =======
// Could not connect to Google Play Services. The user needs to select an account,
// grant permissions or resolve an error in order to sign in. Refer to the javadoc for
// ConnectionResult to see possible error codes.
Log.d("ani", "onConnectionFailed:" + connectionResult);
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e("ani", "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
}
}*/
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setTitle("HnBS Alert")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
EDIT 2 : MY HOMEACTIVITY CODE
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/**
* react to the user tapping/selecting an options menu item
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_menu_logout:
LoginManager.getInstance().logOut(); //LogOut from Facebook
//logout from login manual
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("IsLoggedManual",false).commit();
//if (mGoogleApiClient.isConnected()) {
// if (mGoogleApiClient.isConnected())
// Auth.GoogleSignInApi.signOut(mGoogleApiClient);
//}
Toast.makeText(this, "LoggedOut!", Toast.LENGTH_SHORT).show();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
After eight hours trial with some debugging, i couldn't find any trace of what is causing my HomeActivity fires twice. for people who stuck in any similar case, if you want and if its not breaking out your code, you can try to make your activity appear only one instance by adding this on your activity declaration in the manifest:
android:launchMode = "singleTask"
this has been the solution for me right now cause i don't want to waste any time longer as i need to move on to the next progress. thank you for any assistance.
You are calling the activity twice. That is
when consider if you are logged in facebook and google then the both the code get executed.
in onCreate you are calling
if (opr.isDone())
{
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result); //check method for going to home activity
}
and
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
} else if ( IsLoggedManual ) { //IF already LOGGED IN MANUAL (SHAREDPREF)
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
Use these conditions as one eg
opr.isDone() || AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null
Here you missed it, check out this code -
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
}
Above cached sign-in will start HomeActivity as well as if your AccessToken is not null(you're logged in with facebook) - again will start Home Activity
//CHECK IF ALREADY LOGGED BY FB
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
Solution:
You should put these conditions using else if ladder statements...
Hi I use Google login in my app it works fine but whenever I logging out I tried many solution for logging out but it doesn't works for me and if I further clicks on Google login button then app crashes.
Here is my code for Login
public class LoginActivity extends Activity implements AsyncInterface,
OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
EditText etLoginEmail, etLoginPassword;
Button btnLoginSubmit, btnLoginSignup;
TextView txtLoginForgotPass;
LoginResponseMain loginResponseMain;
/* For Google */
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
// Google Sign In Button
btnSignIn.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if (AppMethod.getBooleanPreference(LoginActivity.this, AppConstant.PREF_FIRST_LOGIN)) {
//startActivity(new Intent(LoginActivity.this, HomePage.class));
} else {
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
public void init() {
loginResponseMain = new LoginResponseMain();
btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);
}
#Override
public void onWSResponse(String json, String WSType) {
if (WSType == AppConstant.WS_LOGIN_G) {
try {
Log.e("Json", json);
JSONObject jobj = new JSONObject(json);
boolean error = jobj.getBoolean("error");
if (!error) {
JSONArray jsonArray = jobj.getJSONArray("user");
JSONObject jobjUser = jsonArray.getJSONObject(0);
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_FACEBOOK_ID, jobjUser.getString("facebook_id"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_GOOGLE_ID, jobjUser.getString("google_plus_id"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_EMAIL, jobjUser.getString("email"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_FNAME, jobjUser.getString("first_name"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_LNAME, jobjUser.getString("last_name"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_UPDATED_AT, jobjUser.getString("updated_at"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_CREATED_AT, jobjUser.getString("created_at"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_ID, String.valueOf(jobjUser.getInt("id")));
Intent i = new Intent(LoginActivity.this, TermsForUseActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(LoginActivity.this, AppConstant.SOMETHING_WRONG_TRY_AGAIN, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
getProfileInformation();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
// Login Button Click
case R.id.sign_in_button:
signInWithGplus();
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result2 = googleAPI.isGooglePlayServicesAvailable(this);
if (result2 != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result2)) {
googleAPI.getErrorDialog(this, result2, 0).show();
}
}
return;
}
if (!mIntentInProgress) {
mConnectionResult = connectionResult; // Store the ConnectionResult for later usage
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to resolve all errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
/* Fetching user's information name, email, profile pic */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
String url = AppConstant.LOGIN_WITH_G;
// WS for google login data submit.
if (AppMethod.isNetworkConnected(LoginActivity.this)) {
String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
String device_token = AppMethod.registerForGCM(LoginActivity.this);
Uri.Builder values = new Uri.Builder()
.appendQueryParameter("first_name", personName)
.appendQueryParameter("email", email)
.appendQueryParameter("udid", android_id)
.appendQueryParameter("login_type", "0")
.appendQueryParameter("device_token", device_token)
.appendQueryParameter("google_plus_id", currentPerson.getId());
WsHttpPostWithNamePair wsHttpPost = new WsHttpPostWithNamePair(LoginActivity.this, AppConstant.WS_LOGIN_G, values);
wsHttpPost.execute(url);
} else {
Toast.makeText(LoginActivity.this, AppConstant.NO_INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}
Now i need to signout from another activity use this code
For Logging out
public class HomePage extends TabActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
ResultCallback<People.LoadPeopleResult> {
DrawerLayout dLayout;
LinearLayout right_layout;
Button btnViewProfile, btnLogout;
//Google
GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private ConnectionResult mConnectionResult;
private static final int RC_SIGN_IN = 0;
private boolean mSignInClicked;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.home_page);
llHomePageMain = (LinearLayout) findViewById(R.id.llHomePageMain);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
mGoogleApiClient.connect();
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
right_layout = (LinearLayout) findViewById(R.id.right_layout);
btnViewProfile = (Button) findViewById(R.id.btnViewProfile);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnViewProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Right Layout", "Profile");
dLayout.closeDrawer(Gravity.END);
Intent i = new Intent(HomePage.this, ProfileActivity.class);
startActivity(i);
}
});
btnLogout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AppMethod.clearApplicationData(HomePage.this);
googlePlusLogout();
loginSessionClear();
}
}
});
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
}
private void resolveSignInError() {
if (mConnectionResult != null)
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
private void googlePlusLogout() {
if (mGoogleApiClient != null)
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result2 = googleAPI.isGooglePlayServicesAvailable(this);
if (result2 != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result2)) {
googleAPI.getErrorDialog(this, result2, 0).show();
}
}
return;
}
if (!mIntentInProgress) {
mConnectionResult = connectionResult;
if (mSignInClicked) {
resolveSignInError();
}
}
}
#Override
public void onBackPressed() {
dLayout.closeDrawers();
super.onBackPressed();
}
public void loginSessionClear() {
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_EMAIL, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_FNAME, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_LNAME, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_UDID, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_DEVICE_TOKEN, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_UPDATED_AT, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_CREATED_AT, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_GOOGLE_ID, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_ID, String.valueOf(""));
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onResult(People.LoadPeopleResult loadPeopleResult) {
}
}
This method doesnt work for me.
Even if i clear preference and try for new login with google then app crashes.
Logcat Error
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.common.ConnectionResult.hasResolution()' on a null object reference
Check null first
private void resolveSignInError() {
if (mConnectionResult != null)
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
and call bellow method for Logout
private void googlePlusLogout() {
if (mGoogleApiClient != null)
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
Am implementing google sign in my android application,in that i can log in using the google sign in after the success log in ,i want redirect from login page to my homepageactvity.But from the Home page activity i can log out (disconnect Google api client),when clicking the log out button again the Homepageactvity is coming..pls help me to figure this issue. My Login actvity is below
public class LoginActivityGoogle extends Activity implements OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Google client to communicate with Google
private GoogleApiClient mGoogleApiClient;
private String TAG = "Login";
private boolean mIntentInProgress;
private boolean signedInUser;
private ConnectionResult mConnectionResult;
private SignInButton signinButton;
private ImageView image;
private TextView username, emailLabel;
private LinearLayout profileFrame, signinFrame;
SessionManager session;
private boolean mSignInClicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_google);
signinButton = (SignInButton) findViewById(R.id.signin);
signinButton.setOnClickListener(this);
image = (ImageView) findViewById(R.id.image);
username = (TextView) findViewById(R.id.username);
emailLabel = (TextView) findViewById(R.id.email);
profileFrame = (LinearLayout) findViewById(R.id.profileFrame);
signinFrame = (LinearLayout) findViewById(R.id.signinFrame);
session = new SessionManager(getApplicationContext());
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.addScope(new Scope(Scopes.EMAIL))
.build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
if (!mIntentInProgress) {
// store mConnectionResult
mConnectionResult = result;
if (signedInUser) {
resolveSignInError();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further.
if (resultCode != RESULT_OK) {
signedInUser = false;
}
signedInUser = false;
mGoogleApiClient.connect();
}
}
#Override
public void onConnected(Bundle arg0) {
signedInUser = false;
Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();
// To launch from gere to homwpageactivity
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Intent in = new Intent(getApplicationContext(), HomePageActivity.class);
in.putExtra("username",personName);
in.putExtra("email",email);
in.putExtra("profile_pic",personPhotoUrl);
startActivity(in);
getProfileInformation();
}
private void updateProfile(boolean isSignedIn) {
if (isSignedIn) {
signinFrame.setVisibility(View.GONE);
// profileFrame.setVisibility(View.VISIBLE);
} else {
signinFrame.setVisibility(View.VISIBLE);
//profileFrame.setVisibility(View.GONE);
}
}
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
updateProfile(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
updateProfile(false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.signin:
googlePlusLogin();
break;
}
}
public void signIn(View v) {
googlePlusLogin();
}
private void googlePlusLogin() {
if (!mGoogleApiClient.isConnecting()) {
signedInUser = true;
resolveSignInError();
}
}
private void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateProfile(false);
}
}
// download Google Account profile image, to complete profile
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView downloadedImage;
public LoadProfileImage(ImageView image) {
this.downloadedImage = image;
}
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap icon = null;
try {
InputStream in = new java.net.URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return icon;
}
protected void onPostExecute(Bitmap result) {
downloadedImage.setImageBitmap(result);
}
}
And My homepageactvity is
public class HomePageActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener,
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener
{
private SharedPreferences preferences;
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cd = new ConnectionDetector(this);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header=navigationView.getHeaderView(0);
TextView username=(TextView) header.findViewById(R.id.username);
TextView user_email=(TextView) header.findViewById(R.id.email);
ImageView profileImage=(ImageView) header.findViewById(R.id.imageView) ;
String user_name= getIntent().getStringExtra("username");
String user_gmail= getIntent().getStringExtra("email");
String profile_pic=getIntent().getStringExtra("profile_pic");
username.setText(user_gmail);
user_email.setText(user_name);
CardView card_attendance = (CardView) findViewById(R.id.card_attendance);
CardView card_assignment = (CardView) findViewById(R.id.card_assignment);
CardView card_circular = (CardView) findViewById(R.id.card_circular);
CardView card_communication = (CardView) findViewById(R.id.card_communication);
CardView card_Fee = (CardView) findViewById(R.id.card_Fee);
CardView card_Library = (CardView) findViewById(R.id.card_Library);
CardView card_Result = (CardView) findViewById(R.id.card_Result);
CardView card_StudyMat = (CardView) findViewById(R.id.card_StudyMat);
card_attendance.setOnClickListener(this);
card_assignment.setOnClickListener(this);
card_circular.setOnClickListener(this);
card_communication.setOnClickListener(this);
card_Fee.setOnClickListener(this);
card_Library.setOnClickListener(this);
card_Result.setOnClickListener(this);
card_StudyMat.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.addScope(new Scope(Scopes.EMAIL))
.build();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_change_pass) {
Intent intent = new Intent(HomePageActivity.this, ChangePasswordActivity.class);
startActivity(intent);
} else if (id == R.id.nav_logout) {
googlePlusLogout();
}
else if (id == R.id.nav_faq) {
Intent intent = new Intent(HomePageActivity.this, FAQActivity.class);
startActivity(intent);
} else if (id == R.id.nav_about) {
PopupAbout();
} else if (id == R.id.nav_share) {
shareApp();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.card_attendance:
Intent intent = new Intent(HomePageActivity.this, AttendanceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.card_assignment:
Intent intent2 = new Intent(HomePageActivity.this, AssignmentActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent2);
break;
case R.id.card_StudyMat:
Intent intent3 = new Intent(HomePageActivity.this, StudyMaterialListActivity.class);
intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent3);
break;
case R.id.card_Library:
Intent intent4 = new Intent(HomePageActivity.this, LibraryActivity.class);
intent4.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent4);
break;
case R.id.card_Result:
Intent intent5 = new Intent(HomePageActivity.this, ResultActivity.class);
intent5.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent5);
break;
case R.id.card_communication:
Intent intent6 = new Intent(HomePageActivity.this, CommunicationActivity.class);
intent6.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent6);
break;
case R.id.card_Fee:
Intent intent7=new Intent(HomePageActivity.this,FeeActivity.class);
intent7.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent7);
break;
case R.id.card_circular:
Intent intent8=new Intent(HomePageActivity.this,CircularListActivity.class);
intent8.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent8);
break;
default:
break;
}
}
private void shareApp() {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Checkout The NI Model School App for Android");
String sAux = "\nHi, I am using The NI Model School Android app to track my child's activities in school.\n";
String sAux1 = sAux + "Why don't you check it out on your Android phone.\n";
String sAux2 = sAux1 + "market://details?id="
+ HomePageActivity.this.getPackageName() + "\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux2);
startActivity(Intent.createChooser(i, "choose one"));
} catch (Exception e) {
e.printStackTrace();
}
}
private void PopupAbout() {
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(
HomePageActivity.this);
alertDialogBuilder1.setTitle(R.string.app_name);
LayoutInflater li = LayoutInflater.from(HomePageActivity.this);
final View pView = li.inflate(R.layout.alert_about, null);
alertDialogBuilder1.setView(pView);
alertDialogBuilder1.setIcon(R.mipmap.ic_launcher);
alertDialogBuilder1.setCancelable(true);
try {
PackageInfo pInfo = HomePageActivity.this.getPackageManager()
.getPackageInfo(HomePageActivity.this.getPackageName(), 0);
String version = pInfo.versionName;
alertDialogBuilder1.setMessage("Version: " + version);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
alertDialogBuilder1.setPositiveButton("Rate",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
Uri uri = Uri.parse("market://details?id="
+ HomePageActivity.this.getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY
| Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Toast.makeText(HomePageActivity.this,
"Play Store unavailable..",
Toast.LENGTH_LONG).show();
}
}
});
AlertDialog alertDialog = alertDialogBuilder1.create();
alertDialog.show();
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
} private void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
Intent intent = new Intent(HomePageActivity.this, LoginActivityGoogle.class);
startActivity(intent);
}
}
remove the selected line in image from your code
I resolved the above issue,actually the app got crashr=ed because i didn't connect google client in to my Homepageactvity.So once i coonected the google client in to my Homepageactvity,then i can log out from my app.
First i intailthe below codes in to my On create method
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
After that i called the method for googlesignout.Its working fine now