Reading Contact List in Micromax Q50 - java-me

I am using the following code to read Contact List in Micromax Device.
But without any success.
try {
PIM t_pim = PIM.getInstance();
String[] namesOfContactLists = t_pim.listPIMLists(PIM.CONTACT_LIST);
PIMList t_pimlist = t_pim.openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, namesOfContactLists[0]);//namesOfContactLists[0] is the Phone List.
Enumeration t_enumeration = t_pimlist.items();
boolean isFormattedNameSupported = t_pimlist.isSupportedField(Contact.FORMATTED_NAME);
while (t_enumeration.hasMoreElements()) {
String t_contactName = "";
Contact t_contact = (Contact) t_enumeration.nextElement();
if (isFormattedNameSupported) {
if (t_contact.countValues(Contact.FORMATTED_NAME) > 0) {
t_contactName = t_contact.getString(Contact.FORMATTED_NAME, 0);//Throws UnsupportedFieldException
}
}
}
} catch (PIMException ex) {
ex.printStackTrace();
}
Other options like Contact.NAME, Contact.NAME_GIVEN, Contact.NAME_FAMILY, Contact.NAME_OTHER, Contact.NAME_PREFIX, Contact.NAME_SUFFIX, Contact.NICKNAME also throw the same UnsupportedFieldException.
This code works fine on Nokia and Sony Ericsson devices. But fails on Micromax.

When you say "without any success", what do you mean? What actually happens? If you mean that FORMATTED_NAME is an unsupported field for Contact, then these fields are optional. Use PIMList.getSupportedFields() to figure out which fields you can read on each platform.

Related

device.GattServices returns an empty set for BLE devices on a Windows universal app

I am using the sample from Microsoft. When an advertisement is received I am calling
BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);
and then
device.GattServices()
but that always returns an empty list. Why is this happening? I have found no answer whatsoever.
If you want this to work by using advertisement watcher, you need to target the windows 10 creators update(10.0;Build 15063) and use the latest SDK, otherwise you will have to pair the device first.
To get the GattServices, first check if the device is not null.
Then use:
var serviceResult = await bluetoothLeDevice.GetGattServicesAsync();
if (serviceResult.Status == GattCommunicationStatus.Success)
{
//Do something with servivicResult list
}
But there is a catch; It can be that serviceResult.Status returns success, but not all or no services have been found yet.
My solution is to put it in a loop with a short delay and try it a few times until serviceResult count stays the same.
I wanted to put more explanation in my comment, but something went wrong and cannot edit my comment so I will add it as an answer.
I had exactly the same problem. for some reason you have to initialize your BLEdevice as null.
private BluetoothLEDevice device = null;
Also to prevent that you advertisementWatcher is setting your device over and over, use an if statement to set it only when the divice is null,
if (device == null)
{
device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);
}
or if you want to set multiple devices than add them to a collection and make sure each device is only added once.
This is my working code :
private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher,
BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
BluetoothLEAdvertisementType advertisementType = eventArgs.AdvertisementType;
short rssi = eventArgs.RawSignalStrengthInDBm;
string localName = eventArgs.Advertisement.LocalName;
string manufacturerDataString = "";
var manufacturerSections = eventArgs.Advertisement.ManufacturerData;
if (manufacturerSections.Count > 0)
{
// Only print the first one of the list
var manufacturerData = manufacturerSections[0];
var data = new byte[manufacturerData.Data.Length];
using (var reader = DataReader.FromBuffer(manufacturerData.Data))
{
reader.ReadBytes(data);
}
manufacturerDataString = string.Format("0x{0}: {1}",
manufacturerData.CompanyId.ToString("X"),
BitConverter.ToString(data));
}
string res = string.Format("type={0}, rssi={1}, name={2}, manufacturerData=[{3}]",
advertisementType.ToString(),
rssi.ToString(),
localName,
manufacturerDataString);
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
textBoxWatcher.Text = res;
});
if (device == null)
{
device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);
if (device != null)
{
var deviceInfo = device.DeviceInformation;
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (device.Name != string.Empty)
{
//ResultCollection is a observable observable collection of blueutooth devices
// to bind to a listvieuw,it is not needed!
ResultCollection.Add(new BleDevice(device));
if (deviceInfo.Name == "HMSoft")
{
if (ResultCollection[0] is BleDevice bleDevice)
{
BleDeviceId = bleDevice.Id;
SelectedBleDeviceName = bleDevice.Name;
}
Connect();
}
}
});
}
}

Search for users by Forgerock ClientSDK tools

