I have an Android application in which i am scanning PDF417 barcode image. After scanning the Barcode i am getting the result as below.
#
ANSI 636014040002DL00410477ZC05180089DLDAQD1234562 XYXYXYXYXYXYXYXYX
DCSLASTNAMEXYXYXYXYXYXYXYXYXXYXYXYXYXYXYXYX
DDEU
DACFIRSTXYXYXYXYXYXYXYXYXXYXYXYXYXYXYXYXXYX
DDFU
DADXYXYXYXYXYXYXYXYXXYXYXYXYXYXYXYXXYXYXYXY
DDGU
DCAA XYXY
DCBNONEY1XY1XY1
DCDNONEX
DBD10312009
DBB10311977
DBA10312014
DBC1
DAU068 IN
DAYBRO
DAG1234 ANY STREET XY1XY1XY1XY1XY1XY1X
DAICITY XY1XY1XY1XY1XY1
DAJCA
DAK000000000
DCF00/00/0000NNNAN/ANFD/YY X
DCGUSA
DCUSUFIX
DAW150
DAZBLK XY1XY1XY
DCKXY1XY1XY1XY1XY1XY1XY1XY1X
DDAF
DDBMMDDCCYY
DDD1
ZCZCAY
ZCBCORR LENS
ZCCBRN
ZCDXYX
ZCEXYXYXYXYXYXYXY
ZCFXY1XY1XY1XY1XY1XY1XYXYXYXYXYXYXY
I want to get details like FirstName, LastName, City, Address etc from the above String.
Can anyone please tell me how do i get the details.
Thanks.
Please see below link and generate the parser to extract the information of driver License.
http://www.dol.wa.gov/external/docs/barcodeCalibration-EDLEID.pdf
I have make this decoder for ios app
here the code :
NSString *message=barcode.barcodeString;
NSMutableArray *arrFixedData=[[NSMutableArray alloc]initWithObjects:#"DCS",#"DCT",#"DCU",#"DAG",#"DAI",#"DAJ",#"DAK",#"DCG",#"DAQ",#"DCA",#"DCB",#"DCD",#"DCF",#"DCH",#"DBA",#"DBB",#"DBC",#"DBD",#"DAU",#"DCE",#"DAY",#"ZWA",#"ZWB",#"ZWC",#"ZWD",#"ZWE",#"ZWF", nil];
NSMutableArray *arrDriverData=[[NSMutableArray alloc]initWithObjects:#"Customer Family Name",#"Customer Given Name",#"Name Suffix",#"Street Address 1",#"City",#"Jurisdction Code",#"Postal Code",#"Country Identification",#"Customer Id Number",#"Class",#"Restrictions",#"Endorsements",#"Document Discriminator",#"Vehicle Code",#"Expiration Date",#"Date Of Birth",#"Sex",#"Issue Date",#"Height",#"Weight",#"Eye Color",#"Control Number",#"Endorsements",#"Transaction Types",#"Under 18 Until",#"Under 21 Until",#"Revision Date", nil];
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
for (int i=0; i<[arrFixedData count]; i++)
{
NSRange range = [message rangeOfString: [arrFixedData objectAtIndex:i] options: NSCaseInsensitiveSearch];
NSLog(#"found: %#", (range.location != NSNotFound) ? #"Yes" : #"No");
if (range.location != NSNotFound)
{
NSString *temp=[message substringFromIndex:range.location+range.length];
NSRange end = [temp rangeOfString:#"\n"];
if (end.location != NSNotFound)
{
temp = [temp substringToIndex:end.location];
temp =[temp stringByReplacingOccurrencesOfString:#"\n" withString:#""];
temp=[temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
NSLog(#"temp data : %#",temp);
[dict setObject:temp forKey:[arrDriverData objectAtIndex:i]];
}
}
NSLog(#"Dictionary : %#",dict);
The barcodestring contains the data which are scanned from pdf 417.
Thanks
Here's the Decoder for Android
Here, The Parameter "data" contains the string which you have to scanned pdf417.
==========Properties=============
HashMap<String, String> myData = new HashMap<String, String>();
public final String Customer_Family_Name = "DCS", Customer_Given_Name = "DCT", Name_Suffix = "DCU",
Street_Address_1 = "DAG", City = "DAI", Jurisdction_Code = "DAJ", Postal_Code = "DAK",
Country_Identification = "DCG", Customer_Id_Number = "DAQ", Class = "DCA", Restrictions = "DCB",
Endorsements = "DCD", Document_Discriminator = "DCF", Vehicle_Code = "DCH", Expiration_Date = "DBA",
Date_Of_Birth = "DBB", Sex = "DBC", Issue_Date = "DBD", Height = "DAU", Weight = "DCE", Eye_Color = "DAY",
Control_Number = "ZWA", WA_SPECIFIC_ENDORSMENT = "ZWB", Transaction_Types = "ZWC", Under_18_Until = "ZWD",
Under_21_Until = "ZWE", Revision_Date = "ZWF", Customer_Full_Name = "DAA", Customer_First_Name = "DAC",
Customer_Middle_Name = "DAD", Street_Address_2 = "DAH", Street_Address_1_optional = "DAL",
Street_Address_2_optional = "DAM";
ArrayList<String> allKeys = new ArrayList<String>();
============Methods after Scaning================
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SCAN_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
ArrayList<BarcodeResult> barcodes = data.getParcelableArrayListExtra(BarcodeScanActivity.RESULT_EXTRA);
Log.e("BARCODE RESULT ", "<<<>>" + barcodes.toString());
String barcodeResult = barcodes.get(0).barcodeString;
String lines[] = barcodeResult.split("\\r?\\n");
for (int i = 0; i < lines.length; i++)
{
String str = lines[i];
if (str.contains("ANSI"))
{
str = str.substring(str.indexOf("DL"));
String str1[] = str.split("DL");
if (str1.length > 1)
{
str = str1[str1.length - 1];
}
}
if (str.length() > 3)
{
String key = str.substring(0, 3);
String value = str.substring(3);
if (allKeys.contains(key))
{
if (!value.equalsIgnoreCase("None"))
{
myData.put(allKeys.get(allKeys.indexOf(key)), value);
}
}
}
Log.e("RESULT ", "<<>>" + lines[i]);
}
Log.e("TAG", "SO MAY BE FINAL RESULT");
if (myData.containsKey(Customer_Family_Name))
{
Log.v("TAG", "users family name:" + myData.get(Customer_Family_Name));
lname = myData.get(Customer_Family_Name).trim();
}
if (myData.containsKey(Customer_Given_Name))
{
Log.v("TAG", "users Given name:" + myData.get(Customer_Given_Name));
try
{
String CustomerName[] = myData.get(Customer_Given_Name).split(" ");
fname = CustomerName[0].trim();
mname = CustomerName[1].substring(0, 1).trim();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if (myData.containsKey(Name_Suffix))
{
Log.v("TAG", "Surname name:" + myData.get(Name_Suffix));
}
if (myData.containsKey(Street_Address_1))
{
Log.v("TAG", "Address line 1 :" + myData.get(Street_Address_1));
try
{
address = myData.get(Street_Address_1).trim();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if (TextUtils.isEmpty(address))
{
if (myData.containsKey(Street_Address_2))
{
address = myData.get(Street_Address_2).trim();
}
if (TextUtils.isEmpty(address))
{
if (myData.containsKey(Street_Address_1_optional))
{
address = myData.get(Street_Address_1_optional).trim();
}
}
if (TextUtils.isEmpty(address))
{
if (myData.containsKey(Street_Address_2_optional))
{
address = myData.get(Street_Address_2_optional).trim();
}
}
}
if (myData.containsKey(City))
{
Log.v("TAG", "City:" + myData.get(City));
city = myData.get(City).trim();
}
if (myData.containsKey(Jurisdction_Code))
{
Log.v("TAG", "State:" + myData.get(Jurisdction_Code));
State = myData.get(Jurisdction_Code).trim();
}
if (myData.containsKey(Postal_Code))
{
Log.v("TAG", "Pin Code:" + myData.get(Postal_Code));
zipcode = myData.get(Postal_Code).substring(0, 5).trim();
}
if (myData.containsKey(Date_Of_Birth))
{
Log.v("TAG", "Birth Date :" + myData.get(Date_Of_Birth));
birthday = myData.get(Date_Of_Birth).substring(0, 2) + "/" + myData.get(Date_Of_Birth).substring(2, 4)
+ "/" + myData.get(Date_Of_Birth).substring(4);
if (isThisDateValid(birthday, "MM/dd/yyyy", myData.get(Date_Of_Birth)))
Log.e("TAG", "IS VALID");
else
Log.e("TAG", "IS NOT VALID");
}
if (myData.containsKey(Sex))
{
Log.v("TAG", "Sex:" + (myData.get(Sex).toString().trim().equals("1") ? "Male" : "Female"));
}
if (myData.containsKey(Customer_Full_Name))
{
String cName = myData.get(Customer_Full_Name);
int startIndexOfComma = 0;
int endIndexOfComma = 0;
startIndexOfComma = cName.indexOf(",");
endIndexOfComma = cName.lastIndexOf(",");
if (startIndexOfComma != endIndexOfComma)
{
String CustomerName[] = myData.get(Customer_Full_Name).split(",");
lname = CustomerName[0].replace(",", "").trim();
fname = CustomerName[1].trim();
mname = CustomerName[2].substring(0, 1).trim();
}
else
{
String CustomerName[] = myData.get(Customer_Full_Name).split(" ");
lname = CustomerName[0].replace(",", "").trim();
fname = CustomerName[1].trim();
mname = CustomerName[2].substring(0, 1).trim();
}
}
if (myData.containsKey(Customer_First_Name))
{
fname = myData.get(Customer_First_Name).trim();
}
if (myData.containsKey(Customer_Middle_Name))
{
mname = myData.get(Customer_Middle_Name).substring(0, 1).trim();
}
// TODO edit here at 7/3/2014
if (myData.containsKey(Customer_Id_Number))
{
licence_number = myData.get(Customer_Id_Number).trim();
Log.e("TAG", "Licence Number is :" + licence_number);
}
if (myData.containsKey(Expiration_Date))
{
licence_expire_date = myData.get(Expiration_Date).trim();
licence_expire_date = myData.get(Expiration_Date).substring(0, 2) + "/"
+ myData.get(Expiration_Date).substring(2, 4) + "/" + myData.get(Expiration_Date).substring(4);
licence_expire_date = makeDateValid(licence_expire_date, "MM/dd/yyyy", myData.get(Expiration_Date));
Log.e("TAG", "expire date is :" + licence_expire_date);
}
etFirstName.setText(fname.trim());
etMiddleName.setText(mname.trim());
etLastName.setText(lname.trim());
etAddress.setText(address.trim());
etZipCode.setText(zipcode.trim());
etCity.setText(city.trim());
etState.setText(State.trim());
etDLNumber.setText(licence_number);
etDLExpirationDate.setText(licence_expire_date);
etBirthDay.setText(birthday.trim());
}
}
Here's the code I use to decode the PDF417 data in Swift.
private let pdf417Map: [String: String] = [
"DAA":"Full Name",
"DAB":"Family Name",
"DAC":"Given Name",
"DAD":"Middle Name",
"DAE":"Name Suffix",
"DAF":"Name Prefix",
"DAG":"Mailing Street Address1",
"DAH":"Mailing Street Address2",
"DAI":"Mailing City",
"DAJ":"Mailing Jurisdiction Code",
"DAK":"Mailing Postal Code",
"DAL":"Residence Street Address1",
"DAM":"Residence Street Address2",
"DAN":"Residence City",
"DAO":"Residence Jurisdiction Code",
"DAP":"Residence Postal Code",
"DAQ":"License or ID Number",
"DAR":"License Classification Code",
"DAS":"License Restriction Code",
"DAT":"License Endorsements Code",
"DAU":"Height in FT_IN",
"DAV":"Height in CM",
"DAW":"Weight in LBS",
"DAX":"Weight in KG",
"DAY":"Eye Color",
"DAZ":"Hair Color",
"DBA":"License Expiration Date",
"DBB":"Date of Birth",
"DBC":"Sex",
"DBD":"License or ID Document Issue Date",
"DBE":"Issue Timestamp",
"DBF":"Number of Duplicates",
"DBG":"Medical Indicator Codes",
"DBH":"Organ Donor",
"DBI":"Non-Resident Indicator",
"DBJ":"Unique Customer Identifier",
"DBK":"Social Security Number",
"DBL":"Date Of Birth",
"DBM":"Social Security Number",
"DBN":"Full Name",
"DBO":"Family Name",
"DBP":"Given Name",
"DBQ":"Middle Name or Initial",
"DBR":"Suffix",
"DBS":"Prefix",
"DCA":"Virginia Specific Class",
"DCB":"Virginia Specific Restrictions",
"DCD":"Virginia Specific Endorsements",
"DCE":"Physical Description Weight Range",
"DCF":"Document Discriminator",
"DCG":"Country territory of issuance",
"DCH":"Federal Commercial Vehicle Codes",
"DCI":"Place of birth",
"DCJ":"Audit information",
"DCK":"Inventory Control Number",
"DCL":"Race Ethnicity",
"DCM":"Standard vehicle classification",
"DCN":"Standard endorsement code",
"DCO":"Standard restriction code",
"DCP":"Jurisdiction specific vehicle classification description",
"DCQ":"Jurisdiction-specific",
"DCR":"Jurisdiction specific restriction code description",
"DCS":"Last Name",
"DCT":"First Name",
"DCU":"Suffix",
"DDA":"Compliance Type",
"DDB":"Card Revision Date",
"DDC":"HazMat Endorsement Expiry Date",
"DDD":"Limited Duration Document Indicator",
"DDE":"Family Name Truncation",
"DDF":"First Names Truncation",
"DDG":"Middle Names Truncation",
"DDH":"Under 18 Until",
"DDI":"Under 19 Until",
"DDJ":"Under 21 Until",
"DDK":"Organ Donor Indicator",
"DDL":"Veteran Indicator",
"PAA":"Permit Classification Code",
"PAB":"Permit Expiration Date",
"PAC":"Permit Identifier",
"PAD":"Permit IssueDate",
"PAE":"Permit Restriction Code",
"PAF":"Permit Endorsement Code",
"ZVA":"Court Restriction Code"
]
// metadataObj = # ANSI 63601404....
if metadataObj.stringValue != nil {
let licenseData = metadataObj.stringValue!.components(separatedBy: "\n")
var customerProfile: [[String: String]] = []
for item in licenseData {
var metaDataItem = item
if metaDataItem.count > 3 {
if let dlCodeRange = metaDataItem.range(of: "DAQ") {
let dlStart = dlCodeRange.lowerBound
let dlEnd = metaDataItem.index(metaDataItem.endIndex, offsetBy: 0)
let dlNoRange = dlStart..<dlEnd
metaDataItem = String(metaDataItem[dlNoRange])
}
// Get the 3 letter code
let pdf417Code = String(metaDataItem.prefix(3))
// See if the code exists in the map
if pdf417Map[pdf417Code] != nil {
// Code exists in map, save to profile
let start = metaDataItem.index(metaDataItem.startIndex, offsetBy: 3)
let end = metaDataItem.index(metaDataItem.endIndex, offsetBy: 0)
let range = start..<end
let extractedData = metaDataItem[range]
customerProfile.append([pdf417Map[pdf417Code]!: String(extractedData)])
}
}
}
print("customerProfile: \(customerProfile)")
}
Please look into this Link having decoder for driver license in Java. It might help.
Related
I am working with HashMap and don't have much experience yet.
I am trying to write a csvFile for proof of a comparison between two lists.
If the compared value is the same ok otherwise not ok.
Simple, but the values "ok" or "not ok" need to be changed automatically, so it was suggested to me to use HashMap where I put the name of the compared field which is the key and the value will be its state (ok or not ok).
So far the values are returned and the file is written, but the status does not fill in automatically.
This is my code so far, if anyone knows how I can do it or has other suggestions please let me know.
HashMap
public static Map<String, String> initMap(String status) {
Map<String, String> mapFields = new HashMap<String, String>();
mapFields.put("Book Ref", status);
mapFields.put("Trade Date", status);
mapFields.put("Start Date", status);
mapFields.put("End Date", status);
mapFields.put("Period Multiplier", status);
mapFields.put("Notional", status);
mapFields.put("Currency", status);
mapFields.put("Rate", status);
mapFields.put("Frequency Multiplier", status);
mapFields.put("Day count", status);
return mapFields;
}
Here in the same class, I created this method to compare two lists and define if it is ok or not.
public static void compareValues(List<String> inputs, List<String> outputs, XrayFields fields, TradeData data, MKTWireIRS mkt) throws ParseException, InterruptedException {
int y = 0;
int x = 0;
Map<String, String> map = new HashMap<String, String>();
// List<WriterCSV> writeCSV = new ArrayList<>();
WriterCSV cv = new WriterCSV();
try {
for (String input : inputs) {
for (String out : outputs) {
cv = new WriterCSV();
map = new HashMap<String, String>();
if (y == x) {
if (input.equals(out)) {
System.out.println("ok: " + input + " = " + out);
String comment = "All fields checked are ok";
fields.setComment(comment);
fields.setStatus("PASS");
cv.setOk("Ok");
map = initMap(cv.getOk());
} else {
System.out.println("not ok: " + input + " = " + out);
fields.setStatus("FAIL");
String comment = "The value " + input + " is not the same as " + out;
fields.setComment(comment);
cv.setOk("not Ok");
map = initMap(cv.getOk());
}
}
x = x + 1; // count of the list of output
}
y = y + 1; // count of the list of inputs
x = 0; // reset to 0 the count of outputs
}
//create evidence of comparison
cv.reportMKTWireToOutputIRS(data, mkt, map);
} catch (Error e) {
System.out.println(e);
}
}
This is the method for writing the csv.
public void reportMKTWireToOutputIRS(TradeData data2, MKTWireIRS mkt, Map<String, String> map ) throws ParseException, InterruptedException {
try {
FileWriter fw = new FileWriter(new File(CSV_MKTWire + Setup.IRScsv));
CSVWriter cw = new CSVWriter(fw);
//format values
String month = PropertyNames.deCapitalize(data2.getPeriod());
String monthReset = PropertyNames.deCapitalize(data2.getResetFrequencyPeriod());
String formatTradeDateMKT = Utils.formatDateToCompareMKTWire(data2.getTradeDateIRS());
String formatStartDateMKT = Utils.formatDateToCompareMKTWire(data2.getStart_Date());
String formatMAturityDateMKT = Utils.formatDateToCompareMKTWire(data2.getMaturity_Date());
String rateActual = Utils.roundDecimal(data2.getRateIRS());
String rateFormat = Utils.roundRateMKTwire(mkt.getRateIRS());
String notionalFormat = data2.getNotional().charAt(0) + "M";
String[] headers = { "Output Field", "Output Value", " MKTWire Field", " MKTWire Value", "Status" };
List<String[]> data = new ArrayList<String[]>();
String[] book = { "Book Ref", data2.getBookRef() + data2.getBookType(),"Book MKTWire",mkt.getBookIRS(), map.get("Book Ref")};
String[] tradeDate = { "Trade Date", formatTradeDateMKT,"Trade Date MKTWire",mkt.getTradeDateIRS(), map.get("Trade Date")};
String[] startDate = { "Start Date", formatStartDateMKT, "Start Date MKTWire",mkt.getStartDate(), map.get("Start Date") };
String[] maturity = { "End Date", formatMAturityDateMKT, "End Date MKTWire",mkt.getEndDate(), map.get("End Date") };
String[] tenor = { "Period Multiplier", data2.getPeriodMultiplier() + month, "Tenor MKTWire",mkt.getTenorIRS(), map.get("Period Multiplier") };
String[] notional = { "Notional", notionalFormat, "Notional MKTWire", mkt.getNotionalValueIRS(), map.get("Notional") };
String[] currency = { "Currency", data2.getCurrencyIRS(), "Currency MKTWire", mkt.getCurrencyIRS(), map.get("Currency") };
String[] rate = { "Rate", rateActual, "Rate MKTWire", rateFormat, map.get("Rate") };
String[] resetFrequency = { "Frequency Multiplier", data2.getResetFrequencyMultiplier() + monthReset, "Frequency Multiplier MKTWire", mkt.getResetFrequencyIRS(),map.get("Frequency Multiplier") };
String[] dayCount = { "Day Count", data2.getDayCount(), "Day Count MKTWire", mkt.getDayCountIRS(), map.get("Day count") };
data.add(headers);
data.add(book);
data.add(tradeDate);
data.add(startDate);
data.add(maturity);
data.add(tenor);
data.add(notional);
data.add(currency);
data.add(rate);
data.add(resetFrequency);
data.add(dayCount);
cw.writeAll(data);
cw.flush();
fw.flush();
cw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You are having one map and you are calling the initMap method which sets the value for all keys in the map within a loop, in the end it will have either "ok" or "not ok" based on your final loop validation.
how would I modify the following code so that it grabs the name(which it already does) and the mobile number from Android contacts? I would like the phone number labeled as mobile in contacts.
private ArrayList<ContactInfo> getLegalContacts() {
ArrayList<ContactInfo> legalContacts = new ArrayList<>();
List<String> contacts = loadLegalContacts();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber != null) {
phoneNumber = phoneNumber.replace("(", "");
phoneNumber = phoneNumber.replace(")", "");
phoneNumber = phoneNumber.replace("-", "");
phoneNumber = phoneNumber.replace(" ", "");
phoneNumber = phoneNumber.replace("+", "");
}
if (contacts.contains(id)) {
ContactInfo info = new ContactInfo(id, name, phoneNumber, true);
boolean isNew = true;
for (int i = 0; i < legalContacts.size(); i++) {
if (TextUtils.equals(legalContacts.get(i).name, name)) {
isNew = false;
break;
}
}
if (isNew) {
legalContacts.add(info);
}
}
}
phones.close();
return legalContacts;
}
private List<String> loadLegalContacts() {
List<String> contacts = new ArrayList<>();
Set<String> set = SharedPrefUtil.getInstance().getStringSet("LegalContacts");
if (set != null) {
contacts.addAll(set);
}
return contacts;
}
You can do it like this
private ArrayList<ContactInfo> getLegalContacts() {
ArrayList<ContactInfo> legalContacts = new ArrayList<>();
List<String> contacts = loadLegalContacts();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String labelString = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
if(labelString!=null)
{
int type = Integer.parseInt(labelString);
if(type==ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
Log.d("LableTag", " lable is : " + type);
if (phoneNumber != null) {
phoneNumber = phoneNumber.replace("(", "");
phoneNumber = phoneNumber.replace(")", "");
phoneNumber = phoneNumber.replace("-", "");
phoneNumber = phoneNumber.replace(" ", "");
phoneNumber = phoneNumber.replace("+", "");
}
if (contacts.contains(id)) {
ContactInfo info = new ContactInfo(id, name, phoneNumber, true);
boolean isNew = true;
for (int i = 0; i < legalContacts.size(); i++) {
if (TextUtils.equals(legalContacts.get(i).getName(), name)) {
isNew = false;
break;
}
}
if (isNew) {
legalContacts.add(info);
}
}
}
}
}
phones.close();
return legalContacts;
}
labelString will hold the value of currently it is labeled as
Then we need to check whether it is a mobile type if true then we access it and add it to list
For more info visit ContactsContract.CommonDataKinds.Phone
I would like to build an app, that checks all the available WiFi networks,
If a network's SSID matches a search key then connect to that network, if two networks match then connect to the one with the higher signal strength.
e.g. SearchKey = "Open";
here is the code to check check all the wifi names :
if (networkInfo.isConnected()) {
ArrayList<ScanResult> mItems = new ArrayList<ScanResult>();
List<ScanResult> results = wifiManager.getScanResults();
int size = results.size();
HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
try {
for (int i = 0; i < size; i++) {
ScanResult result = results.get(i);
if (!result.SSID.isEmpty()) {
String key = result.SSID + " " + result.capabilities;
Log.i("TAG", "ssid: " + result.SSID + " | level: " + result.level);
}
Then I would need to
Arrays.asList(mItems).contains("Open")
I am stuck here, How to do a proper check if the keyword "Open" exits, if so, then get the whole name and use below. ?
online sample how to conenct.
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);
WifiManager wifiManager = (WifiManager).getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
UPDATE CODE ------------------------------ - --------------------------------- - -- ---------------------------------------
How to check, This works But Now I need to implement Search by signal strength
if (!result.SSID.isEmpty()) {
String key = result.SSID + " " + result.capabilities;
Log.i("TAG", "ssid: " + result.SSID + " | level: " + result.level);
if(result.SSID.contains("Open")) {
String useSSID = result.SSID;
Log.w(TAG, "useSSID => " + useSSID);
connectToWifi(MainActivity.this, useSSID);
break;
}
else { Log.e(TAG, "NO result contains"); }
Now how can I query my :
ArrayList<ScanResult> mItems = new ArrayList<ScanResult>();
if (!signalStrength.containsKey(key)) {
signalStrength.put(key, i);
mItems.add(result);
} else {
int position = signalStrength.get(key);
ScanResult updateItem = mItems.get(position);
if (calculateSignalStength(wifiManager, updateItem.level) > calculateSignalStength(wifiManager, result.level)) {
mItems.set(position, updateItem);
}
}
if(mItems.contains("Open")) {
String useSSID = mItems #how to the name SSID name from mItems ???
Log.w(TAG, "useSSID => " + useSSID);
connectToWifi(MainActivity.this, useSSID);
break;
}
else { Log.e(TAG, "NO result contains"); }
=== Now my question is how to the SSID name from mItems ?
Thanks guys for your help.
Here is a snippet for the same:
public string getValidSSID()
{
List<ScanResult> results = wifiManager.getScanResults();
HashMap<String,ScanResult> distinctNetworks = new HashMap<String, ScanResult>();
for(ScanResult scanResult : results)
{
if(scanResult.SSID.contains("Open"))
{
if(!distinctNetworks.containsKey(scanResult))
{
distinctNetworks.put(scanResult.SSID, scanResult);
}
else
{
if(WifiManager.compareSignalLevel(scanResult.level, distinctNetworks.get(scanResult.SSID).level)>0)
{
distinctNetworks.put(scanResult.SSID, scanResult);
}
}
}
}
Set<String> networks = distinctNetworks.keySet();// This will only contain one key which will be ths ssid with the max strength containing "open" in SSID
for (String s : networks) {
return s;
}
}
Java - Serialization - Grabbing number of objects in file
I'm trying to retrieve my objects from my serialized file and re-add them to my file. There seems to be an issue, no exception is being thrown but nothing is being printed in my console when running my method. Before continuing here is my code:
public boolean openCollection(){
try {
FileInputStream e = new FileInputStream("profiles.ser");
ObjectInputStream inputStream = new ObjectInputStream(e);
List<Profile> profiles = (List<Profile>) inputStream.readObject();
//De-obscure
for(Profile p : profiles){
String unObcName = deobscure(p.getName()); //Original name
String unObcSurname = deobscure(p.getSurname()); //Original surname
String unObcUsername = deobscure(p.getUsername()); //Original username
String unObcPassword = deobscure(p.getPassword()); //Original password
p.setName(unObcName);
p.setSurname(unObcSurname);
p.setUsername(unObcUsername);
p.setPassword(unObcPassword);
//Debugging
System.out.println("DE-OBSCURE - Profile name: " + p.getName() +"\n"+
"Profile surname: " + p.getSurname() +"\n"+
"Profile username: " + p.getUsername() +"\n"+
"Profile password: " + p.getPassword());
this.profiles.add(p);
}
} catch (FileNotFoundException var3) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JOptionPane.showMessageDialog(null, "No profiles found, please create a profile!");
final CreateProfile createProfile = new CreateProfile();
createProfile.setVisible(true);
}
});
return false;
} catch (IOException var4) {
var4.printStackTrace();
JOptionPane.showMessageDialog(null, "IO Exception");
return false;
} catch (ClassNotFoundException var5) {
var5.printStackTrace();
JOptionPane.showMessageDialog(null, "Required class not found");
return false;
}
return true;
}
This is the serialization method
public void saveCollection(){
//Obscure the data
List<Profile> saveProfiles = new ArrayList<>();
for(Profile p : profiles){
String obcName = obscure(p.getName());
String obcSurname = obscure(p.getSurname());
String obcUsername = obscure(p.getUsername());
String obcPassword = obscure(p.getPassword());
p.setName(obcName);
p.setSurname(obcSurname);
p.setUsername(obcUsername);
p.setPassword(obcPassword);
//Debugging
System.out.println("DEBUG - Profile name: " + p.getName() + "\n" +
"Profile surname: " + p.getSurname() + "\n" +
"Profile username: " + p.getUsername() + "\n" +
"Profile password: " + p.getPassword());
saveProfiles.add(p);
}
//Save it
try {
FileOutputStream e = new FileOutputStream("profiles.ser");
ObjectOutputStream outputStream = new ObjectOutputStream(e);
outputStream.writeObject(saveProfiles);
outputStream.flush();
outputStream.close();
} catch (IOException var3) {
var3.printStackTrace();
JOptionPane.showMessageDialog(null, "Error. Cannot save database.");
}
}
When creating a profile the details are being obscured properly, here are the results:
DEBUG - Profile name: OBF:1u2a1toa1w8v1tok1u30
Profile surname: OBF:1u2a1toa1w8v1tok1u30
Profile username: OBF:1u2a1toa1w8v1tok1u30
Profile password: OBF:1u2a1toa1w8v1tok1u30
However when running openCollection() nothing is being printed into the console.
NOTE: The profile details were all 'admin' which is why all the data looks the same
After a while checking things out I figured out that the issue was simply with my deobscuring method. I have now edited it and replace it with the following:
/**
* #param str Obscured String
* #return Unobscured String
*/
private String deobscure(String s){
if (s.startsWith(__OBFUSCATE)) s = s.substring(4);
byte[] b = new byte[s.length() / 2];
int l = 0;
for (int i = 0; i < s.length(); i += 4)
{
if (s.charAt(i)=='U')
{
i++;
String x = s.substring(i, i + 4);
int i0 = Integer.parseInt(x, 36);
byte bx = (byte)(i0>>8);
b[l++] = bx;
}
else
{
String x = s.substring(i, i + 4);
int i0 = Integer.parseInt(x, 36);
int i1 = (i0 / 256);
int i2 = (i0 % 256);
byte bx = (byte) ((i1 + i2 - 254) / 2);
b[l++] = bx;
}
}
return new String(b, 0, l,StandardCharsets.UTF_8);
}
Original Profile name: "Admin"
Obscured Profile name: "OBF:1npu1toa1w8v1tok1nsc
After de-obscuring Profile name: "Admin"
Thus the method now works as intended.
I am currently having issues in attempting to display data (i.e. itemSummaries with a certain ContainerType) for sites that are ISP, as an example, www.telstra.com.au from Australia
Logging into the site works fine, and the credentials for the site work fine (in other words, it does a refresh which succeeds), however there doesn't appear to be a way to display the itemSummary data
The soap command getItemSummaries, doesn't display data for the item (it displays item data from financial institutions fine). Upon examining the sample code provided by Yodlee for the java soap api, you are meant to use the getItemSummaries1 along with setting ContainerTypes using a SummaryRequest
The problem is that this returns a CoreExceptionFaultMessage. The getItemSummaries1 command is causing the CoreExceptionFaultError. Using different ContainerTypes with different combinations (i.e. ISP, Telephone, Bills) didn't alleviate the issue
The same error message is returned in Yodlees own sample code, i.e. java_soap_example (run the com.yodlee.sampleapps.accountsummary.DisplayBillsData main method and provide the Yodlee login info as command line arguments)
As a reference, the code that is provided by Yodlee sample app is below
Running the getItemSummaries1 command
public void displayBillsData (UserContext userContext)
{
/*SummaryRequest sr = new SummaryRequest(
new String[] {ContainerTypes.BILL, ContainerTypes.TELEPHONE},
new DataExtent[] { DataExtent.getDataExtentForAllLevels(),DataExtent.getDataExtentForAllLevels() }
);*/
SummaryRequest sr = new SummaryRequest();
List list = new List();
list.setElements(new String[] {ContainerTypesHelper.BILL, ContainerTypesHelper.TELEPHONE});
sr.setContainerCriteria(list);
Object[] itemSummaries = null;
List itemSummariesList = null;
try {
itemSummariesList = dataService.getItemSummaries1(userContext, sr);
if (itemSummariesList != null){
itemSummaries = itemSummariesList.getElements();
}
} catch (StaleConversationCredentialsExceptionFault e) {
e.printStackTrace();
} catch (InvalidConversationCredentialsExceptionFault e) {
e.printStackTrace();
} catch (CoreExceptionFault e) {
e.printStackTrace();
} catch (IllegalArgumentTypeExceptionFault e) {
e.printStackTrace();
} catch (IllegalArgumentValueExceptionFault e) {
e.printStackTrace();
} catch (InvalidUserContextExceptionFault e) {
e.printStackTrace();
} catch (IllegalDataExtentExceptionFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
if (itemSummaries == null || itemSummaries.length == 0) {
System.out.println ("No bills data available");
return;
}
for (int i = 0; i < itemSummaries.length; i++) {
ItemSummary is = (ItemSummary) itemSummaries[i];
displayBillsDataForItem(is);
// Dump the BillsData Object
// dumpBillsDataForItem(is);
}
}
Printing the item data
public void displayBillsDataForItem (ItemSummary is)
{
String containerType = is.getContentServiceInfo ().
getContainerInfo ().getContainerName ();
System.out.println("containerType = " + containerType );
if (!(containerType.equals(ContainerTypesHelper.BILL ) || containerType.equals(ContainerTypesHelper.TELEPHONE)
|| containerType.equals(ContainerTypesHelper.MINUTES))) {
throw new RuntimeException ("displayBillsDataForItem called with " +
"invalid container type: " + containerType);
}
DisplayItemInfo displayItemInfo = new DisplayItemInfo ();
System.out.println("DisplayItemInfo:");
displayItemInfo.displayItemSummaryInfo (is);
System.out.println("");
ItemData id = is.getItemData();
if(id == null){
System.out.println("ItemData == null");
}else{
List accountsList = id.getAccounts();
Object[] accounts = null;
if (accountsList != null){
accounts = accountsList.getElements();
}
if (accounts == null || accounts.length == 0) {
System.out.println ("\tNo accounts");
}else {
for (int accts = 0; accts < accounts.length; accts++) {
BillsData billsData = (BillsData) accounts[accts];
System.out.println("\tAccount Holder: " + billsData.getAccountHolder() );
System.out.println("\tAccount Id: " + billsData.getAccountId());
System.out.println("\tItemAccountId: " + billsData.getItemAccountId() );
System.out.println("\tAccountName: " + billsData.getAccountName() );
System.out.println("\tAccountNumber: " + billsData.getAccountNumber() );
System.out.println("");
// Get List of Bill Objects
List billsList = billsData.getBills();
Object[] bills = null;
if (billsList != null){
bills = billsList.getElements();
}
if (bills == null || bills.length == 0) {
System.out.println ("\t\tNo Bill objects");
}else {
for (int b = 0; b < bills.length; b++) {
Bill bill = (Bill) bills[b];
System.out.println("\t\tBill Account Number: " + bill.getAccountNumber() );
System.out.println("\t\tBill Acct Type: " + bill.getAcctType() );
System.out.println("\t\tBill Due Date: " + Formatter.formatDate(bill.getDueDate().getDate(), Formatter.DATE_SHORT_FORMAT) );
System.out.println("\t\tBill Date: " + Formatter.formatDate(bill.getBillDate().getDate(), Formatter.DATE_SHORT_FORMAT) );
System.out.println("\t\tBill Past Due: "
+ (bill.getPastDue() != null ? bill
.getPastDue().getAmount() : 0.0));
System.out
.println("\t\tBill Last payment: "
+ (bill.getLastPayment() != null ? bill
.getLastPayment()
.getAmount()
: 0.0));
System.out.println("\t\tBill Amount Due: "
+ (bill.getAmountDue() != null ? bill
.getAmountDue().getAmount() : 0.0));
System.out
.println("\t\tBill Min Payment: "
+ (bill.getMinPayment() != null ? bill
.getMinPayment()
.getAmount()
: 0.0));
System.out.println("");
// Get List of AccountUsageData
List acctUsageDataList = bill.getAccountUsages();
Object[] acctUsageData = null;
if (acctUsageDataList != null){
acctUsageData = acctUsageDataList.getElements();
}
if (acctUsageData == null || acctUsageData.length == 0) {
System.out.println ("\t\t\tNo AccountUsageData objects");
}else {
for (int usage = 0; usage < acctUsageData.length; usage++) {
AccountUsageData aud = (AccountUsageData) acctUsageData[usage];
System.out.println("\t\t\tAccount Usage Bill ID: " + aud.getBillId() );
System.out.println("\t\t\tAccount Usage Units Used: " + aud.getUnitsUsed() );
}
}
}
}
System.out.println("");
// Get List of AccountUsageData
List acctUsageDataList = billsData.getAccountUsages();
Object[] acctUsageData = null;
if (acctUsageDataList != null){
acctUsageData = acctUsageDataList.getElements();
}
if (acctUsageData == null || acctUsageData.length == 0) {
System.out.println ("\t\tNo AccountUsageData objects");
}else {
for (int usageData = 0; usageData < acctUsageData.length; usageData++) {
AccountUsageData aud = (AccountUsageData) acctUsageData[usageData];
System.out.println("\t\tAccount Usage Bill ID: " + aud.getBillId() );
System.out.println("\t\tAccount Usage Units Used: " + aud.getUnitsUsed() );
}
}
}
}
}
}
EDIT2:
I have updated the getItemSummaries1 command to look like this
ContainerCriteria bills = new ContainerCriteria();
ContainerCriteria telephone = new ContainerCriteria();
ContainerCriteria isp = new ContainerCriteria();
ContainerCriteria utilities = new ContainerCriteria();
bills.setContainerType(ContainerTypesHelper.BILL);
telephone.setContainerType(ContainerTypesHelper.TELEPHONE);
isp.setContainerType(ContainerTypesHelper.ISP);
utilities.setContainerType(ContainerTypesHelper.UTILITIES);
Object[] containerList = {
bills,telephone,isp,utilities
};
SummaryRequest sr = new SummaryRequest();
List list = new List();
list.setElements(containerList);
sr.setContainerCriteria(list);
The command now executes and works correctly, however its returning a list of 0 elements (using DataExtents with different values didn't change anything). My suspicion is that Telstra.com.au site is broken on Yodlee's end (when a full refresh is done on the Telstra site, Yodlee returns a null for refreshing that specific site).
So far I can see some deviation, so do modify your container criteria as mentioned below
object[] list = {
new ContainerCriteria { containerType = "bills" },
new ContainerCriteria { containerType = "telephone" }
};
sr.containerCriteria = list;
You may additionally provide data extent as follows
DataExtent de = new DataExtent();
dataExtent.startLevel = 0; //as per your needs
dataExtent.endLevel = 0; //as per your needs
object[] list = {
new ContainerCriteria { containerType = "bills", dataExtent = de },
new ContainerCriteria { containerType = "telephone", dataExtent = de }
};
sr.containerCriteria = list;
This should solve your issue. If not then try to get the detail which is is node in the response for the CoreExceptionFaultMessage, this detail may help to diagnose the accurate issue.
To get data for any of the container first you need to add an account for the site belonging to that container. Once you have added the account successfully then only you will be able to pull in the data for such container. Also you can check the tag returned in the getItemSummaries API which has and once this statusCode = 0 then only you have data present for that account.
You can do testing by using the Dummy account which yodlee provides. Please refer to Yodlee Dummy account generator page for more info on Dummy accounts.