AutocompleteSupportFragment not working menssage 'Unable to load search results' Android - google-maps

I have a problem finding places with AutocompleteSupportFragment because it doesn't show me any results and I get an error.
I already put the new code that is used since they ask me for a Google console key and it still doesn't work.
This is my code
I don't have the password restricted, I don't know if that's the problem.
The Places API is enabled
Thank you.
MainActivity.java
public class MainActivity extends AppCompatActivity {
PlacesClient placesClient;
List<Place.Field> placesFields= Arrays.asList(Place.Field.ID,Place.Field.NAME,Place.Field.ADDRESS);
AutocompleteSupportFragment places_fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPlaces();
setUpPlacesAutocomplete();
}
private void initPlaces() {
Places.initialize(this,getString(R.string.places_api_key));
placesClient=Places.createClient(this);
}
private void setUpPlacesAutocomplete() {
places_fragment =(AutocompleteSupportFragment)getSupportFragmentManager()
.findFragmentById(R.id.places_autocompletar);
places_fragment.setPlaceFields(placesFields);
places_fragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
Toast.makeText(MainActivity.this, ""+place.getName(), Toast.LENGTH_SHORT).show();
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(MainActivity.this, ""+status.getStatusMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="#+id/places_autocompletar"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</fragment>
</LinearLayout>
In the part of the key I have it in application restrictions in the option of NONE

Please try with below code
private static final int AUTOCOMPLETE_REQUEST_CODE = 101;
/*-- initializing Places API --**/
if (!Places.isInitialized()) {
Places.initialize(getActivity(), getActivity().getResources().getString(R.string.google_map_key));
}
/*-- function to open address search activity --**/
public void createAutoCompleteIntent() {
if (getActivity() != null) {
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG, Place.Field.ADDRESS);
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields)
.build(getActivity());
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
}
}
/*-- Result of Auto complete google address search --**/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
if (place.getLatLng() != null) {
// reverse geoCoding to get Street Address, city,state and postal code
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
System.out.println("------addressList-----" + place.getAddress() + " " + place.getName());
List<Address> addressList = geocoder.getFromLocation(
place.getLatLng().latitude, place.getLatLng().longitude, 1);
System.out.println("------addressList-----" + addressList);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
System.out.println("------address-----" + address);
addressEd.setText(address.getAddressLine(0));
String featureName = "";
if (address.getFeatureName()!=null){
featureName = address.getFeatureName();
}
String throughFare = "";
if (address.getThoroughfare()!=null){
throughFare = address.getThoroughfare();
}
String streetAddress = featureName + " " + throughFare;
streetAddressEd.setText(streetAddress);
cityEd.setText(address.getLocality());
stateEd.setText(address.getAdminArea());
postCodeEd.setText(address.getPostalCode());
countryEd.setText(address.getCountryName());
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
}
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
Status status = Autocomplete.getStatusFromIntent(data);
if (getActivity() != null) {
Util.showMessageBar(getActivity(), status.getStatusMessage());
}
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}

Related

org.json.JSONException: No value for opening_hours ,how to handle this type of error