All.
I'm trying to search for the users using ClientSDK tools of Forgerock OpenAM-12.0.0 by sunIdentityServerPPCommonNameSN.
Look my code.
I found out that I can search the users by AMIdentityRepository.searchIdentities of the filter argument.
However, I don't find out the format.
Please give me your help.
Regard.
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
AuthContext ac = new AuthContext("/");
AuthContext.IndexType indexType =
AuthContext.IndexType.MODULE_INSTANCE;
String indexName = "DataStore";
ac.login(indexType, indexName);
Callback[] callback = ac.getRequirements();
for (int i =0 ; i< callback.length ; i++) {
if (callback[i] instanceof NameCallback) {
NameCallback name = (NameCallback) callback[i];
name.setName("amAdmin");
} else if (callback[i] instanceof PasswordCallback) {
PasswordCallback pass = (PasswordCallback) callback[i];
String password = "adAdmin00";
pass.setPassword(password.toCharArray());
}
}
ac.submitRequirements(callback);
if(ac.getStatus() == AuthContext.Status.SUCCESS){
SSOToken token = ac.getSSOToken();
AMIdentityRepository amIr = new AMIdentityRepository(token, "/");
// I want to search for the users by sunIdentityServerPPCommonNameSN;
String filter = "sunIdentityServerPPCommonNameSN=*";
IdSearchResults isr = amIr.searchIdentities(IdType.USER,
filter,
new IdSearchControl());
Set<AMIdentity> results = isr.getSearchResults();
if ((results != null) && !results.isEmpty()) {
IdSearchResults specialUsersResults =
amIr.getSpecialIdentities(IdType.USER);
results.removeAll(specialUsersResults.getSearchResults());
for (Iterator<AMIdentity> i = results.iterator();
i.hasNext(); ) {
AMIdentity amid = i.next();
System.out.println("dn: "+ amid.getDN());
System.out.println("realm: "+ amid.getRealm());
System.out.println("uid: "+ amid.getUniversalId());
System.out.println("type: "+ amid.getType());
}
}
}
} catch (AuthLoginException e) {
e.printStackTrace();
} catch (L10NMessageImpl e) {
e.printStackTrace();
} catch (IdRepoException e) {
e.printStackTrace();
}
}
You are strongly encouraged to use the ForgeRock REST APIs in preference to the Java SDK.
Have a look at the OpenAM developers guide http://openam.forgerock.org/doc/webhelp/dev-guide/rest-api-query-identity.html
The best alternative is to query the data store directly. For example, if you are using OpenDJ you could use the OpenDJ LDAP SDK, or the OpenDJ REST interface.

j2me - Filter results by two or more criteria

