i ma making AutoCompleteTextView in my adapter for which when i make object of PlaceAutocompleteAdapter when i pass GoogleApiClient object as second parameter to my PlaceAutocompleteAdapter it gives me red error and sys to pass GEODataClient object instead of GoogleApiClient
while the code for my Fragment containing map is this
package com.example.anonymous.ghar_ka_khana;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import android.Manifest;
import android.widget.AutoCompleteTextView;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor;
public class GoogleFragment extends Fragment implements OnMapReadyCallback,LocationListener,GoogleApiClient.OnConnectionFailedListener {
private MapFragment m;
private GoogleMap mMap;
FusedLocationProviderClient fusedLocationProviderClient;
private int REQUEST_PERMISSIONS_REQUEST_CODE = 125;
protected Location mLastLocation;
private AutoCompleteTextView autoCompleteTextView;
private PlaceAutocompleteAdapter autocompleteAdapter;
private String mLatitiudelabel;
private String mLongitudelabel;
private GoogleApiClient mGoogleApiClient;
private static LatLngBounds Lat_Long_Bounds = new LatLngBounds(new LatLng(-40,-168),new LatLng(71,136));
View v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.i("pahlywala", "onCreateView");
v = inflater.inflate(R.layout.fragment_google, container, false);
mGoogleApiClient = new GoogleApiClient
.Builder(getActivity())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(new DrawerActivity(), this)
.build();
autoCompleteTextView = (AutoCompleteTextView)v.findViewById(R.id.mapsearch);
autocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(),mGoogleApiClient,Lat_Long_Bounds,null);
autoCompleteTextView.setAdapter(autocompleteAdapter);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLatitiudelabel = "Latitude";
mLongitudelabel = "Longitude";
FragmentManager fragmentManager = getActivity().getFragmentManager();
final MapFragment myMapFragment = (MapFragment) fragmentManager.findFragmentById(R.id.googlemap);
myMapFragment.getMapAsync(this);
Log.i("pahlywalass", "onViewCreated");
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap=googleMap;
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker"));
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStart() {
super.onStart();
if (!checkPermissions()) {
requestPermissions();
} else {
getLastLocation();
}
}
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION);
// Provide an additional rationale to the user. This would happen if the user denied the
// request previously, but didn't check the "Don't ask again" checkbox.
if (shouldProvideRationale) {
Log.i("displaying permission", "Displaying permission rationale to provide additional context.");
/* showSnackbar("warning", android.R.string.ok,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
startLocationPermissionRequest();
}
});*/
} else {
Log.i("requesting permission", "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the user denied the permission
// previously and checked "Never ask again".
startLocationPermissionRequest();
}
}
private void startLocationPermissionRequest() {
ActivityCompat.requestPermissions(new DrawerActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i("onRequestPerm", "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i("onRequestPerm", "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
getLastLocation();
} else {
// Permission denied.
// Notify the user via a SnackBar that they have rejected a core permission for the
// app, which makes the Activity useless. In a real app, core permissions would
// typically be best requested during a welcome-screen flow.
// Additionally, it is important to remember that a permission might have been
// rejected without asking the user for permission (device policy or "Never ask
// again" prompts). Therefore, a user interface affordance is typically implemented
// when permissions are denied. Otherwise, your app could appear unresponsive to
// touches or interactions which have required permissions.
/*showSnackbar(R.string.textwarn, R.string.settings,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});*/
}
}
}
private void getLastLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationProviderClient.getLastLocation()
.addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mLastLocation = task.getResult();
Log.i("Longitutde", mLastLocation.getLongitude()+"");
Log.i("Longitutde", mLastLocation.getLatitude()+"");
LatLng cur_Latlng=new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()); // giving your marker to zoom to your location area.
mMap.addMarker(new MarkerOptions()
.position(cur_Latlng)
.title("umair"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(cur_Latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
/*String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();*/
Log.i("pat", ""+city);
}
else {
Log.i("getlasts", "getLastLocation:exception", task.getException());
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
while the code for PlaceAutoCompleteAdapter is following
package com.example.anonymous.ghar_ka_khana;
/**
* Created by Anonymous on 2/19/2018.
*/
import android.content.Context;
import android.graphics.Typeface;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.data.DataBufferUtils;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBufferResponse;
import com.google.android.gms.location.places.GeoDataClient;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.tasks.RuntimeExecutionException;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Adapter that handles Autocomplete requests from the Places Geo Data Client.
* {#link AutocompletePrediction} results from the API are frozen and stored directly in this
* adapter. (See {#link AutocompletePrediction#freeze()}.)
*/
public class PlaceAutocompleteAdapter
extends ArrayAdapter<AutocompletePrediction> implements Filterable {
private static final String TAG = "PlaceAutocompleteAd";
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
/**
* Current results returned by this adapter.
*/
private ArrayList<AutocompletePrediction> mResultList;
/**
* Handles autocomplete requests.
*/
private GeoDataClient mGeoDataClient;
/**
* The bounds used for Places Geo Data autocomplete API requests.
*/
private LatLngBounds mBounds;
/**
* The autocomplete filter used to restrict queries to a specific set of place types.
*/
private AutocompleteFilter mPlaceFilter;
/**
* Initializes with a resource for text rows and autocomplete query bounds.
*
* #see android.widget.ArrayAdapter#ArrayAdapter(android.content.Context, int)
*/
public PlaceAutocompleteAdapter(Context context, GeoDataClient geoDataClient,
LatLngBounds bounds, AutocompleteFilter filter) {
super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
mGeoDataClient = geoDataClient;
mBounds = bounds;
mPlaceFilter = filter;
}
/**
* Sets the bounds for all subsequent queries.
*/
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
/**
* Returns the number of results received in the last autocomplete query.
*/
#Override
public int getCount() {
return mResultList.size();
}
/**
* Returns an item from the last autocomplete query.
*/
#Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
// Sets the primary and secondary text for a row.
// Note that getPrimaryText() and getSecondaryText() return a CharSequence that may contain
// styling based on the given CharacterStyle.
AutocompletePrediction item = getItem(position);
TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
TextView textView2 = (TextView) row.findViewById(android.R.id.text2);
textView1.setText(item.getPrimaryText(STYLE_BOLD));
textView2.setText(item.getSecondaryText(STYLE_BOLD));
return row;
}
/**
* Returns the filter for the current set of autocomplete results.
*/
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We need a separate list to store the results, since
// this is run asynchronously.
ArrayList<AutocompletePrediction> filterData = new ArrayList<>();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
filterData = getAutocomplete(constraint);
}
results.values = filterData;
if (filterData != null) {
results.count = filterData.size();
} else {
results.count = 0;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
mResultList = (ArrayList<AutocompletePrediction>) results.values;
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
notifyDataSetInvalidated();
}
}
#Override
public CharSequence convertResultToString(Object resultValue) {
// Override this method to display a readable result in the AutocompleteTextView
// when clicked.
if (resultValue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultValue).getFullText(null);
} else {
return super.convertResultToString(resultValue);
}
}
};
}
/**
* Submits an autocomplete query to the Places Geo Data Autocomplete API.
* Results are returned as frozen AutocompletePrediction objects, ready to be cached.
* Returns an empty list if no results were found.
* Returns null if the API client is not available or the query did not complete
* successfully.
* This method MUST be called off the main UI thread, as it will block until data is returned
* from the API, which may include a network request.
*
* #param constraint Autocomplete query string
* #return Results from the autocomplete API or null if the query was not successful.
* #see GeoDataClient#getAutocompletePredictions(String, LatLngBounds, AutocompleteFilter)
* #see AutocompletePrediction#freeze()
*/
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
Log.i(TAG, "Starting autocomplete query for: " + constraint);
// Submit the query to the autocomplete API and retrieve a PendingResult that will
// contain the results when the query completes.
Task<AutocompletePredictionBufferResponse> results =
mGeoDataClient.getAutocompletePredictions(constraint.toString(), mBounds,
mPlaceFilter);
// This method should have been called off the main UI thread. Block and wait for at most
// 60s for a result from the API.
try {
Tasks.await(results, 60, TimeUnit.SECONDS);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
e.printStackTrace();
}
try {
AutocompletePredictionBufferResponse autocompletePredictions = results.getResult();
Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
// Freeze the results immutable representation that can be stored safely.
return DataBufferUtils.freezeAndClose(autocompletePredictions);
} catch (RuntimeExecutionException e) {
// If the query did not complete successfully return null
Toast.makeText(getContext(), "Error contacting API: " + e.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting autocomplete prediction API call", e);
return null;
}
}
}
my gradle file is following
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.anonymous.ghar_ka_khana"
minSdkVersion 17
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.firebase:firebase-database:11.8.0'
//11.0.4
implementation 'com.android.support:support-v4:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.google.android.gms:play-services:11.8.0'
implementation 'com.firebaseui:firebase-ui-auth:3.1.3'
// FirebaseUI for Firebase Auth
implementation 'com.firebaseui:firebase-ui-database:3.1.3'
// FirebaseUI for Firebase Realtime Database
implementation 'com.firebaseui:firebase-ui-firestore:3.1.3'
// FirebaseUI for Cloud Firestore
compile 'com.google.firebase:firebase-firestore:11.8.0'
//Firestore dependency
implementation 'com.firebaseui:firebase-ui-storage:3.1.3'
// FirebaseUI for Cloud Storage
implementation 'com.facebook.android:facebook-login:4.29.0'
// Required only if Facebook login support is required
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.github.florent37:materialtextfield:1.0.7'
compile 'com.scalified:fab:1.1.3'
compile 'com.google.firebase:firebase-storage:11.8.0'
compile 'com.google.firebase:firebase-auth:11.8.0'
compile 'com.github.glomadrian:Grav:1.1'
implementation('com.mikepenz:materialdrawer:6.0.6#aar') {
transitive = true
}
compile 'com.wdullaer:materialdatetimepicker:3.5.1'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.android.support:support-annotations:26.1.0'
implementation 'com.google.android.gms:play-services:11.8.0'
implementation 'com.google.android.gms:play-services-location:11.8.0'
}
apply plugin: 'com.google.gms.google-services'
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '26.1.0'
}
}
}
}
Ok. I've got the solution instead of using:
autocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(),mGoogleApiClient,Lat_Long_Bounds,null);
you will have to use:
autocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(),Places.getGeoDataClient(getActivity(), null),Lat_Long_Bounds,null);
Related
Hello keycloak extension experts,
I have enabled successfully the declarative user profile (https://www.keycloak.org/docs/latest/server_admin/#user-profile).
I would like now to "deploy" a custom-made validator. (KC 18.0 embedded wildfly)
I have trouble to understand how I need to package my validator to make it available in the admin console UI.
I did with maven a jar as for an eventListener extension spi (which used to work very fine) with a ProviderFactory and a Provider.
Yet, the validator is not proposed in the console UI as a validator. Deployment seems successful.
I wonder if my packaging is wrong or if there is an extra step required.
By the way I had a look to https://github.com/thomasdarimont/keycloak-extension-playground/blob/master/custom-user-profile-extension/src/main/java/com/github/thomasdarimont/keycloak/userprofile/validator/AgeValidator.java but here it lacks the packaging stage as far as I can see
You can find the code below. I duplicated the code for the out of the box LengthValidator.
org.keycloak.validate.ValidatorFactory
lu.lns.keycloak.custom.validator.LengthValidatorProviderFactory
LengthValidatorProviderFactory.java
package lu.lns.keycloak.custom.validator;
import org.keycloak.Config;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.validate.Validator;
import org.keycloak.validate.ValidatorFactory;
public class LengthValidatorProviderFactory implements ValidatorFactory {
#Override
public Validator create(KeycloakSession session) {
return new LengthValidatorProvider();
}
#Override
public void init(Config.Scope config) {
}
#Override
public void postInit(KeycloakSessionFactory factory) {
}
#Override
public String getId() {
return "lns-length-validator";
}
}
LengthValidatorProvider
package lu.lns.keycloak.custom.validator;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.keycloak.models.KeycloakSession;
import org.keycloak.provider.ConfiguredProvider;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.validate.AbstractStringValidator;
import org.keycloak.validate.ValidationContext;
import org.keycloak.validate.ValidationError;
import org.keycloak.validate.ValidationResult;
import org.keycloak.validate.ValidatorConfig;
import org.keycloak.validate.validators.ValidatorConfigValidator;
/**
* String value length validation - accepts plain string and collection of strings, for basic behavior like null/blank
* values handling and collections support see {#link AbstractStringValidator}. Validator trims String value before the
* length validation, can be disabled by {#link #KEY_TRIM_DISABLED} boolean configuration entry set to
* <code>true</code>.
* <p>
* Configuration have to be always provided, with at least one of {#link #KEY_MIN} and {#link #KEY_MAX}.
*/
public class LengthValidatorProvider extends AbstractStringValidator implements ConfiguredProvider {
public static final LengthValidatorProvider INSTANCE = new LengthValidatorProvider();
public static final String ID = "lns-length";
public static final String MESSAGE_INVALID_LENGTH = "LNS-error-invalid-length";
public static final String KEY_MIN = "min";
public static final String KEY_MAX = "max";
public static final String KEY_TRIM_DISABLED = "trim-disabled";
private static final List<ProviderConfigProperty> configProperties = new ArrayList<>();
static {
ProviderConfigProperty property;
property = new ProviderConfigProperty();
property.setName(KEY_MIN);
property.setLabel("Minimum length");
property.setHelpText("The minimum length");
property.setType(ProviderConfigProperty.STRING_TYPE);
configProperties.add(property);
property = new ProviderConfigProperty();
property.setName(KEY_MAX);
property.setLabel("Maximum length");
property.setHelpText("The maximum length");
property.setType(ProviderConfigProperty.STRING_TYPE);
configProperties.add(property);
}
#Override
public String getId() {
return ID;
}
#Override
protected void doValidate(String value, String inputHint, ValidationContext context, ValidatorConfig config) {
Integer min = config.getInt(KEY_MIN);
Integer max = config.getInt(KEY_MAX);
if (!config.getBooleanOrDefault(KEY_TRIM_DISABLED, Boolean.FALSE)) {
value = value.trim();
}
int length = value.length();
if (config.containsKey(KEY_MIN) && length < min.intValue()) {
context.addError(new ValidationError(ID, inputHint, MESSAGE_INVALID_LENGTH, min, max));
return;
}
if (config.containsKey(KEY_MAX) && length > max.intValue()) {
context.addError(new ValidationError(ID, inputHint, MESSAGE_INVALID_LENGTH, min, max));
return;
}
}
#Override
public ValidationResult validateConfig(KeycloakSession session, ValidatorConfig config) {
Set<ValidationError> errors = new LinkedHashSet<>();
if (config == null || config == ValidatorConfig.EMPTY) {
errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE));
errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE));
} else {
if (config.containsKey(KEY_TRIM_DISABLED) && (config.getBoolean(KEY_TRIM_DISABLED) == null)) {
errors.add(new ValidationError(ID, KEY_TRIM_DISABLED, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_BOOLEAN_VALUE, config.get(KEY_TRIM_DISABLED)));
}
boolean containsMin = config.containsKey(KEY_MIN);
boolean containsMax = config.containsKey(KEY_MAX);
if (!(containsMin || containsMax)) {
errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE));
errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_MISSING_VALUE));
} else {
if (containsMin && config.getInt(KEY_MIN) == null) {
errors.add(new ValidationError(ID, KEY_MIN, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, config.get(KEY_MIN)));
}
if (containsMax && config.getInt(KEY_MAX) == null) {
errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, config.get(KEY_MAX)));
}
if (errors.isEmpty() && containsMin && containsMax && (config.getInt(KEY_MIN) > config.getInt(KEY_MAX))) {
errors.add(new ValidationError(ID, KEY_MAX, ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_VALUE));
}
}
}
return new ValidationResult(errors);
}
#Override
public String getHelpText() {
return "LNS Length validator";
}
#Override
public List<ProviderConfigProperty> getConfigProperties() {
return configProperties;
}
}
NB: I cross-posted the same question into keycloak forum.
AbstractStringValidator implements both the Validator and ValidatorFactory. Therefore, you don't need to implement a separate factory for you custom SPI.
Also, the META-INF directory should have services as a subdirectory, not META-INF.services (this is probably why it isn't working).
If you remove the factory and put the LengthValidatorProvider in the META-INF file then it should work.
I am trying to use the datawedge intent API with my flutter application, on a Zebra android scanner. I started to use the Zebra EMDK API from a git repository, which works perfectly. Now I want to migrate it (which is recommended by Zebra) because I want it to be also available on mobiles (if it is possible).
I am trying to follow the instructions from this page and merge it with the code from the git repo, but no scan event is detected in my app.
Has someone already done this and could help me?
Here is my MainActivity.java:
package com.example.test_datawedge;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
// import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import io.flutter.plugins.GeneratedPluginRegistrant;
import java.util.ArrayList;
public class MainActivity extends FlutterActivity {
private static final String BARCODE_RECEIVED_CHANNEL = "samples.flutter.io/barcodereceived";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
// setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
// registerReceiver(myBroadcastReceiver, filter);
new EventChannel(getFlutterView(), BARCODE_RECEIVED_CHANNEL).setStreamHandler(
new StreamHandler() {
private BroadcastReceiver barcodeBroadcastReceiver;
#Override
public void onListen(Object arguments, EventSink events) {
Log.d("FLUTTERDEMO", "EventChannelOnListen");
barcodeBroadcastReceiver = createBarcodeBroadcastReceiver(events);
registerReceiver(
barcodeBroadcastReceiver, new IntentFilter("readBarcode"));
}
#Override
public void onCancel(Object arguments) {
Log.d("FLUTTERDEMO", "EventChannelOnCancel");
unregisterReceiver(barcodeBroadcastReceiver);
barcodeBroadcastReceiver = null;
}
}
);
}
// #Override
// protected void onDestroy()
// {
// super.onDestroy();
// unregisterReceiver(myBroadcastReceiver);
// }
//
// After registering the broadcast receiver, the next step (below) is to define it.
// Here it's done in the MainActivity.java, but also can be handled by a separate class.
// The logic of extracting the scanned data and displaying it on the screen
// is executed in its own method (later in the code). Note the use of the
// extra keys are defined in the strings.xml file.
//
private BroadcastReceiver createBarcodeBroadcastReceiver(final EventSink events) {
return new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("FLUTTERDEMO", "createBarcodeBroadcastReceiver " + action);
if(action.equals("readBarcode")){
String barcode = intent.getStringExtra("barcode");
String barcodetype = intent.getStringExtra("barcodetype");
Log.d("FLUTTERDEMO", "createBarcodeBroadcastReceiver " + barcode);
events.success(barcode);
}
}
};
}
//
// The section below assumes that a UI exists in which to place the data. A production
// application would be driving much of the behavior following a scan.
//
// private void displayScanResult(Intent initiatingIntent, String howDataReceived)
// {
// String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
// String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
// String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
// final TextView lblScanSource = (TextView) findViewById(R.id.lblScanSource);
// final TextView lblScanData = (TextView) findViewById(R.id.lblScanData);
// final TextView lblScanLabelType = (TextView) findViewById(R.id.lblScanDecoder);
// lblScanSource.setText(decodedSource + " " + howDataReceived);
// lblScanData.setText(decodedData);
// lblScanLabelType.setText(decodedLabelType);
// }
}
Zebra EMDK retrieves data by overriding the 'onStatus' and 'onData' functions.
Retrieve your barcode data from 'onData'
I am using mapbox in a fragment with bottom navigation, when i exit and resume the app or when i change tabs rapidly, the app crashes. this is the error i get
10-07 22:20:36.046 21867-21886/com.dropexpress.driver.dropexpressdriver E/Mbgl-FileSource: Failed to read the storage key:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Bundle.getBoolean(java.lang.String, boolean)' on a null object reference
at com.mapbox.mapboxsdk.storage.FileSource.getCachePath(FileSource.java:88)
at com.mapbox.mapboxsdk.storage.FileSource$FileDirsPathsTask.doInBackground(FileSource.java:165)
at com.mapbox.mapboxsdk.storage.FileSource$FileDirsPathsTask.doInBackground(FileSource.java:155)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
the below code always fails when i exit the app and resume, or when i change tabs rapidly, i am using bottom navigation.
Steps to reproduce
here is my fragment code
package com.dropexpress.driver.dropexpressdriver.fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.dropexpress.driver.dropexpressdriver.R;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
public class HomeFragment extends Fragment {
private MapView mapView;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
Mapbox.getInstance(requireActivity(), "pk.eyJ1Ijoic3ludGF4bHRkIiwiYSI6ImNqaDJxNnhzbDAwNnMyeHF3dGlqODZsYjcifQ.pcz6BWpzCHeZ6hQg4AH9ww");
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Android versions: 5.0 +
Device models: motorola g5
Mapbox SDK versions: 6.5.0
Put your Mapbox.getInstance before inflating your layout.
Mapbox.getInstance(requireActivity(),"Your Map Key");
View view = inflater.inflate(R.layout.fragment_home, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
I hope this helps you.
i opened this issue in github, you check their response here
https://github.com/mapbox/mapbox-gl-native/issues/13044#issuecomment-427861016
this was their response:
I can see 2 issues with the provided code:
You are not calling MapView#onDestroy, this has to be called from you fragment's #onDestroyView.
MapView#onCreate should be called from fragment's #onViewCreatedinstead of #onCreateView.
I applied the changes and it worked!
I am showing the contact list from the contact table but not able to get the phone number using the same on RecyclerView.My code is -
package com.oodles.oodlesapprtc;
import android.annotation.SuppressLint;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by ankita on 13/4/17.
*/
public class LoginUserActivity extends AppCompatActivity {
public static final int CONTACT_LOADER_ID = 78;
RecyclerView loginUserRecycler;
ArrayList<ContactBeans> contactBeanses;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +
" COLLATE LOCALIZED ASC";
private static final String[] PROJECTION2 = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.PHOTO_URI,ContactsContract.Contacts.HAS_PHONE_NUMBER
};
private static final String[] PROJECTION3 = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.PHOTO_URI, ContactsContract.Contacts.LOOKUP_KEY
};
private static final String[] PROJECTION = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY, ContactsContract.CommonDataKinds.Phone.NUMBER
};
// private static final String[] PROJECTION1 = {
// ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
// ContactsContract.CommonDataKinds.Phone.NUMBER
// };
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user_activity);
initViews();
}
private void initViews() {
getLoaderManager().initLoader(0, null, contactLoaderManager);
initRecycler();
}
private void initRecycler() {
loginUserRecycler = (RecyclerView) findViewById(R.id.loginUserRecycler);
loginUserRecycler.setLayoutManager(new LinearLayoutManager(this));
loginUserRecycler.setItemAnimator(new DefaultItemAnimator());
}
LoaderManager.LoaderCallbacks<Cursor> contactLoaderManager = new LoaderManager.LoaderCallbacks<Cursor>() {
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// String[] projectionFields = new String[]{ContactsContract.Contacts._ID,
// ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.PhoneLookup.NORMALIZED_NUMBER,
// ContactsContract.Contacts.PHOTO_URI};
// Construct the loader
// Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
// ContactsContract.Contacts.CONTENT_URI
// Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
// Uri.encode(phoneNumber));
CursorLoader cursorLoader = new CursorLoader(LoginUserActivity.this,
ContactsContract.Contacts.CONTENT_URI, // URI
PROJECTION2, // projection fields
null, // the selection criteria
null, // the selection args
sortOrder // the sort order
);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
loginUserRecycler.setAdapter(new CursorRecyclerAdapter(LoginUserActivity.this, data));
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
};
}
My Adapter is -
package com.oodles.oodlesapprtc;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by ankita on 13/4/17.
*/
public class CursorRecyclerAdapter extends RecyclerView.Adapter<ContactViewHolder> {
private Cursor mCursor;
private final int mNameColIdx,
mIdColIdx;
int phoneNumber;
int hasPhoneNumber;
private Context mContext;
public CursorRecyclerAdapter(Context context, Cursor cursor) {
mCursor = cursor;
this.mContext = context;
mNameColIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY);
mIdColIdx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
hasPhoneNumber = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int pos) {
View listItemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.contact_row, parent, false);
return new ContactViewHolder(listItemView);
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int pos) {
mCursor.moveToPosition(pos);
String contactName = mCursor.getString(mNameColIdx);
long contactId = mCursor.getLong(mIdColIdx);
Contact c = new Contact();
Log.e("ddhdhdhhdhdhdhd",hasPhoneNumber+"");
c.name = contactName;
c.number = getPhoneNumberFromContactId(contactId);
c.profilePic = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
getPhoneNumberFromContactId(contactId);
contactViewHolder.bind(c);
}
private String getPhoneNumberFromContactId(long contactId) {
String contactNumber = "8874675724";
return contactNumber;
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
}
How can I get the phone number for the same i am getting a cursorindexoutofbound exception and has phone number value as 3 but it can be only 0 or 1 why it is 3 i don't understand this.
Can Anyone please explain this to me also please explain how the contact fetch works
You have a few issues in the code:
You're querying on the Contacts table, but sorting using a CommonDataKinds.Phone table field, that's not good, you can sort using Contacts.DISPLAY_NAME_PRIMARY instead.
cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER) gives you a column index, not the value of the field, that's why you're getting 3 (it's the 4rd field defined in PROJECTION2), change hasPhoneNumber to mHasPhoneNumberIdx to avoid confusion.
add hasPhoneNumber = mCursor.getInt(mHasPhoneNumberIdx); to your onBindViewHolder method, to get the actual value.
Running a long command like a real implementation of getPhoneNumberFromContactId within onBindViewHolder is really bad... you should change your main query so you do two big queries, one for all contacts, one for all phones, and then use some HashMap to get a phone using a contact-id.
As you see my Code, it dont have error when run debug, I put the tabhost into my fragment, but when app run. It dont show the tabhost
package com.example.phamxuanson.myapplication;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
mTitle = getTitle();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
Please see my piuctures
i.imgur.com/AuPA4GO.png
i.imgur.com/Vlrxuhz.png
i.imgur.com/or8m6Mj.png
Why wasn’t tabhost shown?