How to load markers instantly android - google-maps-markers

I using googleMap and what i'm tring to do is to refresh markers from firebase database, and that mean i delete all the previous markers and add the new ones by using this methode
#Override
public void onKeyEntered(String key, GeoLocation location) {
try{
MyItem myItem = new MyItem(location.latitude, location.longitude);
if (!items.contains(myItem)) {
items.add(myItem);
}
Log.d("onKey","called");
}catch (ClassCastException e){
Log.d("classCastException","");
}
}
parseJsonToList methode :
private void parseJsonToList() {
itemss = clusterManagerAlgorithm.getItems();
try {
items.removeAll(itemss);
}catch (IndexOutOfBoundsException e){
Log.d("itemsDoesn't exist"," : ");
}
mClusterManager.clearItems();
mClusterManager.cluster();
mClusterManager.addItems(items);
Log.d("items"," : " + items);
}
So, my problem is that everytime I'm tring to clean and load data what happened is that all markers desapears for about 3 second to been reloaded again. How can i delete and reload data without markers dispear.
this is myItem class :
public class MyItem implements ClusterItem {
private final LatLng mPosition;
public MyItem(double lat, double lng) {
mPosition = new LatLng(lat, lng);
}
#Override
public LatLng getPosition() {
return mPosition;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyItem item = (MyItem) o;
return Objects.equals(mPosition, item.mPosition);
}
#Override
public int hashCode() {
return Objects.hash(mPosition);
}
}

Related

Android Studio sort the value from TextView in a ListView

I try to sort my ListView with the date from TextView.
In the Screenshots you can see my ToDo List, one TextView stores the Due Date. I try to sort the ListView with the dates, but i do not know how to do it right.
Here is the Code i could find in a Tutorial, but it does not work for me.
public class ToDoOverview extends AppCompatActivity {
ListView lv;
List<ToDo> dataSource;
ToDoOverviewListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do_overview);
this.lv = (ListView) findViewById(R.id.listToDo);
this.dataSource = ToDoDatabaseHelper.getInstance(this).readAllToDos();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_NewToDo:
createToDo();
return true;
case R.id.menu_dailyToDo:
showDailyToDo();
return true;
case R.id.menu_Sort_Fav:
sortFav();
return true;
case R.id.menu_Sort_Date:
sortDate();
return true;
case R.id.menu_Sort_Progress:
sortProg();
return true;
}
return super.onOptionsItemSelected(item);
}
public void sortDate(){
adapter.sort(new Comparator<ToDo>() {
#Override
public int compare(ToDo todo1, ToDo todo2) {
if(todo1.getDueDate() != null && todo2.getDueDate() != null){
long date = todo1.getDueDate().compareTo(todo2.getDueDate());
if(date != 0) {
refreshListView();
return (int) date;
} else if(todo1.getDueDate() != null){
refreshListView();
return -1;
} else if(todo2.getDueDate() != null){
refreshListView();
return 1;
}
return todo1.getName().compareToIgnoreCase(todo2.getName());
}
});
}
And here is My ToDoOverviewListAdapter Class:
public class ToDoOverviewListAdapter extends ArrayAdapter<ToDo> {
public ToDoOverviewListAdapter(Context context, List<ToDo> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ToDo currentToDo = (ToDo) getItem(position);
View view = convertView;
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.todo_overview_listitem, parent, false);
}
// First Step
((TextView) view.findViewById(R.id.tvName)).setText(currentToDo.getName());
TextView dueDate = (TextView) view.findViewById(R.id.tvDueDate);
ImageView fav = (ImageView) view.findViewById(R.id.favIcon);
TextView progStatus = (TextView) view.findViewById(R.id.progStatus);
if(currentToDo.getDueDate() == null){
dueDate.setVisibility(View.INVISIBLE);
} else {
dueDate.setVisibility(View.VISIBLE);
dueDate.setText(currentToDo.getDueDate());
}
if(currentToDo.isFavorite()){
fav.setVisibility(View.VISIBLE);
}else{
fav.setVisibility(View.INVISIBLE);
}
if(currentToDo.getProgress() == null){
progStatus.setVisibility(View.INVISIBLE);
} else {
progStatus.setVisibility(View.VISIBLE);
progStatus.setText(currentToDo.getProgress());
}
return view;
}
}

Receiving Sinch messages and call in background and show notifications for incoming message and show overlay for call