I'm trying to filter some records using the RecordFilter interface. In my app I have a couple of interfaces similar to this one, on which the user can enter an ID or Name (he/she could enter both or neither of them too)
Here's what I've done so far:
The Customer filter.
Here if the user didn't enter an ID, I pass 0 as a default value, that's why I evaluate customerID!=0
public class CustomerFilter implements RecordFilter {
private String mName_Filter;
private int mID_Filter;
public CustomerFilter(String name_Filter, int id_Filter) {
this.mName_Filter = name_Filter.toLowerCase();
this.mID_Filter = id_Filter;
}
public boolean matches(byte[] candidate) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(candidate);
DataInputStream dis = new DataInputStream(bis);
int customerID = dis.readInt();
String customerName = dis.readUTF().toLowerCase();
if ((customerName != null && customerName.indexOf(mName_Filter) != -1) && (customerID != 0 && customerID == mID_Filter))
return true;
if (customerName != null && customerName.indexOf(mName_Filter) != -1 && customerID == 0)
return true;
if (customerName == null && (customerID != 0 && customerID == mID_Filter))
return true;
if (customerName == null && customerID == 0)
return true;
} catch (IOException ex) {
//What's the point in catching a exception here???
}
return false;
}
}
The search method:
Note: This method is in a class that I call "RMSCustomer", in which I deal with everything related to RMS access. The search method receives two parameters (id and name) and uses them to instantiate the filter.
public Customer[] search(int id, String name) throws RecordStoreException, IOException {
RecordStore rs = null;
RecordEnumeration recEnum = null;
Customer[] customerList = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
if (rs.getNumRecords() > 0) {
CustomerFilter filter = new CustomerFilter(name, id);
try {
recEnum = rs.enumerateRecords(filter, null, false);
if (recEnum.numRecords() > 0) {
customerList = new Customer[recEnum.numRecords()];
int counter = 0;
while (recEnum.hasNextElement()) {
Customer cust;
int idRecord = recEnum.nextRecordId();
byte[] filterRecord = rs.getRecord(idRecord);
cust = parseRecord(filterRecord);
cust.idRecord = idRecord;
customerList[counter] = cust;
counter++;
}
}
else{
customerList = new Customer[0];
//How to send a message to the midlet from here
//saying something like "No Record Exists.Please select another filter"
}
} finally {
recEnum.destroy();
}
}
else{
//How to send a message to the midlet from here
//saying something like "No Record Exists.Please Add record"
}
} finally {
rs.closeRecordStore();
}
return customerList;
}
Even though, the code shown above works I still have some questions/problems:
In the Filter :
1) How can I improve the code that evaluates the possible values of the filters (name,id)? What if I had more filters?? Will I have to test all the possible combinations??
2) If the user doesn’t enter neither a ID nor a name, should I display all the records or should I display a message "Please enter a name or ID"?? What would you do in this case?
3) Why do I have to put a try-catch in the filter when I can't do anything there?? I can't show any alert from there or can I?
In the search method:
1) How can I show a proper message to the user from that method? something like "No records" (see the "ELSE" parts in my code
Sorry If I asked too many questions, it's just that there's any complete example of filters.
Thanks in advance
How can I improve the code that evaluates the possible values of the
filters (name,id)?
The ID is the first field in the record and the fastest one to search for. If the Id matches, It doesn't really matter what the customer name is. Normally you'll be looking for the records where the ID matches OR the customer name matches, so once the ID matches you can return true. This is my proposal for the CustomerFilter class:
public class CustomerFilter implements RecordFilter {
private String mName_Filter;
//Use Integer instead of int.
//This way we can use null instead of zero if the user didn't type an ID.
//This allows us to store IDs with values like 0, -1, etc.
//It is a bit less memory efficient,
//but you are not creating hundreds of filters, are you? (If you are, don't).
private Integer mID_Filter;
public CustomerFilter(String name_Filter, Integer id_Filter) {
this.mName_Filter = normalizeString(mName_Filter);
this.mID_Filter = id_Filter;
}
//You should move this function to an StringUtils class and make it public.
//Other filters might need it in the future.
private static String normalizeString(final String s){
if(s != null){
//Warning: you might want to replace accentuated chars as well.
return s.toLowerCase();
}
return null;
}
public boolean matches(byte[] candidate) {
ByteArrayInputStream bis = new ByteArrayInputStream(candidate);
DataInputStream dis = new DataInputStream(bis);
try {
if(mID_Filter != null){
//If the ID is unique, and the search is ID OR other fields, this is fine
int customerID = dis.readInt();
if(mID_Filter.intValue == customerID){
return true;
} else {
return false;
}
}
if(mName_Filter != null){
String customerName = normalizeString(dis.readUTF());
if(customerName != null && customerName.indexOf(mName_Filter) != -1){
return true;
}
}
if(mID_Filter == null && mName_Filter == null){
return true; // No filtering, every record matches.
}
} catch (IOException ex) {
//Never swallow exceptions.
//Even if you are using an underlying ByteArrayInputStream, an exception
//can still be thrown when reading from DataInputStream if you try to read
//fields that do not exists.
//But even if no exceptions were ever thrown, never swallow exceptions :)
System.err.println(ex);
//Optional: throw ex;
} finally {
//Always close streams.
if(bis != null){
try {
bis.close();
} catch(IOException ioe){
System.err.println(ioe);
}
}
if(dis != null){
try {
dis.close();
} catch(IOException ioe){
System.err.println(ioe);
}
}
}
return false;
}
}
What if I had more filters?? Will I have to test all the possible
combinations??
It depends on your project. Usually the ID is unique and no two records exist with the same id. In this case you should explicitly design the screen so that the user understands that either he types an Id, or else he fills in the other fields. The condition would be like this:
idMatches OR (field1Matches AND field2Matches AND ... fieldNMatches)
If the user types nothing, then all records will be returned.
But then again this is more a UX issue, I don't know if it is valid for your requirements.
From the programming point of view, what is clear is that the more fields you add, the more messy your filter will became. To prevent this, you could use patterns like Decorator, Composite, and even Chain of responsibility. You'll probably have to trade good design for performance though.
If the user doesn’t enter neither a ID nor a name, should I display
all the records or should I display a message "Please enter a name or
ID"?? What would you do in this case?
It depends. Is there any other way to view all records? If so, then show the message.
Why do I have to put a try-catch in the filter when I can't do
anything there?? I can't show any alert from there or can I?
You shouldn't. This class is only responsible of filtering, not of interacting with the user. You can still log the error from the catch clause, and then throw the exception again. That will propagate the exception up to RMSCustomer.search, so whatever client code is calling that function will handle the exception in the same way you are handling the other ones thrown by that method. But keep the finally clause to close the streams.
How can I show a proper message to the user from that method?
something like "No records" (see the "ELSE" parts in my code)
You shouldn't do anything related to the GUI (like showing dialogs) from the RMSCustomer class. Even if you are not using the Model-View-Controller pattern, you still want to keep your class focused on a single responsibility (managing records). This is called the Single responsibility principle.
Keeping your class isolated from the GUI will allow you to test it and reuse it in environments without GUI.
The no records case should be handled by the screen when there are zero results. An array of lenght == 0 is fine here, and the screen will show the "No results" message. For other kinds of errors, you can extend the Exception class and throw your own custom exceptions, i.e: RecordParsingException, from the RMSCustomer.search method. The screen class will then map the different exceptions to the error message in the language of the user.

Is it possible to call wcf webservice on adf mobile?

I tried to consume a wcf webservice method on adf mobile by using java api as seen as below code snippet.
I tried to run on classical adf generic application by creating webservice proxy. Then i could get response properly. But when i consume webservice method on adfmobile i get http 501 error response. I have tried using drag and drop into amx page and execute binding action, result is same.
What might be the reason?
brgds
private boolean validateClient()
{
List pnames = new ArrayList();
List pvals = new ArrayList();
List ptypes = new ArrayList();
pnames.add("UserName");
pvals.add("test");
ptypes.add(String.class);
pnames.add("Password");
pvals.add("123");
ptypes.add(String.class);
pnames.add("DeviceID");
pvals.add("123456");
ptypes.add(String.class);
GenericType result = null;
try
{
ClientDetail clientDetail = null;
result = (GenericType)AdfmfJavaUtilities.invokeDataControlMethod("mlService", null, "ValidateClient", pnames, pvals, ptypes);
for (int i = 0; i < result.getAttributeCount(); i++)
{
// Get each individual GenericType instance that holds the attribute key-value pairs
GenericType entityGenericType = (GenericType)result.getAttribute(i);
clientDetail = (ClientDetail)GenericTypeBeanSerializationHelper.fromGenericType(ClientDetail.class, entityGenericType);
}
if (clientDetail != null)
{
if (clientDetail.getIsValidate().booleanValue())
return true;
else
AdfmfContainerUtilities.invokeContainerJavaScriptFunction("com.accmee.menu", "navigator.notification.alert",
new Object[] { "No access",
"No access: ", "Ok" });
} else
{
AdfmfContainerUtilities.invokeContainerJavaScriptFunction("com.accmee.menu", "navigator.notification.alert",
new Object[] { "No access",
"No access: ", "Ok" });
return false;
}
}
catch (AdfInvocationException aie)
{
if (AdfInvocationException.CATEGORY_WEBSERVICE.compareTo(aie.getErrorCategory()) == 0)
{
throw new AdfException("Error with the server. Please try later.", AdfException.ERROR);
}
aie.printStackTrace();
throw new AdfException("Uzak veri sağlayısı çağrılırken hata oluştu", AdfException.ERROR);
}
return false;
}
make sure the WSDL URL is accessible from inside the test environment of the app ( emulator or mobile device)

How can i get call log in JavaME by ApiBridge?

I'm trying to read SMS inbox with JavaME. I tried ApiBridge, reserached the developer.nokia and I found some examples. I tried examples but i think code doesn't get the call log, just looping.
Thanks for your helps.
Here is my sample code.
APIBridge bridge = APIBridge.getInstance();
bridge.Initialize(this);
final LoggingService service = (LoggingService)bridge.createService("service.logging");
formum.append("Başlıyor\n");
Thread thread = new Thread() {
public void run() {
try {
BridgeResult res = service.GetList();
Vector returnValues = (Vector) res.getReturnValue();
String out = "Result: \n";
for (int i = 0; i < 2; i++) {
System.out.println("BridgeResult CallLog");
Hashtable item = (Hashtable) (returnValues.elementAt(i));
out += "PhoneNumber: " + item.get("PhoneNumber").toString() + "\n";
}
formum.append(out);
} catch (BridgeException ex) {
tbox.setString("Bridge error occured - unable to retrieve data. " + ex.getMessage());
} catch (Exception ex) {
tbox.setString("General error occured - unable to retrieve data. " + ex.getMessage());
}
}
};
thread.start();
And the sample code is here : http://www.developer.nokia.com/Community/Wiki/J2ME_Api_Bridge_Interface
API Bridge API is a Symbian specific solution which requires you to install both a native Symbian application the /APIBridge Installer/APIBridge_v1_1.sis on the downloaded zip. The APIBridge.jar works against the interfaces provided by APIBridge_v1_1.sis.
Since this is a Nokia Symbian specific solution it does not work for other mobile OSes and manufacturers.

Resources