How to retrieve font name from TTF file for Android - android

There are example for Java (but using java.awt sth) and C#; it seems that getting a name from TTF file should be no pain. But unfortunately it is not. Please help.

Please using class:
class TTFAnalyzer
{
// This function parses the TTF file and returns the font name specified in the file
public String getTtfFontName( String fontFilename )
{
try
{
// Parses the TTF file format.
// See http://developer.apple.com/fonts/ttrefman/rm06/Chap6.html
m_file = new RandomAccessFile( fontFilename, "r" );
// Read the version first
int version = readDword();
// The version must be either 'true' (0x74727565) or 0x00010000
if ( version != 0x74727565 && version != 0x00010000 )
return null;
// The TTF file consist of several sections called "tables", and we need to know how many of them are there.
int numTables = readWord();
// Skip the rest in the header
readWord(); // skip searchRange
readWord(); // skip entrySelector
readWord(); // skip rangeShift
// Now we can read the tables
for ( int i = 0; i < numTables; i++ )
{
// Read the table entry
int tag = readDword();
readDword(); // skip checksum
int offset = readDword();
int length = readDword();
// Now here' the trick. 'name' field actually contains the textual string name.
// So the 'name' string in characters equals to 0x6E616D65
if ( tag == 0x6E616D65 )
{
// Here's the name section. Read it completely into the allocated buffer
byte[] table = new byte[ length ];
m_file.seek( offset );
read( table );
// This is also a table. See http://developer.apple.com/fonts/ttrefman/rm06/Chap6name.html
// According to Table 36, the total number of table records is stored in the second word, at the offset 2.
// Getting the count and string offset - remembering it's big endian.
int count = getWord( table, 2 );
int string_offset = getWord( table, 4 );
// Record starts from offset 6
for ( int record = 0; record < count; record++ )
{
// Table 37 tells us that each record is 6 words -> 12 bytes, and that the nameID is 4th word so its offset is 6.
// We also need to account for the first 6 bytes of the header above (Table 36), so...
int nameid_offset = record * 12 + 6;
int platformID = getWord( table, nameid_offset );
int nameid_value = getWord( table, nameid_offset + 6 );
// Table 42 lists the valid name Identifiers. We're interested in 4 but not in Unicode encoding (for simplicity).
// The encoding is stored as PlatformID and we're interested in Mac encoding
if ( nameid_value == 4 && platformID == 1 )
{
// We need the string offset and length, which are the word 6 and 5 respectively
int name_length = getWord( table, nameid_offset + 8 );
int name_offset = getWord( table, nameid_offset + 10 );
// The real name string offset is calculated by adding the string_offset
name_offset = name_offset + string_offset;
// Make sure it is inside the array
if ( name_offset >= 0 && name_offset + name_length < table.length )
return new String( table, name_offset, name_length );
}
}
}
}
return null;
}
catch (FileNotFoundException e)
{
// Permissions?
return null;
}
catch (IOException e)
{
// Most likely a corrupted font file
return null;
}
}
// Font file; must be seekable
private RandomAccessFile m_file = null;
// Helper I/O functions
private int readByte() throws IOException
{
return m_file.read() & 0xFF;
}
private int readWord() throws IOException
{
int b1 = readByte();
int b2 = readByte();
return b1 << 8 | b2;
}
private int readDword() throws IOException
{
int b1 = readByte();
int b2 = readByte();
int b3 = readByte();
int b4 = readByte();
return b1 << 24 | b2 << 16 | b3 << 8 | b4;
}
private void read( byte [] array ) throws IOException
{
if ( m_file.read( array ) != array.length )
throw new IOException();
}
// Helper
private int getWord( byte [] array, int offset )
{
int b1 = array[ offset ] & 0xFF;
int b2 = array[ offset + 1 ] & 0xFF;
return b1 << 8 | b2;
}
}
codes from http://www.ulduzsoft.com/2012/01/enumerating-the-fonts-on-android-platform/
note that it does not work for all ttf files.

Related

Why when reading NFCtag with Android phone you get different tag ID then when reading with dedicated reader?

