My android app is using contacts providers to display all the contacts to the user. I'm using Loaders to load the contacts by following the tutorial/documentation at https://developer.android.com/training/contacts-provider/retrieve-names
But from the link https://developer.android.com/guide/components/loaders, it is mentioned that loaders are deprecated as of Android P.
Loaders have been deprecated as of Android P (API 28). The recommended
option for dealing with loading data while handling the Activity and
Fragment lifecycles is to use a combination of ViewModels and
LiveData. ViewModels survive configuration changes like Loaders but
with less boilerplate. LiveData provides a lifecycle-aware way of
loading data that you can reuse in multiple ViewModels. You can also
combine LiveData using MediatorLiveData, and any observable queries,
such as those from a Room database, can be used to observe changes to
the data. ViewModels and LiveData are also available in situations
where you do not have access to the LoaderManager, such as in a
Service. Using the two in tandem provides an easy way to access the
data your app needs without having to deal with the UI lifecycle. To
learn more about LiveData see the LiveData guide and to learn more
about ViewModels see the ViewModel guide.
So my question is:
1. How can we fetch the contacts using android view Model and live data from contact providers?
2. Can we use Room database for contact providers?
Below you can find the link to the source code where I tried to use the Android View Model and Live data to fetch the contacts from ContactProviders.
https://github.com/deepak786/phonebook-contacts
3. What can be improved in the above source code so that fetching will be faster?
Thanks & Regards
Deepak
Below you can find a very simple solution for loading contacts using MVVM:
https://github.com/NaarGes/Android-Contact-List
Here comes a bit of code in case the link is no longer working.
First, let's create a simple POJO for contacts UserObject.java
public class UserObject {
private String email, name, phone;
public UserObject() {
// EMPTY CONSTRUCTOR FOR FIREBASE REALTIME DATABASE
}
public UserObject(String email, String name, String phone) {
this.email = email;
this.name = name;
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Now, let's create our repository ContactRepository.java
public class ContactRepository {
private Context context;
private static final String TAG = "debinf ContRepo";
public ContactRepository(Context context) {
this.context = context;
}
public List<UserObject> fetchContacts() {
List<UserObject> contacts = new ArrayList<>();
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Log.i(TAG, "fetchContacts: cursor.getCount() is "+cursor.getCount());
if ((cursor != null ? cursor.getCount() : 0) > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
UserObject contact = new UserObject("",name, phone);
Log.i(TAG, "fetchContacts: phone is "+phone);
contacts.add(contact);
}
}
if (cursor != null) {
cursor.close();
}
return contacts;
}
}
Next, we create our ContactViewModel.java
public class ContactViewModel extends ViewModel {
private ContactRepository repository;
private MutableLiveData<List<UserObject>> contacts;
public ContactViewModel(Context context) {
repository = new ContactRepository(context);
contacts = new MutableLiveData<>();
}
public MutableLiveData<List<UserObject>> getContacts() {
contacts.setValue(repository.fetchContacts());
return contacts;
}
}
Next, we create a factory for our ViewModel ContactViewModelFactory.java
public class ContactViewModelFactory implements ViewModelProvider.Factory {
private Context context;
public ContactViewModelFactory(Context context) {
this.context = context;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(ContactViewModel.class)) {
return (T) new ContactViewModel(context);
}
throw new IllegalArgumentException("Unknown ViewModel class");
}
}
Let's not forget to add permission in our AndroidManifest
<uses-permission android:name="android.permission.READ_CONTACTS" />
And finally, we ask for permission in our MainActivity.java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
and bring our contacts to surface
ContactViewModelFactory factory = new ContactViewModelFactory(this);
viewModel = ViewModelProviders.of(this, factory).get(ContactViewModel.class);
viewModel.getContacts().observe(this, new Observer<List<UserObject>>() {
#Override
public void onChanged(#Nullable List<UserObject> userObjects) {
Log.i(TAG, "ViewModel: userObjects size is "+userObjects.size());
Log.i(TAG, "ViewModel: userObjects size is "+userObjects.get(1).getPhone());
}
});
class ContactsViewModel(private val contentResolver: ContentResolver) : ViewModel()
{
lateinit var contactsList: LiveData<PagedList<Contact>>
fun loadContacts() {
val config = PagedList.Config.Builder()
.setPageSize(20)
.setEnablePlaceholders(false)
.build()
contactsList = LivePagedListBuilder<Int, Contact>(
ContactsDataSourceFactory(contentResolver), config).build()
}
}
class ContactsDataSourceFactory(private val contentResolver: ContentResolver) :
DataSource.Factory<Int, Contact>() {
override fun create(): DataSource<Int, Contact> {
return ContactsDataSource(contentResolver)
}
}
class ContactsDataSource(private val contentResolver: ContentResolver) :
PositionalDataSource<Contact>() {
companion object {
private val PROJECTION = arrayOf(
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
)
}
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<Contact>) {
callback.onResult(getContacts(params.requestedLoadSize, params.requestedStartPosition), 0)
}
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<Contact>) {
callback.onResult(getContacts(params.loadSize, params.startPosition))
}
private fun getContacts(limit: Int, offset: Int): MutableList<Contact> {
val cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
PROJECTION,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY +
" ASC LIMIT " + limit + " OFFSET " + offset)
cursor.moveToFirst()
val contacts: MutableList<Contact> = mutableListOf()
while (!cursor.isAfterLast) {
val id = cursor.getLong(cursor.getColumnIndex(PROJECTION[0]))
val lookupKey = cursor.getString(cursor.getColumnIndex(PROJECTION[0]))
val name = cursor.getString(cursor.getColumnIndex(PROJECTION[2]))
contacts.add(Contact(id, lookupKey, name))
cursor.moveToNext()
}
cursor.close()
return contacts
}
}
Please find the full source code here.
Related
First question here, I hope I'm doing it right.
I'm using Entity Framework Core 5.0 (Code First) with an onion architecture (data/repo/service/mvc) and so I have a service for each table (almost).
It's work well but now I need to manage (get, insert, update, delete) about 150 tables which all have the same structure (Id, name, order).
I have added each of them as Entity class and their DbSet too in my DbContext, but I don't want to make 150 services, I would like to have a generic one .
How can I bind it to my generic repository ?
public class Repository<T> : IRepository<T> where T : BaseEntity
{
private readonly ApplicationContext context;
private DbSet<T> entities;
private readonly RepositorySequence repoSequence;
private string typeName { get; set; }
public Repository(ApplicationContext context)
{
this.context = context;
entities = context.Set<T>();
this.repoSequence = new RepositorySequence(context);
this.typeName = typeof(T).Name;
}
public T Get(long plng_Id)
{
return entities.SingleOrDefault(s => s.Id == plng_Id);
}
[...]
}
In an ideal world, would like to have something like this :
public async Task Insert(dynamic pdyn_Entity)
{
Type DynamicType = Type.GetType(pdyn_Entity);
Repository<DynamicType> vobj_Repo = new Repository<DynamicType>(mobj_AppContext);
long Id = await vobj_Repo.InsertAsync(pdyn_Entity);
}
But I can try to get type from DbSet string Name too, I just managed to retrieve some data :
public IEnumerable<object> GetAll(string pstr_DbSetName)
{
return ((IEnumerable<BaseEntity>)typeof(ApplicationContext).GetProperty(pstr_DbSetName).GetValue(mobj_AppContext, null));
}
I've tried the following method (2.0 compatible apparently) to get the good DbSet, not working neither (no Query) : https://stackoverflow.com/a/48042166/10359024
What am I missing?
Thanks a lot for your help
Not sure why you need to get type?
You can use something like this.
Repository.cs
public class Repository<T> : IRepository<T> where T : BaseEntity
{
private readonly ApplicationContext context;
private DbSet<T> entities;
public Repository(ApplicationContext context)
{
this.context = context;
entities = context.Set<T>();
}
public List<T> Get()
=> entities.ToList();
public T Get(long plng_Id)
=> entities.Find(plng_Id);
public long Save(T obj)
{
if (obj.ID > 0)
entities.Update(obj);
else
entities.Add(obj);
return obj.ID;
}
public void Delete(T obj)
=> entities.Remove(obj);
}
Then you can use either one of these 2 options you want
Multiple repositories following your tables
UserRepository.cs
public class UserRepository : Repository<User> : IUserRepository
{
private readonly ApplicationContext context;
public UserRepository(ApplicationContext context)
{
this.context = context;
}
}
BaseService.cs
public class BaseService : IBaseService
{
private readonly ApplicationContext context;
private IUserRepository user;
private IRoleRepository role;
public IUserRepository User { get => user ??= new UserRepository(context); }
public IRoleRepository Role { get => user ??= new RoleRepository(context); }
public BaseService(ApplicationContext context)
{
this.context = context;
}
}
If you are lazy to create multiple repositories, can use this way also. Your service just simple call Repository with entity name.
BaseService.cs
public class BaseService : IBaseService
{
private readonly ApplicationContext context;
private IRepository<User> user;
private IRepository<Role> role;
public IRepository<User> User { get => user ??= new Repository<User>(context); }
public IRepository<Role> Role { get => role ??= new Repository<Role>(context); }
public BaseService(ApplicationContext context)
{
this.context = context;
}
}
Finally, you can call service like this. You can use multiple services instead of BaseService if you want.
HomeController.cs
public class HomeController : Controller
{
private readonly IBaseService service;
public HomeController(IBaseService service)
{
this.service = service;
}
public IActionResult Index()
{
var user = service.User.Get();
return View(user);
}
public IActionResult Add(User user)
{
var id = service.User.Save(user);
return View();
}
}
I suggest to use first option (multiple repositories) because you may need to customise functions in own repository in future. And create service class following your controller name. For example, you have HomeController, UserController, etc. Create HomeService, UserService and link them with BaseService so that you can create customised functions in their own service class.
I assume you have a base entity like this:
public class BaseEntity
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Order { get; set; }
}
Then you can do CRUD operations in your generic repository like this:
public int Create(T item)
{
if (item == null) return 0;
entities.Add(item);////SaveChanges
return item.Id;
}
public void Update(T updatedItem)
{
context.SetModified(updatedItem);//SaveChanges
}
public IQueryable<T> All()
{
return entities();
}
And in each of the methods you have access to your 3 common fields in BaseEntity
Thank you all for your responses.
I need to have the type because I am using a blazor component which automatically binds to these tables. This component has the name of the desired entity class (in string) as a parameter. Thanks to #Asherguru's response I was able to find a way to do this:
1 - I made a 'SedgmentEntity' Class :
public abstract class SegmentEntity : ISegmentEntity
{
public abstract long Id { get; set; }
public abstract string Name { get; set; }
public abstract short? Order { get; set; }
}
2 - A SegmentRepository which is typed via Reflection:
public class SegmentRepository : ISegmentRepository
{
private readonly ApplicationContext context;
private readonly RepositorySequence repoSequence;
public SegmentRepository(ApplicationContext context)
{
this.context = context;
this.repoSequence = new RepositorySequence(context);
}
public async Task<long> Insert(string pstr_EntityType, SegmentEntity pobj_Entity)
{
Type? vobj_EntityType = Assembly.GetAssembly(typeof(SegmentEntity)).GetType("namespace.Data." + pstr_EntityType);
if (vobj_EntityType != null)
{
// create an instance of that type
object vobj_Instance = Activator.CreateInstance(vobj_EntityType);
long? nextId = await repoSequence.GetNextId(GetTableName(vobj_EntityType));
if (nextId == null)
{
throw new TaskCanceledException("Sequence introuvable pour " + vobj_EntityType.FullName);
}
PropertyInfo vobj_PropId = vobj_EntityType.GetProperty("Id");
vobj_PropId.SetValue(vobj_Instance, nextId.Value, null);
PropertyInfo vobj_PropName = vobj_EntityType.GetProperty("Name");
vobj_PropName.SetValue(vobj_Instance, pobj_Entity.Name, null);
PropertyInfo vobj_PropOrder = vobj_EntityType.GetProperty("Order");
vobj_PropOrder.SetValue(vobj_Instance, pobj_Entity.Order, null);
return ((SegmentEntity)context.Add(vobj_Instance).Entity).Id;
}
}
public IEnumerable<object> GetAll(string pstr_EntityType)
{
Type? vobj_EntityType = Assembly.GetAssembly(typeof(SegmentEntity)).GetType("namespace.Data." + pstr_EntityType);
if (vobj_EntityType != null)
{
PropertyInfo vobj_DbSetProperty = typeof(ApplicationContext).GetProperties().FirstOrDefault(prop =>
prop.PropertyType.FullName.Contains(vobj_EntityType.FullName));
return (IEnumerable<object>)vobj_DbSetProperty.GetValue(context, null);
}
return null;
}
}
I still have to handle the Get and the Delete functions but it should be fine.
Then I will be able to create a single service which will be called by my component.
Thanks again !
I'm going to add data to a CRUD component in Vaadin. It's an easy question here.
But the issue I got is that I cannot add data to the CRUD by first getting the grid object and then set its items to it.
Here is my Vaadin class. This class begins first to get data from a JPA Spring database. OK. That's works. And the data is transfered into a collection named crudData. Then the crudData is beings set to crud.getGrid().setItems(crudData); and that's not working. I assume that if I get the grid from the CRUD, then I can set the grid items as well too and then they will show up on the CRUD....but no...
#Data
public class StocksCrud {
private Crud<StockNames> crud;
private List<StockNames> crudData;
private StockNamesRepository stockNamesRepository;
private CrudEditor<StockNames> createStocksEditor() {
TextField stockName = new TextField("Name of the stock");
FormLayout form = new FormLayout(stockName);
Binder<StockNames> binder = new Binder<>(StockNames.class);
binder.bind(stockName, StockNames::getStockName, StockNames::setStockName);
return new BinderCrudEditor<>(binder, form);
}
public StocksCrud(StockNamesRepository stockNamesRepository) {
this.stockNamesRepository = stockNamesRepository;
// Fill the crud
crudData = new ArrayList<StockNames>();
for(StockNames stockName: stockNamesRepository.findAll()) {
crudData.add(new StockNames(stockName.getId(), stockName.getStockName()));
}
// Crate crud table
crud = new Crud<>(StockNames.class, createStocksEditor());
crud.getGrid().setItems(crudData); // This won't work
crud.addSaveListener(e -> saveStock(e.getItem()));
crud.addDeleteListener(e -> deleteStock(e.getItem()));
crud.getGrid().removeColumnByKey("id");
crud.addThemeVariants(CrudVariant.NO_BORDER);
}
private void deleteStock(StockNames stockNames) {
boolean exist = stockNamesRepository.existsBystockName(stockNames.getStockName());
if(exist == true) {
crudData.remove(stockNames);
stockNamesRepository.delete(stockNames);
}
}
private void saveStock(StockNames stockNames) {
System.out.println(stockNames == null);
System.out.println(stockNamesRepository == null);
boolean exist = stockNamesRepository.existsBystockName(stockNames.getStockName());
if(exist == false) {
crudData.add(stockNames);
stockNamesRepository.save(stockNames);
}
}
}
Here is my error output:
java.lang.ClassCastException: com.vaadin.flow.component.crud.CrudFilter cannot be cast to com.vaadin.flow.function.SerializablePredicate
I know that there is a way to set data to CRUD in Vaadin, by using a data provider class. But I don't want to use that. It's....to much code. I want to keep it clean and write less code in Java. Example here at the bottom: https://vaadin.com/components/vaadin-crud/java-examples
#Entity
#Data
#NoArgsConstructor
public class StockNames implements Cloneable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String stockName;
public StockNames(int id, String stockName) {
this.id = id;
this.stockName = stockName;
}
}
Update:
This is my code now
#Data
public class StocksCrud {
private Crud<StockNames> crud;
private List<StockNames> crudData;
private StockNamesRepository stockNamesRepository;
private CrudEditor<StockNames> createStocksEditor() {
TextField stockName = new TextField("Name of the stock");
FormLayout form = new FormLayout(stockName);
Binder<StockNames> binder = new Binder<>(StockNames.class);
binder.bind(stockName, StockNames::getStockName, StockNames::setStockName);
return new BinderCrudEditor<>(binder, form);
}
public StocksCrud(StockNamesRepository stockNamesRepository) {
this.stockNamesRepository = stockNamesRepository;
// Fill the crud
crudData = new ArrayList<StockNames>();
for(StockNames stockName: stockNamesRepository.findAll()) {
crudData.add(new StockNames(stockName.getId(), stockName.getStockName()));
}
// Create grid
Grid<StockNames> grid = new Grid<StockNames>();
grid.setItems(crudData);
// Crate crud table
crud = new Crud<>(StockNames.class, createStocksEditor());
crud.setGrid(grid);
crud.addSaveListener(e -> saveStock(e.getItem()));
crud.addDeleteListener(e -> deleteStock(e.getItem()));
//crud.getGrid().removeColumnByKey("id");
crud.addThemeVariants(CrudVariant.NO_BORDER);
}
private void deleteStock(StockNames stockNames) {
boolean exist = stockNamesRepository.existsBystockName(stockNames.getStockName());
if(exist == true) {
crudData.remove(stockNames);
stockNamesRepository.delete(stockNames);
}
}
private void saveStock(StockNames stockNames) {
System.out.println(stockNames == null);
System.out.println(stockNamesRepository == null);
boolean exist = stockNamesRepository.existsBystockName(stockNames.getStockName());
if(exist == false) {
crudData.add(stockNames);
stockNamesRepository.save(stockNames);
}
}
}
Update 2:
This gives an error.
// Create grid
Grid<StockNames> grid = new Grid<StockNames>();
StockNames s1 = new StockNames(1, "HELLO");
crudData.add(s1);
grid.setItems(crudData);
// Crate crud table
crud = new Crud<>(StockNames.class, createStocksEditor());
crud.setGrid(grid);
crud.addSaveListener(e -> saveStock(e.getItem()));
crud.addDeleteListener(e -> deleteStock(e.getItem()));
crud.getGrid().removeColumnByKey(grid.getColumns().get(0).getKey());
crud.addThemeVariants(CrudVariant.NO_BORDER);
The error is:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0'
What? I just added a object.
Assigning grid fixes the issue
Grid<StockNames> grid=new Grid<>(StockNames.class);
crud = new Crud<>(StockNames.class,grid, createStocksEditor());
In your code example you are relying on default implementation provided by Crud, thus CrudGrid is getting created. Its setDataProvider returns DataProvider<E,CrudFilter>, whereas Grid's DataProvider is of type: AbstractDataProvider<T, SerializablePredicate<T>> (This is because you are using ListDataProvider, which extends AbstractDataProvider<T, SerializablePredicate<T>>). This is what error states:
java.lang.ClassCastException: com.vaadin.flow.component.crud.CrudFilter cannot be cast to com.vaadin.flow.function.SerializablePredicate
So if you want to assign values via grid- you would first need to create one. Otherwise, as shown in the docs you could provide a custom dataprovider: PersonDataProvider
Update
This is an example code I am using. Adding a new item in Crud works, after I have added a no-args constructor to the bean:
import java.util.Random;
public class StockNames implements Cloneable{
Random rnd=new Random();
private int id;
private String stockName;
public StockNames(){
//You will an id generated automatically for you, but here is just an example
id=rnd.nextInt(12000);
}
public StockNames(int id, String stockName) {
this.id = id;
this.stockName = stockName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
}
and the StockCrud class:
import com.vaadin.flow.component.crud.*;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;
import java.util.ArrayList;
import java.util.List;
#Route("crudLayout")
public class StockCrud extends VerticalLayout {
private Crud<StockNames> crud;
private List<StockNames> crudData;
private CrudEditor<StockNames> createStocksEditor() {
TextField stockName = new TextField("Name of the stock");
FormLayout form = new FormLayout(stockName);
Binder<StockNames> binder = new Binder<>(StockNames.class);
binder.bind(stockName, StockNames::getStockName, StockNames::setStockName);
return new BinderCrudEditor<>(binder, form);
}
public StockCrud() {
// Fill the crud
crudData = new ArrayList<StockNames>();
for(int i=0;i<150;i++) {
crudData.add(new StockNames(i,"Name " + i));
}
// Crate crud table
Grid<StockNames> grid=new Grid<>(StockNames.class);
crud = new Crud<>(StockNames.class,grid, createStocksEditor());
//((CrudGrid )crud.getGrid()).setItems(crudData);
crud.getGrid().setItems(crudData); // This won't work
crud.addSaveListener(e -> saveStock(e.getItem()));
crud.addDeleteListener(e -> deleteStock(e.getItem()));
// crud.getGrid().removeColumnByKey("id");
crud.addThemeVariants(CrudVariant.NO_BORDER);
add(crud);
}
private void deleteStock(StockNames stockNames) {
// if(crudData.contains(stockNames)) {
crudData.remove(stockNames);
//}
}
private void saveStock(StockNames stockNames) {
System.out.println(stockNames == null);
if(!crudData.contains(stockNames)) {
crudData.add(stockNames);
}
}
}
we need to make a spring boot project that works with spring ldap.
every things is good.But when we remove a member from a group,the member deleted form group (i see it in debug mode in a Setmembers) but, in ldap(Oracle Internet Directory) that member exists!
Please help me!
//Group Entry
#Entry(objectClasses = {"top", "groupOfUniqueNames", "orclGroup"}, base = "cn=Groups")
public final class Group {
#Id
private Name dn;
#Attribute(name = "cn")
private String name;
private String description;
private String displayName;
#Attribute(name = "ou")
private String ou;
#Attribute(name = "uniqueMember")
private Set<Name> members;
public void addMember(Name newMember) {
members.add(newMember);
}
public void removeMember(Name member) {
members.remove(member);
}
//Custom LdapUtils
public class CustomLdapUtils {
private static final String GROUP_BASE_DN = "cn=Groups";
private static final String USER_BASE_DN = "cn=Users";
public Name buildGroupDn(String name) {
return LdapNameBuilder.newInstance(GROUP_BASE_DN)
.add("cn","Charts")
.add("cn",name)
.build();
}
private static final CsutomLdapUtils LDAP_UTILS = new CsutomLdapUtils ();
private CsutomLdapUtils () {
}
public Name buildPersonDn(String name) {
return LdapNameBuilder.newInstance(USER_BASE_DN)
.add("cn", name)
.build();
}
}
//Controller
#DeleteMapping(value = "/memberOfGroup", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> removeMemberFromGroup(#RequestBody Map<String,String> map) throws NamingException {
List<Group> groupToFind = ldapSearchGroupsService.getGroupByCn(map.get("groupName"));
List<User> userToFind = ldapSearchUserService.getAllUserByUserName(map.get("userName"));
if (groupToFind.isEmpty()) {
//TODO : Group no found!
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
for (Group group1 : groupToFind) {
group1.removeMember(userToFind.stream().findAny().get().getDn());
//ldapBindGroupService.deleteMemberFromGroup(group1);
DirContextOperations ctx = ldapTemplate.lookupContext(CustomLdapUtils.getInstance().buildGroupDn(map.get("groupName")));
ctx.removeAttributeValue("uniqueMember",map.get("userName"));
ctx.rebind(CustomLdapUtils.getInstance().buildGroupDn(map.get("groupName")),map.get("groupName"));
ldapTemplate.modifyAttributes(ctx);
}
return new ResponseEntity<>(HttpStatus.OK);
}
}
Is some problem in code? or need some methods?
Finally after several search and debug,i found the problem!
In each ldap env,after every changes,the directory must be commit and apply.
In above code,i implemented that,but not in true way!
Best way is here:
#DeleteMapping(value = "/membersOfGroup", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> removeMemberFromGroup(#RequestBody Map<String,String> map) {
List<Group> groupToFind = ldapSearchGroupsService.getGroupByCn(map.get("groupName"));
List<User> userToFind = ldapSearchUserService.getAllUserByUserName(map.get("userName"));
if (groupToFind.isEmpty()) {
//TODO : Group no found!
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
for (Group group1 : groupToFind) {
group1.removeMember(userToFind.stream().findAny().get().getDn());
DirContextOperations ctx = ldapTemplate.lookupContext(CustomLdapUtils.getInstance().buildGroupDn(map.get("groupName")));
ctx.removeAttributeValue("member",CustomLdapUtils.getInstance().buildPersonDn(map.get("userName")));
//True way
ldapTemplate.update(group1);
}
return new ResponseEntity<>(HttpStatus.OK);
}
}
I am attempting to read data from an Android Room database in a background Service. There are no exceptions but no data is returned.
I wrote a function to select all rows from a table in the DAO. Calling that function from a background service succeeds, but it returns no data.
My "Contact" class holds contact information (names, phone numbers, emails) and defines the database schema. The database holds rows of contacts, with names, phone numbers, an emails as columns.
The function that returns the LiveData in the DAO is:
#Query("SELECT * FROM contacts_table")
LiveData<List<Contact>> getAll();
where "contacts_table" is the database table holding contact information.
I called getAll as follows:
AppDatabase db = AppDatabase.getDatabase(messageSenderContext.getApplicationContext());
mContactDAO = db.contactDAO();
mAllContacts = mContactDAO.getAll();
where mContactDao is a ContactDAO (The Database Access Object for my Contact class), and mAllContacts is a LiveData>. These are private fields of the class calling getAll().
db.contactDAO() returns an object, as does mContactDAO.getAll(). But attempting to unpack the List from mAllContacts using mAllContacts.getValue() returns null.
This turned out to be a misuse of LiveData. That requires an Observer to actually get the data.
In your ROOM
#Database(entities={Contact.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
public static final String DATABASE_NAME = "AppDatabase.db";
private static volatile AppDatabase INSTANCE;
private static final int NUMBER_OF_THREADS = 4;
public static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
public abstract ContactDAO contactDAO();
public static AppDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (AppDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, DATABASE_NAME)
.build();
}
}
}
return INSTANCE;
}
}
In your DAO
#Dao
public interface ContactDAO{
#Query("SELECT * FROM contacts_table")
LiveData<List<Contact>> getAll();
}
In your repository:
public class AppRepository {
private ContactDAO mContactDAO;
//constructor
public AppRepository(Application application) {
AppDatabase db = AppDatabase.getDatabase(application);
mContactDAO= db.contactDAO();
}
public LiveData<List<Contact>> getAllContacts(){
LiveData<List<Contact>> contactsList = null;
Future<LiveData<List<Contact>>> futureList = AppDatabase.EXECUTOR_SERVICE.submit(new Callable(){
#Override
public LiveData<List<Contact>> call() {
return contactDAO.getAll();
}
});
try {
contactsList = futureList.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return contactsList ;
}
}
In your ViewModel
public class ContactsViewModel extends AndroidViewModel {
private AppRepository appRepository;
private LiveData<List<Contact>> contactsList;
public ContactsViewModel(#NonNull Application application) {
super(application);
appRepository = new AppRepository(application);
}
public LiveData<List<Contacts>> list() {
return appRepository.getAllContacts();
}
}
In your activity (inside of onCreated put)
ContactsViewModel contactsViewModel = new ViewModelProvider(this).get(ContactsViewModel.class);
contactsViewModel.list().observe(getViewLifecycleOwner(), new Observer<List<Contact>>() {
#Override
public void onChanged(List<Contact> contactsList) {
//the contact list will be observed and will return data if there are changes.
//use for example to feed the adapter of a recyclerview
//below an example just to view the contacts data
for(Contact conctact : contactsList){
Log.d("TestApp>>>", "Id: + contact.getId);
Log.d("TestApp>>>", "Name: + contact.getName);
}
});
I have a class Activity that can have several activities associated with it (List). How can I configure my class with Fluent API to load all other child activities if one parent activity is selected?
Here is my Domain Class for Activity:
public class Activity : ProjectBase
{
private string activityType;
public string ActivityType
{
get { return activityType; }
set { activityType = value; }
}
private string catagory;
public string Catagory
{
get { return catagory; }
set { catagory = value; }
}
private string priority;
public string Priority
{
get { return priority; }
set { priority = value; }
}
public Activity()
:base()
{
}
}
ProjectBase has the List property declared. My database is generated following Table Per Hierarchy and the table for Activity seems generated fine for recursion.
Any suggestion is highly appreciated.
All I had to do was put virtual on the list and it brought all related records:
private List<Activity> activities = new List<Activity>();
public virtual List<Activity> Activities
{
get { return activities; }
set { activities = value; }
}
Thanks for the help people!