logcat screenshot
**after parsing json if there is no value for opening_hours nothing is displaying how to handle that please help me.
url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY" **
I did all techniques but not got success in that please help me to resolve this error
public class Details extends AppCompatActivity {
private ImageView image_details, open, close;
private TextView text_mobile, openNow;
private RequestQueue mRequestQueue;
String place_id, img_url, mobile, open_now;
ArrayList<DetailsPojo> mDetailsList;
private Context mContext;
LinearLayout openingLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
findViewByIds();
mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
Intent intent = getIntent();
//if (getIntent().hasExtra("PLACE_ID"))
place_id = intent.getStringExtra("PLACE_ID");
Toast.makeText(this, "Place ID :" + place_id.toString(), Toast.LENGTH_SHORT).show();
parseJson();
}
private void parseJson() {
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place_id + "&key=" + KEY;
Log.d("DetailedURL",url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject resultObject = response.getJSONObject("result");
mobile = resultObject.optString("formatted_phone_number", "not available");
if (resultObject.has("formatted_phone_number")) {
text_mobile.setText(mobile);
} else {
text_mobile.setText("not available");
}
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
open_now = openingObject.optString("open_now", "Not provided");
if(resultObject.has("opening_hours")) {
if (open_now.equalsIgnoreCase("true")) {
open.setVisibility(View.VISIBLE);
openNow.setText("Open");
} else {
close.setVisibility(View.VISIBLE);
openNow.setText("Closed");
}
}else {
openNow.setText("no information provided for Open/Close");
}
if(resultObject.has("photos")){
JSONArray photosArray = resultObject.getJSONArray("photos");
for (int i = 0; i < photosArray.length(); i++) {
JSONObject photosObject = photosArray.getJSONObject(i);
img_url = URL_PHOTO + photosObject.optString("photo_reference","No image available") + "&key=" + KEY;
if (img_url.isEmpty()) {
image_details.setImageResource(R.drawable.hospital);
} else {
Picasso.with(mContext).load(img_url).fit().centerInside().into(image_details);
}
}
}else{
image_details.setImageResource(R.drawable.no_image_available);
}
// mDetailsList.add(new DetailsPojo(img_url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
private void findViewByIds() {
image_details = findViewById(R.id.image_view);
open = findViewById(R.id.open);
close = findViewById(R.id.closed);
text_mobile = findViewById(R.id.text_mobile);
openNow = findViewById(R.id.text_open_now);
openingLayout=findViewById(R.id.Openinglayout);
}
}
Please check your JSON that is coming from the Google APIs https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=AIzaSyBB8VIJUlcVwYC2EnEQATSMIa9S1cDguDg
as you can see in Logcat that it is saying that No value for "opening_hours".
& you are trying to get that JSONObject without checking it that it exists or not.
here you can see your code :-
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
So first validate it that it is coming or not as per the documentation it can even throw the exception if the mapping does not go well.
https://developer.android.com/reference/org/json/JSONObject#getJSONObject(java.lang.String)

How to get url of uploaded file to google drive in android using Drive API?

I need to get the link of the video that I upload it to google drive so that I can open the video in the web browser, I can upload a video file to google drive and can get also the file ID using the following code:
private void UploadFile(final DriveId driveId)
{
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult driveContentsResult)
{
if (!driveContentsResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create new file contents");
return;
}
OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
Toast.makeText(context, "Uploading to drive....", Toast.LENGTH_LONG).show();
final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoFiles/testVideo.mkv");
try
{
FileInputStream fileInputStream = new FileInputStream(theFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1)
{
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mkv").setStarred(false).build();
DriveFolder folder = driveId.asDriveFolder();
folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(#NonNull DriveFolder.DriveFileResult driveFileResult)
{
if (!driveFileResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the file");
return;
}
Log.v(TAG, "Created a file: " + driveFileResult.getDriveFile().getDriveId());
}
});
}
});
}
I tried to get the video url using the following code:
DriveFile file = Drive.DriveApi.getFile(googleApiClient,driveId);
DriveResource.MetadataResult mdRslt = file.getMetadata(googleApiClient).await();
if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
String link = mdRslt.getMetadata().getWebContentLink();
Log.d("LINK", link);
}
But then I got "Cannot resolve symbol 'googleApiClient'
Any suggestion please?
Ok, I found the solution, first I have to get the completed file ID by using the change events listener, then we can add "drive.google.com/open?id=" to the file ID, so the complate url will be drive.google.com/open?id=FileID.
here is my answer:
public class Uploader extends Activity implements ConnectionCallbacks,OnConnectionFailedListener{
private static final String TAG = "Google Drive Activity";
private static final int REQUEST_CODE_RESOLUTION = 1;
private static final int REQUEST_CODE_OPENER = 2;
private GoogleApiClient mGoogleApiClient;
public DriveFile file;
private String FOLDER_NAME = "GD_VideoFile";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume()
{
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onStop()
{
super.onStop();
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result)
{
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint)
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
if (mGoogleApiClient != null)
{
check_folder_exists();
} else
{
Log.e(TAG, "Could not connect to google drive manager");
}
}
#Override
public void onConnectionSuspended(int cause)
{
Log.i(TAG, "GoogleApiClient connection suspended");
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data)
{
switch (requestCode)
{
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK)
{
DriveId mFileId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("file id", mFileId.getResourceId() + "");
String url = "https://drive.google.com/open?id="+ mFileId.getResourceId();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
private void check_folder_exists()
{
Query query = new Query.Builder().addFilter(Filters.and(Filters.eq(SearchableField.TITLE, FOLDER_NAME), Filters.eq(SearchableField.TRASHED, false))).build();
Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(#NonNull DriveApi.MetadataBufferResult result)
{
if (!result.getStatus().isSuccess())
{
Log.e(TAG, "Cannot create folder in the root.");
} else
{
boolean isFound = false;
for (Metadata m : result.getMetadataBuffer())
{
if (m.getTitle().equals(FOLDER_NAME)) {
Log.e(TAG, "Folder exists");
isFound = true;
DriveId driveId = m.getDriveId();
UploadFile(driveId);
break;
}
}
if (!isFound)
{
Log.i(TAG, "Folder not found; creating it.");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(FOLDER_NAME).build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFolder(mGoogleApiClient, changeSet)
.setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() {
#Override
public void onResult(#NonNull DriveFolder.DriveFolderResult result)
{
if (!result.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the folder");
} else {
Log.i(TAG, "Created a folder");
DriveId driveId = result.getDriveFolder().getDriveId();
UploadFile(driveId);
}
}
});
}
}
}
});
}
private void UploadFile(final DriveId driveId)
{
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>()
{
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult driveContentsResult)
{
if (!driveContentsResult.getStatus().isSuccess())
{
Log.e(TAG, "U AR A MORON! Error while trying to create new file contents");
return;
}
OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
Toast.makeText(Uploader.this, "Uploading to drive....", Toast.LENGTH_LONG).show();
final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyMobile_Videos/a.mov");
try
{
FileInputStream fileInputStream = new FileInputStream(theFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1)
{
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mov").setStarred(false).build();
DriveFolder folder = driveId.asDriveFolder();
folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>()
{
#Override
public void onResult(#NonNull DriveFolder.DriveFileResult driveFileResult)
{
if (!driveFileResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the file");
return;
}
Toast.makeText(Uploader.this, "Created a file: " + driveFileResult.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
String Folder_Id = driveId.getResourceId();
System.out.println("The folder id: " +Folder_Id);
//This is to get the file id from the listener
DriveId File_Uncompleted_Id = driveFileResult.getDriveFile().getDriveId();
DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, File_Uncompleted_Id);
file.addChangeListener(mGoogleApiClient, changeListener);
}
//A listener to handle file change events.
final private ChangeListener changeListener = new ChangeListener()
{
#Override
public void onChange(ChangeEvent event)
{
String File_Completed_Id = event.getDriveId().getResourceId();
System.out.println("The uploaded file id: " +File_Completed_Id);
System.out.println("File URL: https://drive.google.com/open?id=" +File_Completed_Id);
}
};
}
);
}
}
);
}
}

NullPointerException at dual fragment display

I'm writing an app that has two kinds of displays:
1. "phone mode" on normal sized displays, show one fragment at a time (search fragment, map fragment, etc). Here the fragments load with no particular problem.
2."Tablet mode" on larger displays, shows two fragments side by side - one is the same as "phone mode", the second is a permenant display of the map fragment. When trying to load the app on a tablet emulator it throws an exception:
FATAL EXCEPTION: main
Process: il.co.sredizemnomorie.myapiplaces, PID: 7808
java.lang.RuntimeException: Unable to start activity ComponentInfo{il.co.sredizemnomorie.myapiplaces/il.co.sredizemnomorie.myapiplaces.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at maps.f.g.a(Unknown Source)
at maps.ag.g$a.<init>(Unknown Source)
at maps.ag.g.a(Unknown Source)
at maps.ag.R.<init>(Unknown Source)
at maps.ag.t.a(Unknown Source)
at uz.onTransact(:com.google.android.gms.DynamiteModulesB:167)
at android.os.Binder.transact(Binder.java:361)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addMarker(Unknown Source)
at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
at il.co.sredizemnomorie.myapiplaces.FragmentWithMap.setUpMap(FragmentWithMap.java:165)
at il.co.sredizemnomorie.myapiplaces.FragmentWithMap.setUpMapIfNeeded(FragmentWithMap.java:141)
at il.co.sredizemnomorie.myapiplaces.FragmentWithMap.onCreateView(FragmentWithMap.java:72)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:339)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:602)
at il.co.sredizemnomorie.myapiplaces.MainActivity.onStart(MainActivity.java:270)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
at android.app.Activity.performStart(Activity.java:5241)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Here's the code:
MainActivity.java
public class MainActivity extends ActionBarActivity implements FragmentWithDetails.OnFragmentInteractionListener, FragmentWithMap.OnFragmentInteractionListener,
FragmentWithDetails.ListFragmentListener, TextView.OnEditorActionListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
SettingsFragment.OnFragmentInteractionListener {
private static final String TAG = "PlaceFounder";
public static final String TAG_FAVORITES = "frag_favorites";
private static final String TAG_MAP = "map";
private static final String TAG_DETAILS = "details";
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
private Bundle currentLocationBundle = new Bundle();
FragmentTransaction fragmentTransaction;
private android.support.v4.app.FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
fragmentManager = getSupportFragmentManager();
FragmentWithDetails fragmentDetails;
if (isSingleFragment()) {
if (savedInstanceState == null) {
fragmentDetails = FragmentWithDetails.newInstance();
fragmentDetails.setArguments(currentLocationBundle);
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmnet_container, fragmentDetails, TAG_DETAILS);
fragmentTransaction.commit();
}
}//end if we at small screen
else {
if (savedInstanceState == null) {
fragmentDetails = FragmentWithDetails.newInstance();
FragmentWithMap fragmentWithMap = FragmentWithMap.newInstance(null);
fragmentDetails.setArguments(currentLocationBundle);
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmnet_container_details, fragmentDetails, TAG_DETAILS);
fragmentTransaction.add(R.id.fragmnet_container_map, fragmentWithMap, TAG_MAP);
fragmentTransaction.commit();
}
}//end if big screen
}
// Show favorites fragment
private void showFavorites() {
currentLocationBundle.putInt("isShowFav", 1);
FragmentWithDetails fragmentFavorites = (FragmentWithDetails) fragmentManager.findFragmentByTag(TAG_FAVORITES);
if (fragmentFavorites == null) {
fragmentFavorites = FragmentWithDetails.newInstance();
fragmentFavorites.setArguments(currentLocationBundle);
}
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmnet_container, fragmentFavorites, TAG_FAVORITES);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.show(fragmentFavorites);
handleLargeLayout();
fragmentTransaction.commit();
}
//Hide details and map only on large screen
//On small screen we reuse the same container
private void handleLargeLayout() {
if (!isSingleFragment()) {
fragmentTransaction.hide(getDetailsFragment());
fragmentTransaction.hide(getMapFragment());
}
}
private FragmentWithMap getMapFragment() {
return (FragmentWithMap) fragmentManager.findFragmentByTag(TAG_MAP);
}
private FragmentWithDetails getDetailsFragment() {
return (FragmentWithDetails) fragmentManager.findFragmentByTag(TAG_DETAILS);
}
private FragmentWithDetails getFavoritesFragment() {
return (FragmentWithDetails) fragmentManager.findFragmentByTag(TAG_FAVORITES);
}
// Show settings fragment
private void showSettings() {
SettingsFragment settingsFragment = SettingsFragment.newInstance();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmnet_container, settingsFragment, "frag_settings");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.show(settingsFragment);
handleLargeLayout();
fragmentTransaction.commit();
}
// Display current location on map
private void getCurrentLocation() {
String currentLat = null;
String currentLong = null;
if (mLastLocation != null) {
currentLat = String.valueOf(mLastLocation.getLatitude());
currentLong = String.valueOf(mLastLocation.getLongitude());
if (getMapFragment() != null) {
getMapFragment().setPlace(new Place(0, "Current location", "", (float) mLastLocation.getLatitude(), (float) mLastLocation.getLongitude()));
}
}
currentLocationBundle.putString("currentLat", currentLat);
currentLocationBundle.putString("currentLong", currentLong);
}
//Builds a GoogleApiClient.
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
showSettings();
return true;
case R.id.action_favorites:
showFavorites();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected boolean isSingleFragment() {
return findViewById(R.id.layout_single_fragment) != null;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onPlaceSelected(long placeId) {
fragmentManager = getSupportFragmentManager();
Place place = getPlace(placeId);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (isSingleFragment()) {
FragmentWithMap fragmentWithMap = FragmentWithMap.newInstance(place);
fragmentTransaction.replace(R.id.fragmnet_container, fragmentWithMap, TAG_MAP).addToBackStack(null);
} else {
if (getMapFragment() == null) {
android.support.v4.app.Fragment fragmentWithMap = FragmentWithMap.newInstance(place);
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmnet_container_map, fragmentWithMap, TAG_MAP);
fragmentTransaction.show(fragmentWithMap);
fragmentTransaction.show(getDetailsFragment());
} else {
FragmentWithMap fragmentWithMap = getMapFragment();
fragmentTransaction.show(fragmentWithMap);
fragmentTransaction.show(getDetailsFragment());
if (getFavoritesFragment() != null) {
fragmentTransaction.hide(getFavoritesFragment());
}
fragmentWithMap.showPlace(place);
}
}
fragmentTransaction.commit();
}
private Place getPlace(long placeId) {
Cursor cursor = null;
Place place = null;
try {
cursor = getContentResolver().query(PlacesContract.Places.CONTENT_URI, null, "_id=" + placeId, null, "name DESC");
cursor.moveToNext();
place = new Place(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getFloat(3), cursor.getFloat(4));
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return place;
}
#Override
public void onBackPressed() {
if (isSingleFragment() && getMapFragment() != null) {
fragmentManager.popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else if (fragmentManager.findFragmentByTag("frag_favorites") != null) {
fragmentManager.popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else if (fragmentManager.findFragmentByTag("frag_settings") != null) {
fragmentManager.popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
super.onBackPressed();
}
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
return true;
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
//start google analytics
EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
//stop google analytics
EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation == null) {
Toast.makeText(this, "Location not found", Toast.LENGTH_LONG).show();
}
getCurrentLocation();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
toast("No Google Service");
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
private void toast(String message) {
Toast.makeText(this, message,
Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
}
the map fragment:
FragmentWithMap.java
public class FragmentWithMap extends android.support.v4.app.Fragment {
private OnFragmentInteractionListener mListener;
private static final double LAT = 32.084;
private static final double LON = 34.8878;
Place place;
private GoogleMap mMap;
private View view;
private Marker marker;
int userIcon = FragmentWithDetails.userIcon;
public static FragmentWithMap newInstance(Place place) {
Bundle args = new Bundle();
if (place != null) {
args.putInt("id", place.getId());
args.putString("name", place.getName());
args.putString("address", place.getAddress());
args.putFloat("lat", place.getLat());
args.putFloat("lng", place.getLng());
}
FragmentWithMap fragment = new FragmentWithMap();
fragment.setArguments(args);
return fragment;
}
public FragmentWithMap() {
//empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null && getArguments().getString("name") != null) {
place = new Place(getArguments().getInt("id"), getArguments().getString("name"),
getArguments().getString("address"), getArguments().getFloat("lat"),
getArguments().getFloat("lng"));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_fragment_with_map, container, false);
}
setUpMapIfNeeded();
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
android.support.v4.app.Fragment f = getFragmentManager()
.findFragmentById(R.id.fragmnet_container_map);
if (f != null) {
try {
getFragmentManager().beginTransaction().remove(f).commit();
} catch (IllegalStateException ise) {
Log.d("FragmentWithMap", "Already closed");
}
}
ViewGroup parentViewGroup = (ViewGroup) view.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeAllViews();
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void showPlace(Place place) {
setPlace(place);
setUpMap();
}
public void setPlace(Place place) {
this.place = place;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
private void setUpMapIfNeeded() {
// Do a null check
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
Fragment mmm = getChildFragmentManager().findFragmentById(R.id.fragment_map2);
mMap = ((SupportMapFragment) mmm).getMap();
// Check if we were successful
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
double lat = LAT;
double lng = LON;
String name = "You are here";
if (place != null) {
lat = place.getLat();
lng = place.getLng();
name = place.getName();
}
if (marker != null) {
marker.remove();
}
LatLng position = new LatLng(lat, lng);
MarkerOptions markerOptions = new MarkerOptions().
position(position).
title(name).
icon(BitmapDescriptorFactory.fromResource(userIcon)).
snippet("Your last recorded location");
marker = mMap.addMarker(markerOptions);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(position, 15);
mMap.animateCamera(cameraUpdate);
}
}
The XMLs:
activity_main.xml
"phone mode":
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout_single_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/fragmnet_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"></FrameLayout>
and "tablet mode"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout_two_fragments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".MainActivity"
>
<FrameLayout
android:id="#+id/fragmnet_container"
android:layout_width="wrap_content"
android:layout_height="match_parent"></FrameLayout>
<FrameLayout
android:id="#+id/fragmnet_container_details"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.31"></FrameLayout>
<FrameLayout
android:id="#+id/fragmnet_container_map"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"></FrameLayout>
I'd greatly appreciate any help you might offer...
Update:
The crashpoint is at the end of the mapfragment in the at the marker = mMap.addMarker(markerOptions); line. I guess I must not be handling the markers correctly... Still not clear why it works fine in single fragment mode, and not dual fragments.
You are trying to access UI elements in the onCreate() but , onCreate() is too early to call getView() and it will return null. Postpone the code that needs to touch the fragment's view hierarchy to onCreateView() or later in the fragment lifecycle. Since in fragment views can be created in onCreateView() method.
Try to include onActivityCreated() which calls when the fragment's activity has been created and this fragment view hierarchy instantiated.
Update: solved
The problem ended up being with the userIcon (which represents the cosmetic type of marker shown on the map). When the app first load, it for some reason returned 0 instead of null. Since it's merely a cosmetic feature I simply removed, and that solved the problem. Not the prettiest solution but it's the one I got, since time constraint prevent me from dedicated more time to this when more critical parts of the app still need tending; I hope it helps. I hope a more experienced programmer will likely be familiar enough with the marker system to offer alternative solutions/workarounds for those who wish to include custom markers.

How to detect If AdRotator V2.1 is showing an Ad or an error occurred

I want to update my UI based on the scenario when an Ad is being shown or an error occurred. I am using AdRotator v2.1. Looking at the source code it seems that the control would collapse if it could not serve an ad from various provider, and the IsAdRotatorEnabled would be set to false. But that property does not trigger an notification change. How can i detect if no ads are being shown?
Enabled="{Binding AreAdsEnabled,Mode=TwoWay,FallbackValue=true,UpdateSourceTrigger=PropertyChanged}"
This is hack i am currently using. Its quite brittle. Its looking at log message for strings to detect if an error has occurred.
public class BaseAdControl
{
public AdRotatorControl CurrentAdRotatorControl { get; set; }
private UserControl userControlWrapper;
public BaseAdControl(AdRotatorControl MyAdRotatorControl, UserControl userControlWrapper)
{
// TODO: Complete member initialization
this.CurrentAdRotatorControl = MyAdRotatorControl;
this.userControlWrapper = userControlWrapper;
MyAdRotatorControl.PlatformAdProviderComponents.Add(AdRotator.Model.AdType.PubCenter, typeof(Microsoft.Advertising.WinRT.UI.AdControl));
MyAdRotatorControl.PlatformAdProviderComponents.Add(AdRotator.Model.AdType.AdDuplex, typeof(AdDuplex.Universal.Controls.Win.XAML.AdControl));
MyAdRotatorControl.Loaded += MyAdRotatorControl_Loaded;
MyAdRotatorControl.Unloaded += MyAdRotatorControl_Unloaded;
}
#region Public Properties
#endregion Public Properties
#region Public Methods
public virtual void adDuplex_AdLoadingError(object sender, AdDuplex.Universal.Win.WinRT.Models.AdLoadingErrorEventArgs e)
{
AdDuplex.Universal.Controls.Win.XAML.AdControl adCtrl = sender as AdDuplex.Universal.Controls.Win.XAML.AdControl;
adCtrl.AdLoadingError -= adDuplex_AdLoadingError;
Utilities.logger.LogDebug(e.Error.Message);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
public virtual async void Logger(string message)
{
Utilities.logger.LogDebug("AdRotator: " + message);
if (string.Equals(message, "No Ads available", StringComparison.CurrentCultureIgnoreCase))
{
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
else if (message.Contains("Ad created for provider"))
{
var cont = CurrentAdRotatorControl as Control;
Object adType = null;
if (cont != null)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
Border border = VisualTreeHelper.GetChild(CurrentAdRotatorControl, 0) as Border;
if (border != null)
{
adType = border.Child;
}
});
if (adType != null)
{
if (adType is Microsoft.Advertising.WinRT.UI.AdControl)
{
var pubsub = adType as Microsoft.Advertising.WinRT.UI.AdControl;
if (pubsub != null)
pubsub.ErrorOccurred += pubsub_ErrorOccurred;
}
else if (adType is AdDuplex.Universal.Controls.Win.XAML.AdControl)
{
var adDuplex = adType as AdDuplex.Universal.Controls.Win.XAML.AdControl;
if (adDuplex != null)
adDuplex.AdLoadingError += adDuplex_AdLoadingError;
}
else if (adType is SomaAd)
{
var smato = adType as SomaAd;
if (smato != null)
smato.GetAdError += smato_GetAdError;
}
}
}
this.userControlWrapper.Visibility = Utilities.AreAdsEnabled ? Visibility.Visible : Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: "+this.userControlWrapper.Visibility);
}
}
public virtual void MyAdRotatorControl_Loaded(object sender, RoutedEventArgs e)
{
AdRotatorControl.Log += Logger;
}
public virtual void MyAdRotatorControl_Unloaded(object sender, RoutedEventArgs e)
{
AdRotatorControl.Log -= Logger;
}
public virtual void pubsub_ErrorOccurred(object sender, Microsoft.Advertising.WinRT.UI.AdErrorEventArgs e)
{
Microsoft.Advertising.WinRT.UI.AdControl adCtrl = sender as Microsoft.Advertising.WinRT.UI.AdControl;
adCtrl.ErrorOccurred -= pubsub_ErrorOccurred;
Utilities.logger.LogDebug(e.Error + " ," + e.ErrorCode);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
public virtual void smato_GetAdError(object sender, string ErrorCode, string ErrorDescription)
{
SomaAd adCtrl = sender as SomaAd;
adCtrl.GetAdError -= smato_GetAdError;
Utilities.logger.LogDebug(ErrorDescription + " ," + ErrorCode);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
#endregion Public Methods
}

Null map returned from supportmapfragment

I am trying to use Google Maps API v2 in my Android application. I have added the map fragment programmatically using following code and then I try getting the GoogleMap from my SupportMapFragment, but I always get null result back even though the map shows up on screen fine...Any help is highly appreciated!!!!!!!
Thanks
public class MapActivity extends BaseFragmentActivity {
private SchoolType mSchoolType=SchoolType.ALL;
private GoogleMap mMap;
private UiSettings mUiSettings;
private SupportMapFragment mMapFragment;
private static final String MAP_FRAGMENT_TAG = "map";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.map_activity);
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
if(mMapFragment==null)
addMapFragment();
setUpMapIfNeeded();
}
catch(Exception ex){
System.err.println("Exception: " + ex.getMessage());
}
}
private void addMapFragment(){
try{
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.zoomControlsEnabled(true) ;
mMapFragment = SupportMapFragment.newInstance(options);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_map_content, mMapFragment,MAP_FRAGMENT_TAG);
//transaction.addToBackStack(null);
transaction.commit();
}
catch(Exception ex){
System.err.println("Exception: " + ex.getMessage());
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = mMapFragment.getMap(); ***//ALWAYS RETUN NULL***
//mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
call setUpMapIfNeeded in onResume(), like this.
#Override
protected void onResume() {
super.onResume();
// In case Google Play services has since become available.
setUpMapIfNeeded();
}