This is my app so far:
MapsActivity:
public class MapsActivity extends FragmentActivity implements GoogleMap.OnMarkerDragListener, OnMapReadyCallback, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnMapLoadedCallback {
private GoogleMap mMap;
private HashMap<LatLng, CustomMarker> list;
public static String TAG = MapsActivity.class.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
list = new HashMap<>();
Log.e(TAG, "onCreate()");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMarkerClickListener(this);
mMap.setOnMapLoadedCallback(this);
mMap.setOnMapLongClickListener(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMarkerDragListener(this);
Log.e(TAG, "onMapReady");
}
#Override
public void onMapLoaded() {
retrieveMarkersFromDB();
Log.e(TAG, "onMapLoaded");
Toast.makeText(MapsActivity.this, "Touch and hold to create a marker", Toast.LENGTH_SHORT).show();
}
private void retrieveMarkersFromDB() {
new GetMarkers().execute();
}
#Override
public void onMapLongClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
CustomMarker customMarker = getMarkerAddress(latLng);
addMarkerToList(customMarker,latLng);
Toast.makeText(MapsActivity.this, "Marker Added", Toast.LENGTH_SHORT).show();
}
private void addMarkerToList(CustomMarker customMarker, LatLng latLng) {
list.put(latLng, customMarker);
}
private CustomMarker getMarkerAddress(LatLng latLng) {
CustomMarker customMarker = null;
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> allAddresses = geocoder.getFromLocation(latLng.latitude,latLng.longitude,2);
Address oneAddress = allAddresses.get(0);
try{
if(!oneAddress.getLocality().equals("null")||!oneAddress.getLocality().isEmpty()){
customMarker = new CustomMarker(oneAddress.getAddressLine(0)+", "+oneAddress.getLocality(),oneAddress.getCountryName(),"","");
}
}catch (NullPointerException e){
customMarker = new CustomMarker(oneAddress.getAddressLine(0),oneAddress.getCountryName(),"","");
}
} catch (IOException e) {
e.printStackTrace();
}catch (IndexOutOfBoundsException er){
customMarker = new CustomMarker("N/A","N/A","","");
}
return customMarker;
}
#Override
public boolean onMarkerClick(Marker marker) {
Intent intent = new Intent(this,com.example.fixxxer.mapapp.MarkerScreen.class);
CustomMarker customMarker = list.get(new LatLng(marker.getPosition().latitude,marker.getPosition().longitude));
intent.putExtra("addressLine",customMarker.getAddressLine());
intent.putExtra("countryName",customMarker.getCountryName());
intent.putExtra("imageURL",customMarker.getImageURL());
intent.putExtra("comment",customMarker.getComment());
intent.putExtra("lat",marker.getPosition().latitude);
intent.putExtra("lng",marker.getPosition().longitude);
startActivityForResult(intent,1);
return true;
}
#Override
protected void onDestroy() {
new DatabaseHelper(this,null,null,1).addMarkers(list);
super.onDestroy();
}
#Override
public void onMarkerDragStart(Marker marker) {
marker.remove();
list.remove(marker.getPosition());
Toast.makeText(MapsActivity.this, "Marker removed", Toast.LENGTH_SHORT).show();
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
public class GetMarkers extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
Log.e(TAG,"background task started");
list=new DatabaseHelper(MapsActivity.this,null,null,1).getallmarkers();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.e("onPostExecute","background task ready");
Log.e(TAG,String.valueOf(list.size()));
if (!list.isEmpty()){
for (LatLng position: list.keySet() ) {
mMap.addMarker(new MarkerOptions().position(position).draggable(true));
}
}
super.onPostExecute(aVoid);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("Main", "onActivityResult()");
if (requestCode == 1) {
if (resultCode == MarkerScreen.RESULT_COMMENT_ONLY) {
String comment = data.getStringExtra("Comment");
String[]split = data.getStringExtra("Index").split(",");
list.get(new LatLng(Double.valueOf(split[0]),Double.valueOf(split[1]))).setComment(comment);
}else if (resultCode == MarkerScreen.RESULT_IMAGE_ONLY) {
String imageURI = data.getStringExtra("Image");
String[]split = data.getStringExtra("Index").split(",");
list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setImageURL(imageURI);
} else if (resultCode == MarkerScreen.RESULT_BOTH) {
String comment = data.getStringExtra("Comment");
String imageURI = data.getStringExtra("Image");
String[]split = data.getStringExtra("Index").split(",");
list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setComment(comment);
list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setImageURL(imageURI);
} else {
Log.e("Main", "Result - no change");
}
}
}
Marker Screen class(Activity)
public class MarkerScreen extends AppCompatActivity {
private static final int REQUEST_TAKE_PHOTO = 1;
private ImageView imageView;
private TextView addressView;
private TextView countryView;
private TextView latlngView;
private EditText commentView;
private Button saveButton;
private Button deleteButton;
private String addressFromIntent;
private String countryFromIntent;
private String commentFromIntent;
private double latFromIntent;
private double lngFromIntent;
private String photoPath;
private String newPhotoPath;
private int imageModified = 0;
private int commentModified = 0;
static final int RESULT_NONE = 0;
static final int RESULT_BOTH = 1;
static final int RESULT_COMMENT_ONLY = 2;
static final int RESULT_IMAGE_ONLY = 3;
static final int RESULT_DELETE=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_screen);
//Initialising Views
addressView=(TextView)findViewById(R.id.textView);
countryView=(TextView)findViewById(R.id.textView2);
latlngView=(TextView)findViewById(R.id.textView3);
saveButton=(Button)findViewById(R.id.button);
saveButton.setText("Save");
imageView=(ImageView)findViewById(R.id.imageView);
commentView=(EditText)findViewById(R.id.editText);
//Getting intent information
addressFromIntent=getIntent().getStringExtra("addressLine");
countryFromIntent=getIntent().getStringExtra("countryName");
commentFromIntent=getIntent().getStringExtra("comment");
photoPath=getIntent().getStringExtra("imageURL");
latFromIntent=getIntent().getDoubleExtra("lat",0);
lngFromIntent=getIntent().getDoubleExtra("lng",0);
//Setting textFields
addressView.setText(addressFromIntent);
countryView.setText(countryFromIntent);
final String latlngTextField=String.valueOf(latFromIntent)+", "+String.valueOf(lngFromIntent);
latlngView.setText(latlngTextField);
if (photoPath.equals("")){
imageView.setImageResource(R.drawable.image);
} else {
imageView.setImageURI(Uri.parse(photoPath));
}
commentView.setText(commentFromIntent);
commentView.setHint("Enter comment here...");
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
Toast.makeText(MarkerScreen.this, photoPath, Toast.LENGTH_SHORT).show();
}
});
commentView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
commentModified++;
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
if (imageModified == 0 && commentModified == 0) {
setResult(RESULT_NONE);
Log.e("MarkerActivity", "intentResult: RESULT_NONE");
finish();
} else if (imageModified > 0 && commentModified == 0) {
intent.putExtra("Image", newPhotoPath);
intent.putExtra("Index", latlngView.getText());
Log.e("MarkerActivity", "intentResult: RESULT_IMAGE ONLY");
setResult(RESULT_IMAGE_ONLY, intent);
finish();
} else if (imageModified == 0 && commentModified > 0) {
intent.putExtra("Comment", commentView.getText().toString());
intent.putExtra("Index", latlngView.getText());
setResult(RESULT_COMMENT_ONLY, intent);
Log.e("MarkerActivity", "intentResult: RESULT_COMMENT ONLY");
finish();
} else if (imageModified > 0 && commentModified > 0) {
intent.putExtra("Comment", commentView.getText().toString());
intent.putExtra("Image", newPhotoPath);
intent.putExtra("Index", latlngView.getText());
setResult(RESULT_BOTH, intent);
Log.e("MarkerActivity", "intentResult: RESULT_BOTH");
finish();
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
Log.e("markerActivity","back button pressed");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override public void onBackPressed(){
this.finish();
Log.e("markerActivity"," hardware back button pressed");
}
private File createImageFile() throws IOException {
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES+ "/MapApp/" + addressFromIntent);
if (!storageDir.exists()){
File wallpaperDirectory = new File(storageDir.getPath());
boolean photoStatus =wallpaperDirectory.mkdirs();
}
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
newPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri uri = Uri.parse(newPhotoPath);
imageView.setImageURI(uri);
imageModified++;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("photopath",newPhotoPath);
outState.putString("comment",commentView.getText().toString());
outState.putString("addressView",addressView.getText().toString());
outState.putString("countryView",countryView.getText().toString());
outState.putString("latlngView",latlngView.getText().toString());
outState.putInt("imageModified", imageModified);
outState.putInt("commentModified", commentModified);
Log.e("Saved","saved info");
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
photoPath=savedInstanceState.getString("photopath");
commentView.setText(savedInstanceState.getString("comment"));
addressView.setText(savedInstanceState.getString("addressView"));
countryView.setText(savedInstanceState.getString("countryView"));
latlngView.setText(savedInstanceState.getString("latlngView"));
imageModified=savedInstanceState.getInt("imageModified");
commentModified=savedInstanceState.getInt("commentModified");
Log.e("Restored","restored info");
}
activity_maps.xml
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.fixxxer.mapapp.MapsActivity">
<include layout="#layout/map_layout"/>
map_layout.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fixxxer.mapapp.MapsActivity" />
I want to replace starting MarkerScreen Activity with a similar Fragment. How to do this? What i've tried so far is to create a new BlankFragment via menu and set this in the onMarkerClick() method:
getFragmentManager()
.beginTransaction()
.replace(R.id.layout.map_layout, BlankFragment.newInstance())
.addToBackStack(null) // enables back key
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) // if you need transition
.commit();
But i get an no view found error. Is there an easy way to do all this? I'm quite a noob with fragments.
Use R.id.map in place of containerViewId in your replace fragment code like this
getFragmentManager()
.beginTransaction()
.replace(R.id.map, BlankFragment.newInstance())
.addToBackStack(null) // enables back key
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) // if you need transition
.commit();
Related
I can play any mp4 video using Exoplayer in my Android project. But the video uploaded to Google drive or blogspot site is not playing in Exoplayer. Is there any solution to this problem?
Here's the code I'm using:
public class MagicalExoplayer extends AppCompatActivity {
private AndExoPlayerView andExoPlayerView;
// private String TEST_URL_MP4 = "https://www.w3schools.com/html/mov_bbb.mp4";
//Blogger site video link but can't play this video
private String TEST_URL_MP4 = "https://bestmedicalpdf.blogspot.com/2020/05/mrcpwiz-free-mrcp-mcqs-mrcpwiz-your.html";
private String TEST_URL_HLS = "https://content.jwplatform.com/manifests/yp34SRmf.m3u8";
private String TEST_URL_MP3 = "https://host2.rj-mw1.com/media/podcast/mp3-192/Tehranto-41.mp3";
private int req_code = 129;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_magical_exoplayer);
andExoPlayerView = findViewById(R.id.andExoPlayerView);
findViewById(R.id.local).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectLocaleVideo();
}
});
findViewById(R.id.mp4).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadMP4ServerSide();
}
});
findViewById(R.id.hls).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadHls();
}
});
findViewById(R.id.mp3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadMp3();
}
});
}
private void loadMp3() {
andExoPlayerView.setSource(TEST_URL_MP3);
}
private void loadHls() {
andExoPlayerView.setSource(TEST_URL_HLS);
}
private void loadMP4ServerSide() {
andExoPlayerView.setSource(TEST_URL_MP4);
}
private void selectLocaleVideo() {
if (PublicFunctions.checkAccessStoragePermission(this)) {
Intent intent = new Intent();
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), req_code);
}
}
private void loadMP4Locale(String filePath) {
andExoPlayerView.setSource(filePath);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == req_code && resultCode == RESULT_OK) {
Uri finalVideoUri = data.getData();
String filePath = null;
try {
filePath = PathUtil.getPath(this, finalVideoUri);
loadMP4Locale(filePath);
} catch (URISyntaxException e) {
e.printStackTrace();
Toast.makeText(this, "Failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
private class ChromeClient extends WebChromeClient {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
protected FrameLayout mFullscreenContainer;
private int mOriginalOrientation;
private int mOriginalSystemUiVisibility;
ChromeClient() {
}
public Bitmap getDefaultVideoPoster() {
if (mCustomView == null) {
return null;
}
return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
}
public void onHideCustomView() {
((FrameLayout) getWindow().getDecorView()).removeView(this.mCustomView);
this.mCustomView = null;
getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
setRequestedOrientation(this.mOriginalOrientation);
this.mCustomViewCallback.onCustomViewHidden();
this.mCustomViewCallback = null;
}
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback) {
if (this.mCustomView != null) {
onHideCustomView();
return;
}
this.mCustomView = paramView;
this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
this.mOriginalOrientation = getRequestedOrientation();
this.mCustomViewCallback = paramCustomViewCallback;
((FrameLayout) getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
}
But any other mp4 video easily play.
https://bestmedicalpdf.blogspot.com/2020/05/mrcpwiz-free-mrcp-mcqs-mrcpwiz-your.html is a webpage and not the url to a video or audio file.
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 am trying to take a screenshot of google maps android and pass the image to a new activity but I keep getting this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.snapshot(com.google.android.gms.maps.GoogleMap$SnapshotReadyCallback)' on a null object reference
at com.jjoey.transportr.activities.BookRideActivity.initViews(BookRideActivity.java:480)
at com.jjoey.transportr.activities.BookRideActivity.onCreate(BookRideActivity.java:101)
at android.app.Activity.performCreate(Activity.java:5990)
I have tried writing the code in onResume and onMapReady methods of activity but still error persists.
Here's my code for activity:
public class BookRideActivity extends FirebaseUtils implements OnMapReadyCallback {
private static final String TAG = BookRideActivity.class.getSimpleName();
private static final int LOC_REQ_CODE = 2035;
private Toolbar toolbar;
private ImageView backIV;
private SharedPrefsHelper prefsHelper;
private SupportMapFragment mapFragment;
private GoogleMap mGmap;
private LocationRequest locationRequest;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback callback;
private Location mCurrLocation;
private Marker marker;
private Bitmap locnImg;
private EditText startET, dropET, et_coupon, et_payment_options, et_rider;
private TextView estimatedPUTimeTV;
private Button bookNowBtn, cancelBtn;
private double lat = 0f, lon = 0f;
private String start = null, drop = null;
private boolean isValid = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_ride);
initViews();
start = getIntent().getStringExtra("start_addr");
drop = getIntent().getStringExtra("dest_addr");
if (start != null && drop != null) {
startET.setText(start);
dropET.setText(drop);
} else {
clearInputs();
}
setSupportActionBar(toolbar);
prefsHelper = new SharedPrefsHelper(this);
prefsHelper.setLoggedOut(false);
backIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(BookRideActivity.this, ClientHomeActivity.class));
}
});
et_coupon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Coupon Clicked");
showCouponDialog();
}
});
checkPerms();
handlePlacesInput();
}
private void checkPerms() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
} else {
startLocationListener();
}
}
private void reqPerms() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOC_REQ_CODE);
}
private void startLocationListener() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setInterval(UPDATE_INTERVAL);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
LocationSettingsRequest settingsRequest = builder.build();
SettingsClient client = LocationServices.getSettingsClient(this);
client.checkLocationSettings(settingsRequest);
drawLocationOnMap();
}
private void drawLocationOnMap() {
callback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrLocation = locationResult.getLastLocation();
if (marker != null && mCurrLocation != null) {
marker.remove();
lat = mCurrLocation.getLatitude();
lon = mCurrLocation.getLongitude();
}
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lon));
options.title("You");
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_marker));
marker = mGmap.addMarker(options);
mGmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 18.0f));
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.myLooper());
//mGmap.setMyLocationEnabled(true);
} else {
reqPerms();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case LOC_REQ_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationListener();
}
break;
}
}
private void handlePlacesInput() {
startET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startET.setText("");
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(BookRideActivity.this);
startActivityForResult(intent, START_PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
Log.d(TAG, "Play-Services-Repairable Err:\t" + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d(TAG, "Play-Services-Unavailable Err:\t" + e.getMessage());
}
}
});
dropET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dropET.setText("");
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(BookRideActivity.this);
startActivityForResult(intent, DROP_PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
Log.d(TAG, "Play-Services-Repairable Err:\t" + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d(TAG, "Play-Services-Unavailable Err:\t" + e.getMessage());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case START_PLACE_AUTOCOMPLETE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
String txt = place.getAddress().toString();
startET.setText(txt);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
Log.d(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
}
break;
case DROP_PLACE_AUTOCOMPLETE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
String txt = place.getAddress().toString();
dropET.setText(txt);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
Log.d(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
}
break;
}
}
private boolean validate() {
String startAddr = startET.getText().toString();
String destAddr = dropET.getText().toString();
if (TextUtils.isEmpty(startAddr) && TextUtils.isEmpty(destAddr)) {
isValid = false;
} else if (!TextUtils.isEmpty(startAddr) && !TextUtils.isEmpty(destAddr)) {
isValid = true;
}
return true;
}
private void clearInputs() {
startET.setText("");
dropET.setText("");
}
private void initViews() {
toolbar = findViewById(R.id.toolbar);
backIV = findViewById(R.id.backIV);
dropET = findViewById(R.id.dropLocationET);
startET = findViewById(R.id.startLocationET);
bookNowBtn = findViewById(R.id.bookNowBtn);
cancelBtn = findViewById(R.id.cancelBtn);
GoogleMap.SnapshotReadyCallback snapshotReadyCallback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
locnImg = bitmap;
Log.d(TAG, "Snapshot Ready");
}
};
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
mGmap.snapshot(snapshotReadyCallback);
Log.d(TAG, "Snapshot Taken");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
View mapBtn = (View) ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mapBtn.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.setMargins(0, 0, 30, 30);
}
}
I have tried following this tutorial but it doesn't work in my case.The error occurs when I try mGmap.snapshot(snapshotReadyCallback);. I have initialized the map in the lines above and gotten the location using FusedLocationProviderClient api.
Can anyone help me understand why it's throwing this error? Thanks
After having successfully followed the guide Accessing Google APIs, I am trying to move all the Google+ related code from my MainActivity to a separate custom GoogleFragment.
However I am stuck at the very last spot - in my custom Fragment, I don't know how to access the mResolvingError field after the DialogFragment has been dismissed:
public class GoogleFragment extends Fragment
implements GoogleApiClient.OnConnectionFailedListener {
private boolean mResolvingError = false; // HOW TO ACCESS?
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (connectionResult.hasResolution()) {
try {
mResolvingError = true;
connectionResult.startResolutionForResult(getActivity(), REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(connectionResult.getErrorCode());
mResolvingError = true;
}
}
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(ARGS_DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getActivity().getSupportFragmentManager(), TAG_DIALOG_ERROR);
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(ARGS_DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(),
errorCode,
REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
mResolvingError = false; // DOES NOT COMPILE
}
}
}
What should I do here please?
If I make the ErrorDialogFragment non-static I get compile error:
This fragment inner class should be static
(GoogleFragment.ErrorDialogFragment)
If I keep it static - I can not access the variable either.
I am thinking of 2 workarounds for my problem:
Using LocalBroadcastManager to send a custom Intent from ErrorDialogFragment to GoogleFragment
Define a custom method in GoogleFragment and access it through getSupportFragmentManager().findFragmentByTag()
But is there maybe a simpler solution?
UPDATE:
I've changed the mResolvingError field to public and have tried this code:
#Override
public void onDismiss(DialogInterface dialog) {
GoogleFragment f = (GoogleFragment) getActivity().getSupportFragmentManager().findFragmentByTag(GoogleFragment.TAG);
if (f != null && f.isVisible()) {
f.mResolvingError = false;
}
}
but I am not sure how to test this properly and if f.isVisible() is needed there...
UPDATE 2:
Maybe I should somehow use DialogInterface.OnDismissListener with GoogleApiAvailability.getInstance().getErrorDialog in my code?
BladeCoder's comments have been very insightful, thanks.
However I have realized, that all the hassle with saving and restoring mResolvingError is unnecessary, because startResolutionForResult() starts a separate Activity anyway and obstructs my app - so it doesn't really matter if I rotate device or not.
Here is my final code to initiate GCM and fetch Google+ user data -
MainActivity.java:
public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1972;
public static final int REQUEST_GOOGLE_PLUS_LOGIN = 2015;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null)
startRegistrationService();
}
private void startRegistrationService() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int code = api.isGooglePlayServicesAvailable(this);
if (code == ConnectionResult.SUCCESS) {
onActivityResult(REQUEST_GOOGLE_PLAY_SERVICES, Activity.RESULT_OK, null);
} else if (api.isUserResolvableError(code) &&
api.showErrorDialogFragment(this, code, REQUEST_GOOGLE_PLAY_SERVICES)) {
// wait for onActivityResult call (see below)
} else {
String str = GoogleApiAvailability.getInstance().getErrorString(code);
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
Intent i = new Intent(this, RegistrationService.class);
startService(i); // OK, init GCM
}
break;
case REQUEST_GOOGLE_PLUS_LOGIN:
if (resultCode == Activity.RESULT_OK) {
GoogleFragment f = (GoogleFragment) getSupportFragmentManager().
findFragmentByTag(GoogleFragment.TAG);
if (f != null && f.isVisible())
f.onActivityResult(requestCode, resultCode, data);
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
GoogleFragment.java:
public class GoogleFragment extends Fragment
implements View.OnClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
public final static String TAG = "GoogleFragment";
private GoogleApiClient mGoogleApiClient;
private ImageButton mLoginButton;
private ImageButton mLogoutButton;
public GoogleFragment() {
// required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_google, container, false);
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.build();
mLoginButton = (ImageButton) v.findViewById(R.id.login_button);
mLoginButton.setOnClickListener(this);
mLogoutButton = (ImageButton) v.findViewById(R.id.logout_button);
mLogoutButton.setOnClickListener(this);
return v;
}
private void googleLogin() {
mGoogleApiClient.connect();
}
private void googleLogout() {
if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK)
mGoogleApiClient.connect();
}
#Override
public void onClick(View v) {
if (v == mLoginButton)
googleLogin();
else
googleLogout();
}
#Override
public void onConnected(Bundle bundle) {
Person me = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
if (me != null) {
String id = me.getId();
Person.Name name = me.getName();
String given = name.getGivenName();
String family = name.getFamilyName();
boolean female = (me.hasGender() && me.getGender() == 1);
String photo = null;
if (me.hasImage() && me.getImage().hasUrl()) {
photo = me.getImage().getUrl();
photo = photo.replaceFirst("\\bsz=\\d+\\b", "sz=300");
}
String city = "Unknown city";
List<Person.PlacesLived> places = me.getPlacesLived();
if (places != null) {
for (Person.PlacesLived place : places) {
city = place.getValue();
if (place.isPrimary())
break;
}
}
Toast.makeText(getContext(), "Given: " + given + ", Family: " + family + ", Female: " + female + ", City: " + city, Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {
// ignore? don't know what to do here...
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), MainActivity.REQUEST_GOOGLE_PLUS_LOGIN);
} catch (IntentSender.SendIntentException e) {
mGoogleApiClient.connect();
}
} else {
int code = connectionResult.getErrorCode();
String str = GoogleApiAvailability.getInstance().getErrorString(code);
Toast.MakeText(getContext(), str, Toast.LENGTH_LONG).show();
}
}
}
I am working with google+ login to my application and when i done it using a activity its work charm and after that i move my code into a fragment and after that when i try to login to google+ its not working i have to open the fragment activity 2 times to login to the google+ can anyone tell me what happen the code to the fragment is added below
public class GooglePluseFragment extends Fragment implements
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
private static final String TAG = "MainActivity";
private static final int PROFILE_PIC_SIZE = 800;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut;
private Context mContext;
private Activity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = getActivity();
mContext = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.compund_google_pluse_fragment,
container, false);
btnSignIn = (SignInButton) view.findViewById(R.id.btn_sign_in);
btnSignOut = (Button) view.findViewById(R.id.btn_sign_out);
sharedPref = view.getContext().getSharedPreferences(
Constantz.SHEARED_PREFEREANCE, Context.MODE_PRIVATE);
mGoogleApiClient = new GoogleApiClient.Builder(view.getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signInWithGplus();
}
});
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOutFromGplus();
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != Activity.RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
mActivity, 0).show();
Log.e(TAG, "" + result.getErrorCode());
return;
}
if (!mIntentInProgress) {
mConnectionResult = result;
if (mSignInClicked) {
Log.e(TAG, "" + result.getErrorCode());
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
getProfileInformation();
updateUI(true);
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(mActivity,
RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
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 personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl + " user id:"
+ currentPerson.getId());
} else {
Toast.makeText(mContext, "Person information is null",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
}
this is how i added framgent in the fragment activity
pluseFragment = new GooglePluseFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.pluse_frame_layout, pluseFragment);
transaction.commit();
can somebody tell me what i have done wrong ? why i have to open the activity two times to login thank you
Finally found the answer, Problem was when the result activity call in the fragment was catch by the parent activity so you have to manually redirect the result to your fragment. Just have to add this line in your Parent Fragment Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GooglePluseFragment.RC_SIGN_IN) {
GooglePluseFragment fragment = (GooglePluseFragment) getSupportFragmentManager()
.findFragmentById(R.id.pluse_frame_layout);
fragment.onActivityResult(requestCode, resultCode, data);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Easy Solution for this ::
just create the static method in fragment
"
public static myOnActivityResult(int requestCode, int resultCode, Intent data){
.....Enter same code
}
and
call this method from Parant Activity on
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
.....
MyFragment.myOnActivityResult(requestCode,resultCode,data)
}
thats it