i am using Sinch in my app for video, audio and messaging purpose. calling and messaging works fine when the app is running in foreground. when the app is closed and removed from stack, incoming messages and calls still works as i implemented push notification to look for incoming calls and messages (i checked in debug mode). My problem is that
1) when i start incoming call activity from firebaseMessaginService it does not show the caller name and picture i am sending in headers as i start it through relayRemotePushNotificationPayload(HashMap);
2) i am unable to get the message content data from incoming message and show notification accordingly.
My Code.
public class MyFirebaseMessagingService extends FirebaseMessagingService implements ServiceConnection {
Context context;
private SinchService.SinchServiceInterface mSinchServiceInterface;
HashMap dataHashMap;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
context = this;
if (SinchHelpers.isSinchPushPayload(remoteMessage.getData())) {
Map data = remoteMessage.getData();
dataHashMap = (data instanceof HashMap) ? (HashMap) data : new HashMap<>(data);
if (SinchHelpers.isSinchPushPayload(dataHashMap)) {
getApplicationContext().bindService(new Intent(getApplicationContext(), SinchService.class), this, Context.BIND_AUTO_CREATE);
}
} else {
Intent intent;
PendingIntent pendingIntent = null;
if (remoteMessage.getData().size() > 0) {
String identifier = remoteMessage.getData().get("identifier");
if (identifier.equals("0")) {
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
} else if (identifier.equals("1")) {
intent = new Intent(this, Appointments.class);
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
StaticInfo.saveData("HEALTH_TIP", "TIP", this);
}
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setWhen(System.currentTimeMillis());
notificationBuilder.setContentTitle(remoteMessage.getNotification().getTitle());
notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationBuilder.setDefaults(Notification.DEFAULT_ALL | Notification.DEFAULT_LIGHTS | Notification.FLAG_SHOW_LIGHTS | Notification.DEFAULT_SOUND);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
public static boolean foregrounded() {
ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(appProcessInfo);
return (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE);
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
}
// it starts incoming call activity which does not show incoming caller name and picture
NotificationResult result = mSinchServiceInterface.relayRemotePushNotificationPayload(dataHashMap);
if (result.isValid() && result.isCall()) {
CallNotificationResult callResult = result.getCallResult();
if (callResult.isCallCanceled() || callResult.isTimedOut()) {
createNotification("Missed Call from : ", callResult.getRemoteUserId());
return;
} else {
if (callResult.isVideoOffered()) {
Intent intent = new Intent(this, IncomingVideoCall.class);
intent.putExtra(SinchService.CALL_ID, callResult.getRemoteUserId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
} else {
Intent intent = new Intent(this, IncomingAudioCall.class);
intent.putExtra(SinchService.CALL_ID, callResult.getRemoteUserId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
}
} else if (result.isValid() && result.isMessage()) {
//i want to get message content here
MessageNotificationResult notificationResult = result.getMessageResult();
createNotification("Received Message from : ", notificationResult.getSenderId());
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
unbindService(this);
}
private void createNotification(String contentTitle, String userId) {
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext()).setSmallIcon(R.mipmap.ic_launcher).setContentTitle(contentTitle).setContentText(userId);
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
Sinch service is
public class SinchService extends Service {
private static final String APP_KEY = "123abc";
private static final String APP_SECRET = "123abc";
private static final String ENVIRONMENT = "sandbox.sinch.com";
public static final String CALL_ID = "CALL_ID";
static final String TAG = SinchService.class.getSimpleName();
private SinchServiceInterface mSinchServiceInterface = new SinchServiceInterface();
private SinchClient mSinchClient;
private String mUserId;
private StartFailedListener mListener;
private PersistedSettings mSettings;
#Override
public void onCreate() {
super.onCreate();
mSettings = new PersistedSettings(getApplicationContext());
String userName = mSettings.getUsername();
if (!userName.isEmpty()) {
start(userName);
}
}
#Override
public void onDestroy() {
if (mSinchClient != null && mSinchClient.isStarted()) {
mSinchClient.terminate();
}
super.onDestroy();
}
private void start(String userName) {
if (mSinchClient == null) {
mSettings.setUsername(userName);
mUserId = userName;
mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext()).userId(userName).applicationKey(APP_KEY).applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT).build();
mSinchClient.setSupportCalling(true);
mSinchClient.setSupportMessaging(true);
mSinchClient.setSupportManagedPush(true);
mSinchClient.checkManifest();
mSinchClient.setSupportActiveConnectionInBackground(true);
mSinchClient.startListeningOnActiveConnection();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.getCallClient().setRespectNativeCalls(false);
mSinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
mSinchClient.getVideoController().setResizeBehaviour(VideoScalingType.ASPECT_FILL);
mSinchClient.start();
}
}
private void stop() {
if (mSinchClient != null) {
mSinchClient.terminate();
mSinchClient = null;
}
mSettings.setUsername("");
}
private boolean isStarted() {
return (mSinchClient != null && mSinchClient.isStarted());
}
#Override
public IBinder onBind(Intent intent) {
return mSinchServiceInterface;
}
public class SinchServiceInterface extends Binder {
public NotificationResult relayRemotePushNotificationPayload(final Map payload) {
if (mSinchClient == null && !mSettings.getUsername().isEmpty()) {
start(mSettings.getUsername());
} else if (mSinchClient == null && mSettings.getUsername().isEmpty()) {
if (!StaticInfo.getSavedData("username", SinchService.this).equals("")) {
start(StaticInfo.getSavedData("username", SinchService.this));
}
return null;
}
return mSinchClient.relayRemotePushNotificationPayload(payload);
}
public void sendMessage(String recipientUserId, String Name, String textBody, String imageUrl) {
SinchService.this.sendMessage(recipientUserId, Name, textBody, imageUrl);
}
public void addMessageClientListener(MessageClientListener listener) {
SinchService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
SinchService.this.removeMessageClientListener(listener);
}
public Call callUser(String userId, HashMap<String, String> name) {
if (mSinchClient == null) {
return null;
}
return mSinchClient.getCallClient().callUser(userId, name);
}
public Call callUserVideo(String userId, HashMap<String, String> name) {
return mSinchClient.getCallClient().callUserVideo(userId, name);
}
public String getUserName() {
return mUserId;
}
public boolean isStarted() {
return SinchService.this.isStarted();
}
public void startClient(String userName) {
start(userName);
}
public void stopClient() {
stop();
}
public void setStartListener(StartFailedListener listener) {
mListener = listener;
}
public Call getCall(String callId) {
return mSinchClient.getCallClient().getCall(callId);
}
public VideoController getVideoController() {
if (!isStarted()) {
return null;
}
return mSinchClient.getVideoController();
}
public AudioController getAudioController() {
if (!isStarted()) {
return null;
}
return mSinchClient.getAudioController();
}
public void LogOut() {
if (mSinchClient != null) {
mSinchClient.stopListeningOnActiveConnection();
mSinchClient.unregisterPushNotificationData();
mSinchClient.unregisterManagedPush();
//mSinchClient.terminate();
}
}
}
public interface StartFailedListener {
void onStartFailed(SinchError error);
void onStarted();
}
private class MySinchClientListener implements SinchClientListener {
#Override
public void onClientFailed(SinchClient client, SinchError error) {
if (mListener != null) {
mListener.onStartFailed(error);
}
mSinchClient.terminate();
mSinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
Log.d(TAG, "SinchClient started");
if (mListener != null) {
mListener.onStarted();
}
}
#Override
public void onClientStopped(SinchClient client) {
Log.d(TAG, "SinchClient stopped");
}
#Override
public void onLogMessage(int level, String area, String message) {
switch (level) {
case Log.DEBUG:
Log.d(area, message);
break;
case Log.ERROR:
Log.e(area, message);
break;
case Log.INFO:
Log.i(area, message);
break;
case Log.VERBOSE:
Log.v(area, message);
break;
case Log.WARN:
Log.w(area, message);
break;
}
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration clientRegistration) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
if (call.getDetails().isVideoOffered()) {
Intent intent = new Intent(SinchService.this, IncomingVideoCall.class);
intent.putExtra(CALL_ID, call.getCallId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
SinchService.this.startActivity(intent);
} else {
Intent intent = new Intent(SinchService.this, IncomingAudioCall.class);
intent.putExtra(CALL_ID, call.getCallId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
SinchService.this.startActivity(intent);
}
}
}
private class PersistedSettings {
private SharedPreferences mStore;
private static final String PREF_KEY = "Sinch";
public PersistedSettings(Context context) {
mStore = context.getSharedPreferences(PREF_KEY, MODE_PRIVATE);
}
public String getUsername() {
return mStore.getString("Username", "");
}
public void setUsername(String username) {
SharedPreferences.Editor editor = mStore.edit();
editor.putString("Username", username);
editor.commit();
}
}
public void sendMessage(String recipientUserId, String name, String textBody, String imageUrl) {
if (isStarted()) {
WritableMessage message = new WritableMessage();
message.addHeader("imageUrl", imageUrl);
message.addHeader("Name", name);
message.addRecipient(recipientUserId);
message.setTextBody(textBody);
mSinchClient.getMessageClient().send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (mSinchClient != null) {
mSinchClient.getMessageClient().addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (mSinchClient != null) {
mSinchClient.getMessageClient().removeMessageClientListener(listener);
}
}
}
i am sending message like this.
private void sendMessage() {
String textBody = mTxtTextBody.getText().toString();
if (textBody.isEmpty()) {
Toast.makeText(this, "No text message", Toast.LENGTH_SHORT).show();
return;
}
getSinchServiceInterface().sendMessage(receiver_username, name, textBody, picture);
mTxtTextBody.setText("");
}
and the adapter where extracting message headers is
public class MessageAdapter extends BaseAdapter {
public static final int DIRECTION_INCOMING = 0;
public static final int DIRECTION_OUTGOING = 1;
private List<Pair<Message, Integer>> mMessages;
private SimpleDateFormat mFormatter;
private LayoutInflater mInflater;
Context context; // modification here
int res = 0;
String photo_url;
public MessageAdapter(Activity activity) {
mInflater = activity.getLayoutInflater();
context = activity;
mMessages = new ArrayList<>();
mFormatter = new SimpleDateFormat("hh:mm aa");
}
public void addMessage(Message message, int direction) {
mMessages.add(new Pair(message, direction));
notifyDataSetChanged();
}
#Override
public int getCount() {
return mMessages.size();
}
#Override
public Object getItem(int i) {
return mMessages.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int i) {
return mMessages.get(i).second;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
int direction = getItemViewType(i);
if (convertView == null) {
if (direction == DIRECTION_INCOMING) {
res = R.layout.message_right;
} else if (direction == DIRECTION_OUTGOING) {
res = R.layout.message_left;
}
convertView = mInflater.inflate(res, viewGroup, false);
}
Message message = mMessages.get(i).first;
String name = message.getHeaders().get("Name");
if (direction == DIRECTION_INCOMING) {
photo_url = message.getHeaders().get("imageUrl");
} else if (direction == DIRECTION_OUTGOING) {
photo_url = StaticInfo.getSavedData("photo", context);
}
CircleImageView photo = convertView.findViewById(R.id.pic);
Picasso.with(context).load(photo_url).into(photo);
TextView txtSender = convertView.findViewById(R.id.txtSender);
TextView txtMessage = convertView.findViewById(R.id.txtMessage);
TextView txtDate = convertView.findViewById(R.id.txtDate);
txtSender.setText(name);
txtMessage.setText(message.getTextBody());
txtDate.setText(mFormatter.format(message.getTimestamp()));
return convertView;
}
}

Android - Xamarin - Fused Location

I am trying to implement a custom activity that initialises the Fused Location services in Xamarin c# so I can reuse this activity whenever the Fused Location is needed. The problem that I am having is that the map is being loaded before the location services. This way, I cannot animate the camera to zoom in at the user's location since the location is still null.
Here is the custom activity:
using System;
using Android.App;
using Android.Gms.Common;
using Android.Gms.Common.Apis;
using Android.Gms.Maps.Model;
using Android.Locations;
using Android.OS;
using Android.Gms.Location;
using Android.Widget;
namespace Maps.Droid.LocationService {
public class LocationTrackerActivity : Activity, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener, Android.Gms.Location.ILocationListener {
// Static Fields
public static long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 5 meters
public static long MIN_TIME_BW_UPDATES = 1000 * 10; // 10 seconds
private Location currentLocation;
private Activity activity;
private bool hasGooglePlayServices;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private bool locationAvailable = false;
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
this.activity = this;
hasGooglePlayServices = checkPlayServices();
if (hasGooglePlayServices) {
initFusedLocation();
} else {
initAndroidLocation();
}
}
private void initFusedLocation() {
mLocationRequest = new LocationRequest();
mLocationRequest.SetInterval(LocationTrackerActivity.MIN_TIME_BW_UPDATES);
mLocationRequest.SetFastestInterval(LocationTrackerActivity.MIN_TIME_BW_UPDATES / 2);
mLocationRequest.SetSmallestDisplacement(LocationTrackerActivity.MIN_DISTANCE_CHANGE_FOR_UPDATES);
mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
mGoogleApiClient = new GoogleApiClient.Builder(Application.Context)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(this)
.AddApi(LocationServices.API)
.Build();
}
protected override void OnResume() {
base.OnResume();
if (mGoogleApiClient.IsConnected) {
LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
protected override void OnPause() {
base.OnPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.IsConnected) {
LocationServices.FusedLocationApi.RemoveLocationUpdates(mGoogleApiClient, this);
}
}
protected override void OnStart() {
base.OnStart();
mGoogleApiClient.Connect();
}
protected override void OnStop() {
base.OnStop();
// only stop if it's connected, otherwise we crash
if (mGoogleApiClient != null) {
mGoogleApiClient.Disconnect();
}
}
private void initAndroidLocation() {
}
private bool checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.Instance;
int resultCode = apiAvailability.IsGooglePlayServicesAvailable(activity);
if (resultCode != ConnectionResult.Success) {
// In case we want to tell the user to install or update Google Play Services
//if (apiAvailability.IsUserResolvableError(resultCode)) {
// apiAvailability.GetErrorDialog(activity, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).Show();
//} else {
// Toast.MakeText(activity, "This device is not supported", ToastLength.Long).Show();
//}
return false;
}
return true; // has google play services installed
}
public double getLatitude() {
return currentLocation == null ? 0.0 : currentLocation.Latitude;
}
public double getLongitude() {
return currentLocation == null ? 0.0 : currentLocation.Longitude;
}
public bool canGetLocation() {
return locationAvailable;
}
public LatLng getLatLng() {
return new LatLng(currentLocation.Latitude, currentLocation.Longitude);
}
public void OnConnected(Bundle connectionHint) {
// Get last known recent location. If the user launches the activity,
// moves to a new location, and then changes the device orientation, the original location
// is displayed as the activity is re-created.
if (currentLocation == null && mGoogleApiClient.IsConnected) {
currentLocation = LocationServices.FusedLocationApi.GetLastLocation(mGoogleApiClient);
}
Console.WriteLine("location is about to be set to true");
locationAvailable = true;
LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
public void OnConnectionSuspended(int cause) {
// GoogleApiClient will automatically attempt to restore the connection.
// Applications should disable UI components that require the service, and wait for a call to onConnected(Bundle) to re-enable them
if (cause == GoogleApiClient.ConnectionCallbacks.CauseServiceDisconnected) {
Toast.MakeText(activity, "Location Services disconnected. Please re-connect.", ToastLength.Long).Show();
} else if (cause == GoogleApiClient.ConnectionCallbacks.CauseNetworkLost) {
Toast.MakeText(activity, "Network lost. Please re-connect.", ToastLength.Long).Show();
}
}
public void OnConnectionFailed(ConnectionResult result) {
Console.WriteLine("Connection failed: " + result.ToString());
}
public void OnLocationChanged(Location location) {
currentLocation = location;
}
}
}
Here is the class that inherit the custom class:
using Android.App;
using Android.OS;
using Maps.Droid.LocationService;
namespace Maps.Droid {
[Activity(Label = "Map Activity")]
public class MapActivity : LocationTrackerActivity {
// Properties
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.map_activity);
var mapFrag = new MapViewFragment();
var ft = FragmentManager.BeginTransaction();
ft.Add(Resource.Id.map_container, mapFrag);
ft.Commit();
}
}
}
Here is the fragment in the inherited activity:
using System;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Gms.Maps;
namespace Maps.Droid {
public class MapViewFragment : Fragment, IOnMapReadyCallback {
// private Activity activity;
private GoogleMap map;
private MapActivity parent;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.Inflate(Resource.Layout.map_fragment, null);
parent = ((MapActivity)Activity);
MapFragment frag = this.FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
frag.GetMapAsync(this);
return view;
}
public void OnMapReady(GoogleMap googleMap) {
if (googleMap != null) {
map = googleMap;
var zoomVariance = 0.2;
var defaultZoom = 16f;
var currentZoomLevel = map.CameraPosition.Zoom;
map.MapType = GoogleMap.MapTypeNormal;
map.MyLocationEnabled = true;
map.CameraChange += delegate (object sender, GoogleMap.CameraChangeEventArgs e) {
if (Math.Abs(e.Position.Zoom - currentZoomLevel) < zoomVariance) {
return;
}
currentZoomLevel = e.Position.Zoom;
Console.WriteLine("Zooming " + currentZoomLevel);
};
map.UiSettings.ZoomControlsEnabled = true;
map.UiSettings.CompassEnabled = true;
map.UiSettings.SetAllGesturesEnabled(true); // Zoom, Tilt, Scroll, Rotate
if (parent.canGetLocation()) {
// ***** PROBLEM HERE ******* canGetLocation is set to true just afterwards.
map.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(parent.getLatLng(), defaultZoom)); // Mosaic coordinates
}
}
}
}
}
I was thinking of implementing a call back to LocationTrackerActivity. So when the location services become available the class MapActivity then would be able to load the MapViewFragment within that custom callback. This way the location services would be loaded before the map. Therefore, this part of the code would always execute :
if (parent.canGetLocation()) {
// ***** PROBLEM HERE ******* canGetLocation is set to true just afterwards.
map.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(parent.getLatLng(), defaultZoom)); // Mosaic coordinates
}
However I have no idea how to customise a callback. Maybe there are better solutions to this problem?
The problem can be because of OnConnected method. That's my OnConnected method for FusedLocationProvider in Xamarin. You can take a look on it.
public async void OnConnected(Bundle bundle)
{
Location location = LocationServices.FusedLocationApi.GetLastLocation(apiClient);
if (location != null)
{
latitude = location.Latitude;
longitude = location.Longitude;
locRequest.SetPriority(100);
locRequest.SetFastestInterval(500);
locRequest.SetInterval(1000);
await LocationServices.FusedLocationApi.RequestLocationUpdates(apiClient, locRequest, this);
}
}
When it is connected, i set the latitude and longitude values. Then in my onMapReady method, i create a new LatLng variable with these latitude and longitude variables.
void IOnMapReadyCallback.OnMapReady(GoogleMap myMap)
{
this.myMap = myMap;
myMarker = new MarkerOptions();
locCoordinates = new LatLng(latitude, longitude);
myMap.MapType = GoogleMap.MapTypeNormal;
myMap.UiSettings.ZoomControlsEnabled = true;
myMap.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(locCoordinates, 10));
}
UPDATE:
I have managed to find a solution. If the user has google play services then use FusedLocation Services, if the user does not then we use Android Location Services. Then we only have to interact with one object of the type LocationTracker and everything is done by this interface:
namespace Maps.Droid.LocationService {
public interface LocationInterface {
void startLocationServices();
void stopLocationServices();
void pauseLocationServices();
void resumeLocationServices();
double getLatitude();
double getLongitude();
bool canGetLocation();
}
}
using System;
using Android.App;
using Android.Gms.Location;
using Android.Gms.Common.Apis;
using Android.OS;
using Android.Gms.Maps.Model;
using Android.Widget;
using Android.Locations;
using Android.Gms.Common;
using Android.Gms.Maps;
namespace Maps.Droid.LocationService {
public class FusedLocation : Java.Lang.Object, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener, Android.Gms.Location.ILocationListener {
private Activity activity;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location currentLocation;
private bool locationAvailable = false;
private GoogleMap map;
public FusedLocation(Activity activity) {
this.activity = activity;
mLocationRequest = new LocationRequest();
mLocationRequest.SetInterval(LocationTracker.MIN_TIME_BW_UPDATES);
mLocationRequest.SetFastestInterval(LocationTracker.MIN_TIME_BW_UPDATES / 2);
mLocationRequest.SetSmallestDisplacement(LocationTracker.MIN_DISTANCE_CHANGE_FOR_UPDATES);
mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
mGoogleApiClient = new GoogleApiClient.Builder(Application.Context)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(this)
.AddApi(LocationServices.API)
.Build();
}
public Location getCurrentLocation() {
return currentLocation;
}
public void setMap(GoogleMap map) {
this.map = map;
}
public double getLatitude() {
return currentLocation.Latitude;
}
public double getLongitude() {
return currentLocation.Longitude;
}
public void OnResume() {
if (mGoogleApiClient.IsConnected) {
LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
public void OnPause() {
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.IsConnected) {
LocationServices.FusedLocationApi.RemoveLocationUpdates(mGoogleApiClient, this);
}
}
public void OnStart() {
mGoogleApiClient?.Connect();
}
public void OnStop() {
// only stop if it's connected, otherwise we crash
if (mGoogleApiClient.IsConnected) {
mGoogleApiClient?.Disconnect();
}
}
public LatLng getLatLng() {
return new LatLng(currentLocation.Latitude, currentLocation.Longitude);
}
public bool canGetLocation() {
return locationAvailable && currentLocation != null;
}
public void OnConnected(Bundle connectionHint) {
// Get last known recent location. If the user launches the activity,
// moves to a new location, and then changes the device orientation, the original location
// is displayed as the activity is re-created.
currentLocation = LocationServices.FusedLocationApi.GetLastLocation(mGoogleApiClient);
if (currentLocation != null) {
locationAvailable = true;
LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (map != null) {
map.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(getLatLng(), LocationTracker.DEFAULT_ZOOM));
}
}
}
public void OnConnectionSuspended(int cause) {
// GoogleApiClient will automatically attempt to restore the connection.
// Applications should disable UI components that require the service, and wait for a call to onConnected(Bundle) to re-enable them
if (cause == GoogleApiClient.ConnectionCallbacks.CauseServiceDisconnected) {
Toast.MakeText(activity, "Location Services disconnected. Please re-connect.", ToastLength.Long).Show();
} else if (cause == GoogleApiClient.ConnectionCallbacks.CauseNetworkLost) {
Toast.MakeText(activity, "Network lost. Please re-connect.", ToastLength.Long).Show();
}
}
public void OnLocationChanged(Location location) {
currentLocation = location;
}
public void OnConnectionFailed(ConnectionResult result) {
Console.WriteLine("Connection failed: " + result.ToString());
}
}
}
using System;
using Android.OS;
using Android.Locations;
using Android.Runtime;
using Android.App;
using Android.Content;
using Android.Widget;
using Android.Gms.Maps.Model;
using Java.Util.Concurrent;
namespace Maps.Droid.LocationService {
public class AndroidLocation : Java.Lang.Object, ILocationListener {
// Properties
private LocationManager locMgr;
private Activity activity;
private Location locationGPS, locationNetwork/*, locationPassive*/, currentLocation;
private bool locationAvailable = false;
private Android.Gms.Maps.GoogleMap map;
// UNCOMMNET
// private bool isPassiveEnabled = false; // Gets location from other apps that uses Location Services
// Initializer method (Constructor). Call this method onCreate
public AndroidLocation(Activity activity) {
this.activity = activity;
getLocation();
}
public Location getCurrentLocation() {
return currentLocation;
}
public void setMap(Android.Gms.Maps.GoogleMap map) {
this.map = map;
}
private Location getLocation() {
// Use Standard Android Location Service Provider
try {
locMgr = activity.GetSystemService(Context.LocationService) as LocationManager;
bool isGPSEnabled = locMgr.IsProviderEnabled(LocationManager.GpsProvider);
// Varying precision, Less power consuming. Combination of WiFi and Cellular data
bool isNetworkEnabled = locMgr.IsProviderEnabled(LocationManager.NetworkProvider);
// UNCOMMENT
// bool isPassiveEnabled = locMgr.IsProviderEnabled(LocationManager.GpsProvider);
// UNCOMMNET
//if (isPassiveEnabled) {
// locMgr.RequestLocationUpdates(LocationManager.PassiveProvider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
// locationPassive = locMgr.GetLastKnownLocation(LocationManager.PassiveProvider);
//}
if (isGPSEnabled) {
locMgr.RequestLocationUpdates(LocationManager.GpsProvider, LocationTracker.MIN_TIME_BW_UPDATES, LocationTracker.MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
locationGPS = locMgr?.GetLastKnownLocation(LocationManager.GpsProvider);
}
if (isNetworkEnabled) {
locMgr.RequestLocationUpdates(LocationManager.NetworkProvider, LocationTracker.MIN_TIME_BW_UPDATES, LocationTracker.MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
locationNetwork = locMgr?.GetLastKnownLocation(LocationManager.NetworkProvider);
}
// UNCOMMENT - Method must be implement if PassiveLocation is to be used
// currentLocation = getBestLocation(locationGPS, locationNetwork, locationPassive);
currentLocation = getBestLocation(locationNetwork, locationGPS);
if (currentLocation != null) {
locationAvailable = true;
if (map != null) {
map.AnimateCamera(Android.Gms.Maps.CameraUpdateFactory.NewLatLngZoom(getLatLng(), LocationTracker.DEFAULT_ZOOM));
}
}
} catch (Exception e) {
Console.WriteLine("ERROR: getLocation() " + e.ToString());
}
return currentLocation;
}
// Determines the most recent and/or most accurate location
private Location getBestLocation(Location loc1, Location loc2) {
if (loc1 == null || loc2 == null) {
return loc1 ?? loc2; // If either location is null then return the not null location
}
long time1 = TimeUnit.Milliseconds.ToSeconds(loc1.Time);
long time2 = TimeUnit.Milliseconds.ToSeconds(loc2.Time);
long twiceUpdate = (LocationTracker.MIN_TIME_BW_UPDATES / 1000) * 2;
if (Math.Abs(time1 - time2) > twiceUpdate) { // If location times are more than twiceUpdate apart
if (time1 > time2) { // More time value, most current time
return loc1;
} else {
return loc2;
}
} else {
float accuracy1 = loc1.Accuracy;
float accuracy2 = loc2.Accuracy;
// Smaller the value (meters), the greater the accuracy
if (accuracy1 < accuracy2) {
return loc1;
} else {
return loc2;
}
}
}
public void OnStop() {
locMgr = null;
}
public void OnPause() {
locMgr?.RemoveUpdates(this);
}
public void OnStart() {
}
public void OnResume() {
if (locMgr == null || currentLocation == null) {
getLocation();
}
}
public bool canGetLocation() {
return locationAvailable;
}
public LatLng getLatLng() {
return new LatLng(currentLocation.Latitude, currentLocation.Longitude);
}
public double getLatitude() {
return currentLocation.Latitude;
}
public double getLongitude() {
return currentLocation.Longitude;
}
public void OnLocationChanged(Location location) {
currentLocation = getBestLocation(currentLocation, location);
}
// User disabled a provider
public void OnProviderDisabled(string provider) {
getLocation(); // Check if all providers are disabled and pop up alertDialog if they are so
}
// User enabled a provider
public void OnProviderEnabled(string provider) {
getLocation(); // Update all available providers for getting the best provider available
}
public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras) {
}
}
}
using Android.App;
using Android.Gms.Common;
using Android.Gms.Common.Apis;
using Android.Gms.Maps.Model;
using Android.Gms.Maps;
using Android.Locations;
using Android.Content;
using Android.Widget;
namespace Maps.Droid.LocationService {
public class LocationTracker {
public static long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 5 meters
public static long MIN_TIME_BW_UPDATES = 1000 * 15; // 15 seconds ok, 5 seconds really fast, 30s slow
public static float DEFAULT_ZOOM = 16f;
private bool hasGooglePlayServices;
public GoogleApiClient mGoogleApiClient;
private FusedLocation fusedLocation;
private AndroidLocation androidLocation;
private bool locationIsDisabled;
public LocationTracker(Activity activity) {
if (locationIsDisabled = isLocationDisabled(activity)) {
showSettingsAlert(activity);
} else {
hasGooglePlayServices = checkPlayServices(activity);
if (hasGooglePlayServices) {
fusedLocation = new FusedLocation(activity);
} else {
androidLocation = new AndroidLocation(activity);
}
}
}
private void showSettingsAlert(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.SetTitle("Location Services Not Active");
builder.SetMessage("Please enable Location Services and GPS");
builder.SetPositiveButton("OK", delegate {
// Show location settings when the user acknowledges the alert dialog
var intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
activity.StartActivity(intent);
});
builder.SetNegativeButton("Cancel", delegate {
Toast.MakeText(activity, "Location disabled by user", ToastLength.Short).Show();
});
AlertDialog alertDialog = builder.Create();
alertDialog.SetCanceledOnTouchOutside(false);
alertDialog.Show();
}
private bool isLocationDisabled(Activity activity) {
LocationManager locMgr = activity.GetSystemService(Context.LocationService) as LocationManager;
// More precise, More power consuming
bool isGPSEnabled = locMgr.IsProviderEnabled(LocationManager.GpsProvider);
// Varying precision, Less power consuming. Combination of WiFi and Cellular data
bool isNetworkEnabled = locMgr.IsProviderEnabled(LocationManager.NetworkProvider);
// UNCOMMENT
// bool isPassiveEnabled = locMgr.IsProviderEnabled(LocationManager.PassiveProvider);
// UNCOMMENT
// return !isGPSEnabled && !isNetworkEnabled && !isPassiveEnabled; // True only when the 3 location services are disabled
return !isGPSEnabled && !isNetworkEnabled; // True only when both location services are disabled
}
// Call this method at OnMapReady callback if initial zooming/animation on user's location is desired
public void setMap(GoogleMap map) {
if (locationIsDisabled) {
return;
}
if (hasGooglePlayServices) {
fusedLocation.setMap(map);
} else {
androidLocation.setMap(map);
}
}
public void OnResume() {
if (locationIsDisabled) {
return;
}
if (hasGooglePlayServices) {
fusedLocation.OnResume();
} else {
androidLocation.OnResume();
}
}
public void OnPause() {
if (locationIsDisabled) {
return;
}
if (hasGooglePlayServices) {
fusedLocation.OnPause();
} else {
androidLocation.OnPause();
}
}
public void OnStart() {
if (locationIsDisabled) {
return;
}
if (hasGooglePlayServices) {
fusedLocation.OnStart();
} else {
androidLocation.OnStart();
}
}
public void OnStop() {
if (locationIsDisabled) {
return;
}
if (hasGooglePlayServices) {
fusedLocation.OnStop();
} else {
androidLocation.OnStop();
}
}
private bool checkPlayServices(Activity activity) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.Instance;
int resultCode = apiAvailability.IsGooglePlayServicesAvailable(activity);
if (resultCode == ConnectionResult.Success) {
return true;
}
return false;
}
public double getLatitude() {
if (locationIsDisabled) {
return 0;
}
if (hasGooglePlayServices) {
return fusedLocation.getCurrentLocation() == null ? 0.0 : fusedLocation.getLatitude();
} else {
return androidLocation.getCurrentLocation() == null ? 0.0 : androidLocation.getLatitude();
}
}
public double getLongitude() {
if (locationIsDisabled) {
return 0;
}
if (hasGooglePlayServices) {
return fusedLocation.getCurrentLocation() == null ? 0.0 : fusedLocation.getLongitude();
} else {
return androidLocation.getCurrentLocation() == null ? 0.0 : androidLocation.getLongitude();
}
}
public bool canGetLocation() {
if (locationIsDisabled) {
return false;
}
if (hasGooglePlayServices) {
return fusedLocation.canGetLocation();
} else {
return androidLocation.canGetLocation();
}
}
public LatLng getLatLng() {
if (locationIsDisabled) {
return null;
}
LatLng latlng;
if (hasGooglePlayServices) {
latlng = fusedLocation.getLatLng();
} else {
latlng = androidLocation.getLatLng();
}
return latlng;
}
public Location getCurrentLocation() {
if (hasGooglePlayServices) {
return fusedLocation.getCurrentLocation();
} else {
return androidLocation.getCurrentLocation();
}
}
}
}
Then to use it on your fragment or activity:
Initialise it at OnCreate:
Location tracker = new LocationTracker(this.Activity);
make a referent for the life cycles:
public override void OnResume() {
base.OnResume();
tracker.OnResume();
}
public override void OnPause() {
base.OnPause();
tracker.OnPause();
}
public override void OnStart() {
base.OnStart();
tracker.OnStart();
}
public override void OnStop() {
base.OnStop();
tracker.OnStop();
}
if you want the animation to zoom at the users location in the beginning, then you have to add this line of code when you have the googlemap:
tracker.setMap(googleMap); // Invoke this method if zooming/animating to the user's location is desired
Spent many days on this solution. Hope it can help somebody!

TableView, setting editable cells

I try to make Table cells editable. I managed to do this with two Collumns that have String values in it, but I cant make this with columns that represent Integer values.
Places with X is where compiler get the error:
The method setCellFactory(Callback<TableColumn<DataModel,Integer>,TableCell<DataModel,Integer>>) in the type TableColumn<DataModel,Integer> is not applicable for the arguments (Callback<TableColumn<DataModel,String>,TableCell<DataModel,String>>)
and places with XX is where compiler get the error:
The method setOnEditCommit(EventHandler<TableColumn.CellEditEvent<DataModel,Integer>>) in the type TableColumn<DataModel,Integer> is not applicable for the arguments ((CellEditEvent<DataModel, Integer> event) -> {})
Heres the code:
public void initialize(URL location, ResourceBundle resources) {
//Tworzymy sobie kolumny, które będą odpowiadać oraz przyjmować konretne dane
TableColumn<DataModel, String> nameColumn = new TableColumn<DataModel, String>("Name");
nameColumn.setMinWidth(100);
TableColumn<DataModel, String> surnameColumn = new TableColumn<DataModel, String>("Surname");
surnameColumn.setMinWidth(100);
TableColumn<DataModel, Integer> ageColumn = new TableColumn<DataModel, Integer>("Age");
ageColumn.setMinWidth(100);
TableColumn<DataModel, Integer> telNumberColumn = new TableColumn<DataModel, Integer>("Tel. Number");
telNumberColumn.setMinWidth(100);
//dodajemy kolumny do okna
tableView.getColumns().addAll(nameColumn,surnameColumn,ageColumn,telNumberColumn);
//podajemy nazwy zmiennych, których wartości mają się wyświetlać w poszczególnych kolumnach
nameColumn.setCellValueFactory(new PropertyValueFactory<>("sName"));
surnameColumn.setCellValueFactory(new PropertyValueFactory<>("sSurname"));
ageColumn.setCellValueFactory(new PropertyValueFactory<>("iAge"));
telNumberColumn.setCellValueFactory(new PropertyValueFactory<>("iPhoneNumber"));
//Sprawiamy że poszczególne kolumny stają się edytowalne
nameColumn.setCellFactory(TextFieldTableCell.<DataModel>forTableColumn());
nameColumn.setOnEditCommit((CellEditEvent<DataModel, String> event) -> {
((DataModel) event.getTableView().getItems(). get(event.getTablePosition().getRow())). setsName(event.getNewValue());
});
surnameColumn.setCellFactory(TextFieldTableCell.<DataModel>forTableColumn());
surnameColumn.setOnEditCommit((CellEditEvent<DataModel, String> event) -> {
((DataModel) event.getTableView().getItems(). get(event.getTablePosition().getRow())). setsSurname(event.getNewValue());
});
X ageColumn.setCellFactory(TextFieldTableCell.<DataModel>forTableColumn());
XX ageColumn.setOnEditCommit((CellEditEvent<DataModel, Integer> event) -> {
// ((DataModel) event.getTableView().getItems(). get(event.getTablePosition().getRow())). setiAge(Integer.valueOf(event.getNewValue()));
});
X telNumberColumn.setCellFactory(TextFieldTableCell.<DataModel>forTableColumn());
XX telNumberColumn.setOnEditCommit((CellEditEvent<DataModel, Integer> event) -> {
// ((DataModel) event.getTableView().getItems(). get(event.getTablePosition().getRow())). setiPhoneNumber(Integer.valueOf(event.getNewValue()));
});
tableView.setPlaceholder(new Label("Pust tabelka!"));//jaki element dodać jeśli tabelka nie jest wyświetlona
tableView.setEditable(true);
tableView.setItems(dataList); //wczytujemy dane do przygotowanej tabelki
buttAdd.setOnAction((ActionEvent e) -> {
buttAddAction(e);
});
}
Im taking oracle TableView tutorial, and its quite difficult. Help.
The issue is that TextFieldTableCell.forTableColumn() is typed to a String value. See the default implementation:
public static <S> Callback<TableColumn<S,String>, TableCell<S,String>> forTableColumn() {
return forTableColumn(new DefaultStringConverter());
}
What you need is the TextFieldTableCell with an IntegerStringConverter, for example:
ageColumn.setCellFactory(TextFieldTableCell.<DataModel, Integer>forTableColumn(new IntegerStringConverter()));
I searched through a lot of answers and I've borrowed/extended/merged to this solution. Edits are committed when focus moves from edited cell. I have a public class for each datatype that can be represented in a table: EditingTextCell, EditingIntegerCell etc. These public classes can be applied to any table provided that the data is represented as an observable list of a class that accesses the data to be displayed as properties. I publish this solution because I was faced with creating a class for each column of each table in my application. Currently, the double value and combobox cell versions are tied to specific columns of specific tables. I'll do a generalized version of these as time permits. Please forgive my not presenting the source links -- I forgot to bookmark them as I perused them.
Java documentation suggests that easier ways of doing this are forthcoming.
Example usage for Integer field:
TableColumn<Factor, Number> noLevelsCol =
new TableColumn<>("No. Levels");
noLevelsCol.setCellValueFactory(
new PropertyValueFactory("numberLevels"));
noLevelsCol.setMinWidth(40);
noLevelsCol.setCellFactory(col -> new EditingIntegerCell<>());
noLevelsCol.setOnEditCommit((CellEditEvent<Factor, Number> t) -> {
((Factor) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setNumberLevels(t.getNewValue().intValue());
});
Example usage for String field:
TableColumn<Factor, String> nameCol = new TableColumn<>("Name");
nameCol.setMinWidth(60);
nameCol.setCellValueFactory(
new PropertyValueFactory("factorName"));
nameCol.setCellFactory(cellFactory);
nameCol.setOnEditCommit((CellEditEvent<Factor, String> t) -> {
((Factor) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setFactorName(t.getNewValue());
});
Definition of Factor class:
public class Factor {
private final IntegerProperty factorID = new SimpleIntegerProperty();
public IntegerProperty getFactorID() { return factorID; }
private StringProperty factorName = new SimpleStringProperty();
public void setFactorName(String value) {
factorNameProperty().set(value); }
public String getFactorName() { return factorNameProperty().get(); }
public StringProperty factorNameProperty() {
if (factorName == null) factorName =
new SimpleStringProperty(this, "factorName");
return factorName;
}
private IntegerProperty numberLevels = new SimpleIntegerProperty();
public void setNumberLevels(int value) {
numberLevelsProperty().set(value); }
public IntegerProperty getNumberLevels() { return numberLevels; }
public IntegerProperty numberLevelsProperty() {
if (numberLevels == null) numberLevels =
new SimpleIntegerProperty(this, "numberLevels");
return numberLevels;
}
private StringProperty listOfLevels = new SimpleStringProperty();
public void setListOfLevels(String value) {
listOfLevelsProperty().set(value); }
public String getListOfLevels() { return listOfLevelsProperty().get(); }
public StringProperty listOfLevelsProperty() {
if (listOfLevels == null) listOfLevels =
new SimpleStringProperty(this, "listOfLevels");
return listOfLevels;
}
// Constructors
public Factor(int factorID, String factorName) {
this.factorID.set(factorID);
this.factorName.set(factorName);
this.numberLevels.set(1);
this.listOfLevels.set("-1, 1");
}
public Factor(int factorID, String factorName, int numberLevels,
String listOfLevels) {
this.factorID.set(factorID);
this.factorName.set(factorName);
this.numberLevels.set(numberLevels);
this.listOfLevels.set(listOfLevels);
}
#Override
public String toString() {
return "Factor{" + "factorName=" + factorName + '}';
}
public String[] getLevels() {
return listOfLevels.getValue().split(",");
}
}
Loading the data into the table
final ObservableList factorList =
FXCollections.observableArrayList(
new Factor(1, "Factor1", 2, "-1, 1")
);
factorTableView.setEditable(true);
factorTableView.getColumns().clear();
factorTableView.setItems(factorList);
boolean addAll;
addAll = factorTableView.getColumns().addAll(idCol,
nameCol, noLevelsCol, levelsCol);
The EditingIntegerCell class
public class EditingIntegerCell extends TableCell {
private TextField textField;
private final Pattern intPattern = Pattern.compile("-?\\d+");
public EditingIntegerCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem().toString());
setGraphic(null);
}
#Override
public void updateItem(Number item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2)
-> {
if (!arg2) {
processEdit();
}
});
}
private void processEdit() {
String text = textField.getText();
if (intPattern.matcher(text).matches()) {
commitEdit(Integer.parseInt(text));
} else {
cancelEdit();
}
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
** The EditingTextCell class **
public class EditingTextCell extends TableCell {
private TextField textField;
public EditingTextCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2)
-> {
if (!arg2) {
commitEdit(textField.getText());
}
});
}
private String getString() {
return getItem() == null ? "" : getItem();
}
}