I am using an Android Cilico F750 and the dedicated RFID reader is CF-RS103.
The RFID tag type is MIFARE Ultralight type C.
When read with a dedicated card reader the id of tag is: 2054270212(10 digit).
But when read with Android phone the id is: 36139312876727556(17digit) and reversed id is: 1316602805183616 (16digit).
Does anyone know why this happens and if its possible to convert the 10digit id to 17digit id or vice versa.
I use intents to detect tag and to resolve intent I use this:
public void resolveIntent(Intent intent){
String action = intent.getAction();
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
||NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
||NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
{
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs;
if(rawMsgs!=null)
{
msgs= new NdefMessage[rawMsgs.length];
for(int i=0; i<rawMsgs.length; i++)
{
msgs[i]=(NdefMessage) rawMsgs[i];
}
}
else
{
byte[] empty = new byte[0];
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] payload = dumpTagData(tag).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,empty,id,payload);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
msgs= new NdefMessage[] {msg};
}
displayMsgs(msgs);
}}
And this are my helper functions:
private void displayMsgs(NdefMessage[] msgs)
{
if(msgs==null || msgs.length==0) {
return;
}
StringBuilder builder = new StringBuilder();
List<ParsedNdefRecord> records= NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for(int i=0;i<size;i++)
{
ParsedNdefRecord record = records.get(i);
String str = record.str();
builder.append(str).append("\n");
}
text.setText(builder.toString());
}
private String dumpTagData(Tag tag) {
StringBuilder sb = new StringBuilder();
byte[] id = tag.getId();
sb.append("ID (hex): ").append(toHex(id)).append('\n');
sb.append("ID (reversed hex):").append(toReversedHex(id)).append('\n');
sb.append("ID (dec): ").append(toDec(id)).append('\n');
sb.append("ID (reversed dec):").append(toReversedDec(id)).append('\n');
String prefix = "android.nfc.tech.";
sb.append("Technologies: ");
for (String tech: tag.getTechList()) {
sb.append(tech.substring(prefix.length()));
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
for (String tech: tag.getTechList()) {
if (tech.equals(MifareClassic.class.getName())) {
sb.append('\n');
String type = "Unknown";
try {
MifareClassic mifareTag = MifareClassic.get(tag);
switch (mifareTag.getType()) {
case MifareClassic.TYPE_CLASSIC:
type = "Classic";
break;
case MifareClassic.TYPE_PLUS:
type = "Plus";
break;
case MifareClassic.TYPE_PRO:
type = "Pro";
break;
}
sb.append("Mifare Classic type: ");
sb.append(type);
sb.append('\n');
sb.append("Mifare size: ");
sb.append(mifareTag.getSize() + " bytes");
sb.append('\n');
sb.append("Mifare sectors: ");
sb.append(mifareTag.getSectorCount());
sb.append('\n');
sb.append("Mifare blocks: ");
sb.append(mifareTag.getBlockCount());
} catch (Exception e) {
sb.append("Mifare classic error: " + e.getMessage());
}
}
if (tech.equals(MifareUltralight.class.getName())) {
sb.append('\n');
MifareUltralight mifareUlTag = MifareUltralight.get(tag);
String type = "Unknown";
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
type = "Ultralight";
break;
case MifareUltralight.TYPE_ULTRALIGHT_C:
type = "Ultralight C";
break;
}
sb.append("Mifare Ultralight type: ");
sb.append(type);
}
}
return sb.toString();
}
private String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = bytes.length - 1; i >= 0; --i) {
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
if (i > 0) {
sb.append(" ");
}
}
return sb.toString();
}
private String toReversedHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
if (i > 0) {
sb.append(" ");
}
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
}
return sb.toString();
}
private long toDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i < bytes.length; ++i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private long toReversedDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = bytes.length - 1; i >= 0; --i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}`
EDIT: I managed to resolve this issue by truncating the 7-byte HEX ID to 4-bytes.
And then formating the decimal ID if its total lenght is less than 10 digits with this statement that basically adds zeroes from left side if DEC ID is smaller than 10 digits:
String strFinal=String.format("%010d", Long.parseLong(str));
This document that describes how the ID is converted from HEX8 TO DEC10 helped me alot aswell: https://www.batag.com/download/rfidreader/LF/RAD-A200-R00-125kHz.8H10D.EM.V1.1.pdf
And a huge thanks to #Andrew and #Karam for helping me resolve this!
The card reader on the PC is configured wrong, it is configured by default to display the ID as 10 digit decimal number (4 byte) when the card has a 7 byte ID.
It thus has to loose some data, it is doing this by truncating the ID to the first 4 bytes of the 7 byte ID
Use the software on the PC change the output format to something suitable for the ID size on the Mifare Ultralight C cards (8 Hex?)
or
Use Mifare Classic cards instead as these had 4 byte ID
or
truncate the 7 byte ID to 4 bytes e.g. change bytes.length to 4 (a hard coding to the first 4 bytes in the 7 byte ID) in your code and handle the fact that there is a very large number (around 16.7 million) of Mifare Ultralight C cards that will seem to have the same "ID" as you want to display it
This is because the spec's give by a seller on Amazon https://www.amazon.co.uk/Chafon-CF-RS103-Multiple-Support-Compatible-Black/dp/B017VXVZ66 (I cannot find any details on the manufacturer's site)
It says "Default output 10 digit Dec, control output format through software. "
"Support with windows,linux and android system, but can only set output format in windows pcs.No programming and software required, just plug and play. "
The only sensible answer is move everything to use a 7 byte ID.
I don't know why are you trying always to convert to decimal?
and please try to explain more about the code you use to read the UID.
about your numbers and to convert 17 digits to 10 digits; I convert both of them to Hex:
36139312876727556(17digit) in Hex : 8064837A71AD04.
2054270212(10 digit) in Hex: 7A71AD04
as you notice you can just tirm first three bytes to get the 10 digits.
and I do belive the both of them are not the UID. but the 7bytes as sayed Andrew, and you already read it in the your photo : (04:B5:71:7A:83:64:80)
So I think the answer is that because you are converting a 7 byte ID to decimal you are getting variable lengths of numbers because of the conversion to decimal.
"The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)."
From https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Could generate a decimal number with 1,2 or 3 characters thus as decimal the id can vary in length.
It also looks like that conversion is going wrong as in theory it should have negative numbers in there as well.
It is much better to handle it as a hex string if you want it to be human readable.
The correct method in Java to convert the 2 pages of the ID to hex is
StringBuilder Uid;
for (int i = 0; i < result.length; i++) {
// byte 4 is a check byte
if (i == 3) continue;
Uid.append(String.format("%02X ", result[i]));
}
Note as per the spec sheet of the card https://www.nxp.com/docs/en/data-sheet/MF0ICU2_SDS.pdf (Section 7.3.1)
There is check byte that is part of the ID, while this will always be the same on the same card and will still give you a unique ID it is technically not part of the ID.
Or if not reading at a low level then
https://developer.android.com/reference/android/nfc/Tag#getId()
will get you the id.
Note that the "36139312876727556(17digit) and reversed id" when converted to hex and reversed actual is 7 bytes and start with the right number.
The 10 digit just looks like the first 4 bytes of the 7 byte number also reversed.

Splitting a byte[] into multiple byte[] arrays

I am trying to "chunk" up the bytes of an image. This will allow me to upload a large image in bytes array. I have the image currently stored as one large byte[]. I would like to split the byte array into byte[]'s with a each exactly of 5 MB.
public static byte[][] divideArray(byte[] source, int chunksize) {
byte[][] ret = new byte[(int) Math.ceil(source.length / (double) chunksize)][chunksize];
int start = 0;
int parts = 0;
for (int i = 0; i < ret.length; i++) {
if (start + chunksize > source.length) {
System.arraycopy(source, start, ret[i], 0, source.length - start);
} else {
System.arraycopy(source, start, ret[i], 0, chunksize);
}
start += chunksize;
parts++;
}
Log.d("Parts", parts + "");
return ret;
}
Call It by
divideArray(common.fullyReadFileToBytes(wallpaperDirectory), 5 * 1024 * 1024)
You can use copyOfRange for that:
T[] copyOfRange (T[] original,
int from,
int to);
In your case, something like this:
Byte[] copyOfRange (original,
0,
5000000);
make sure you calculate the offset:
class test {
// this is just for dummy data
public static byte[] getTestBytes() {
byte[] largeByteArray = new byte[50_000_000];
for(int i = 0; i < 50_000_000; i ++) {
largeByteArray[i] = 0;
}
return largeByteArray;
}
// this method splits your byte array into small portions
// and returns a list with those portions
public static List<byte[]> byteToPortions(byte[] largeByteArray) {
// create a list to keep the portions
List<byte[]> byteArrayPortions = new ArrayList<>();
// 5mb is about 5.000.000 bytes
int sizePerPortion = 5_000_000;
int offset = 0;
// split the array
while(offset < largeByteArray.length) {
// into 5 mb portions
byte[] portion = Arrays.copyOfRange(largeByteArray, offset, offset + sizePerPortion);
// update the offset to increment the copied area
offset += sizePerPortion;
// add the byte array portions to the list
byteArrayPortions.add(portion);
}
// return portions
return byteArrayPortions;
}
// create your byte array, and split it to portions
public static void main(String[] args) {
byte[] largeByteArray = getTestBytes();
List<byte[]> portions = byteToPortions(largeByteArray);
// work with your portions
}
}
Something cool: the value to does not have to be an index inside the array, it checks that for you without erroring and copies a subset that is valid to the intended array.
These answers work fine but has optimization issues. They allocate extra space of the whole chunk size irrespective of the only actual bytes of memory the array needs to allocate for copying the data.
Here is the solution for this problem.
private fun divideDataIntoChunks(source: ByteArray, chunkSize: Int): kotlin.collections.ArrayList<ByteArray> {
val result: ArrayList<ByteArray> = ArrayList()
if (chunkSize <= 0) {
result.add(source)
} else {
for (chunk in source.indices step chunkSize) {
result.add(source.copyOfRange(chunk, min(chunk+chunkSize,source.size)))
}
}
return result
}

Arduino send long string to Android

I'm trying to send long String to Android via bluetooth.
but,
It looks like the picture.
some characters are changed.
how can I get an exact full string?
arduino code :
for(int i=0;i<16;i++){
String rec = String(P[i], HEX);
if(rec.length()<2) rec = "0"+rec;
BTSerial.println(rec);
delay(50);
P is a byte array. Thanks.
Try it without String objects:
// return '0' .. 'F'
char hexnibble(byte nibble) {
nibble &= 0x0F; // just to be sure
if (nibble > 9) return 'A' + nibble - 10;
else return '0' + nibble;
}
void loop() {
byte P[16];
// ... fill P somehow ...
char rec[33];
for(int i=0;i<16;i++){
rec[2*i] = hexnibble(P[i] >> 4);
rec[2*i+1] = hexnibble(P[i] & 0x0F);
}
rec[32] = 0; // string terminator
Serial.println(rec); // just for debugging
delay(1000);
}

Need help generating a unique request code for alarm

My app structure is like, there are 1000 masjids/mosques and each masjid has been given a unique id like 1,2,3,4 ..... 1000 . Now each mosque has seven alarms associated with it , I wish to generate a unique request code number for each alarm so that they don't overlap each other,
Following is the code:
//note integer NamazType has range 0 to 5
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return (MasjidID *(10)) + (namazType);
}
Will this code work?
you can simply concatenate masjidID and namaztype( or specifically namaz ID). This will always return unique.
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return Integer.ParseInt(String.valueOf(MasjidID)+""+NamazType)
}
Use Random class:
Try out like this:
//note integer NamazType has range 0 to 5
public int generateRequestCodeForAlarm(int MasjidID, int NamazType)
{
return (MasjidID * (Math.abs(new Random().nextInt()))) + (namazType);
}
It will work for sure.
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return (MasjidID*(10)) + (NamazType );
}
Output:
Have a look at this
If MasjidID and NamazType are unique, then
Integer.parseInt( MasjidID + "" + NamazType );
would be enough to do the trick!
Example:
Masjid ID = 96, Namaz type = 1, Unique no = 961
MasjidId = 960, Namaz type = 1, Unique no = 9601
MasjidID = 999, Namaz type = 6, Unique no = 9996
I don't find any way in which it would get repeated. However, it is very similar to
(MasjidID * 10) + NamazType
Irrespective of MasjidID and NamazType, if a random number needs to be generated, this can be used.
public class NoRepeatRandom {
private int[] number = null;
private int N = -1;
private int size = 0;
public NoRepeatRandom(int minVal, int maxVal)
{
N = (maxVal - minVal) + 1;
number = new int[N];
int n = minVal;
for(int i = 0; i < N; i++)
number[i] = n++;
size = N;
}
public void Reset() { size = N; }
// Returns -1 if none left
public int GetRandom()
{
if(size <= 0) return -1;
int index = (int) (size * Math.random());
int randNum = number[index];
// Swap current value with current last, so we don't actually
// have to remove anything, and our list still contains everything
// if we want to reset
number[index] = number[size-1];
number[--size] = randNum;
return randNum;
}
}

Array access producing unwanted result

I am getting an unusual result when attempting to place a value in an array.
I have an array table[] of a simple class result{ int score, long time, string ID}
Intention is to have a sort of leader board.
My code happily finds the correct place to insert a new score if it is in the top 10.
int ix = 0;
int jx = 10; //
while ( ix < jx )
{
if (points > sTable[ix].points)
{
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
}
ix++;
}
Problem is that when I try to insert the score using sTable[ix].score = score;
The value gets written to sTable[ix].score and also sTable[ix +1].score.
It is repeatable, it occurs at any value of ix, I have single stepped through the code and as far as I can tell the command only executes once.
Has anyone seen this before?
That because you copied the object reference to the next element in the array. You should copy the values, or create a new object:
Option A:
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx].time = sTable[jx -1].time;
sTable[jx].score = sTable[jx -1].score;
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
Option B:
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
sTable[ix] = new Result(score, time, ""); // Or however you construct the object

Categories

Resources