Silverlight Datagrid Validation on End Edit

I need to do validation on a grid column. all the cells in that column are blank. the user needs to input data and then i need to validate it.
I have at the moment the validation on the cells working but it works on Begin Edit event instead of the end edit event. which is pointless as the validation needs to check if they have entered information.
How can i get the validation to validate on the end edit Event?
Thank in advance for your help
Niven.
Code:
private string _reference;
public string Reference
{
get
{
return _reference;
}
set
{
_reference = value;
ChangeValue("Reference");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void ChangeValue(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public string this[string columnName]
{
get
{
string msg = null;
if (columnName == "Reference")
{
if (Reference == "" && ValidateItem)
{
msg = "Reference is Required. Please Enter a Reference";
}
}
return msg;
}
}
string err;
public string Error
{
get { return err; }
}
I've just solved this behavior with the custom code below. I didn't have time to test all scenarios yet, but I'm pretty confident with the results.
public class ExtendedDataGrid : DataGrid {
private ValidationSummary _validationSummary = null;
private bool _validationFilterBehaviorApplied = false;
private bool _validationFilterBehaviorRestored = false;
public ExtendedDataGrid() { }
public override void OnApplyTemplate() {
base.OnApplyTemplate();
this._validationSummary = (ValidationSummary)this.GetTemplateChild("ValidationSummary");
}
protected override void OnBeginningEdit(DataGridBeginningEditEventArgs e) {
if (!_validationFilterBehaviorApplied) {
_validationSummary.Filter = ValidationSummaryFilters.None;
_validationFilterBehaviorApplied = true;
}
base.OnBeginningEdit(e);
}
protected override void OnRowEditEnding(DataGridRowEditEndingEventArgs e) {
if (_validationFilterBehaviorApplied && !_validationFilterBehaviorRestored) {
_validationSummary.Filter = ValidationSummaryFilters.All;
_validationFilterBehaviorRestored = true;
}
base.OnRowEditEnding(e);
}
protected override void OnRowEditEnded(DataGridRowEditEndedEventArgs e) {
_validationFilterBehaviorApplied = false;
_validationFilterBehaviorRestored = false;
base.OnRowEditEnded(e);
}
}

Resources