I try to write a program to read all the sector of NCF tag.So when I run the test :
the tag is detected
I get the tag Id
I get the number of sector
But i can only read the first sector !
Here my code :
public class MainActivity extends Activity {
public String TAG_LOCAL = "Home - ";
public boolean MODE_DEBUG_LOCAL = true;
NfcAdapter nfcAdapter;
PendingIntent pendingIntent;
IntentFilter[] intentFilter;
String[][] generalTechLists;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.w("ISI", "Main Start");
//detect if NFC device
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) {
Log.w("ISI", "NFC detected");
}else{
Log.w("ISI", "NFC NOT detected");
}
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
Log.w("ISI", " error ndef = " + e.getMessage());
}
intentFilter = new IntentFilter[] {ndef};
generalTechLists = new String[][] { new String[] { MifareClassic.class.getName() } };
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0,new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
resolveIntent(intent);
}
void resolveIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
//Identifiant du tag NFC
byte[] byte_id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
Log.w("ISI", "Tag id = " + ByteArrayToHexString(byte_id));
//techno disponible
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String[] techList = tagFromIntent.getTechList();
for (int Cpt = 0; Cpt <techList.length; Cpt++){
Log.w("ISI", "Techno = " + techList[Cpt]);
}
//QUESTION A POSER DANS XDA!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
MifareClassic mfc = MifareClassic.get(tagFromIntent);
try{
mfc.connect();
int size = mfc.getSize();
Log.w("ISI", "size (byte) = " + size);
int nbrSector = mfc.getSectorCount();
Log.w("ISI", "NbrSector = " + nbrSector);
for (int Cpt = 0; Cpt < nbrSector; Cpt++){
boolean auth = mfc.authenticateSectorWithKeyA(Cpt, MifareClassic.KEY_DEFAULT);
if (auth){
int nbrBlock = mfc.getBlockCountInSector(Cpt);
Log.w("ISI", "NbrBlock = " + nbrBlock + " for sector " + Cpt);
for (int k = 0; k < nbrBlock; k++){
byte[] data = mfc.readBlock(k);
Log.w("ISI", "Block num " + k + " - data " + ByteArrayToHexString(data));
}
}else{
Log.w("ISI", " Impossible to connect at sector " + Cpt);
}
}
}catch(IOException e){
Log.w("ISI", " error = " + e.getMessage());
}
}// End of method
}
#Override
protected void onResume() {
super.onResume();
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilter, generalTechLists);
}
private String getHexString(String hex){
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
return output.toString();
}
String ByteArrayToHexString(byte[] inarray) {
//Thanks Adam Laurie sur XDA
int i, j, in;
String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String out= "";
for(j = 0 ; j < inarray.length ; ++j) {
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
out += hex[i];
i = in & 0x0f;
out += hex[i];
}
return out;
}
}
And here the log :
Tag id = C44F0EDD
Techno = android.nfc.tech.MifareClassic
Techno = android.nfc.tech.NfcA
Techno = android.nfc.tech.NdefFormatable
size (byte) = 1024
NbrSector = 16
NbrBlock = 4 for sector 0
Block num 0 - data C44F0EDD58880400C185149849803612
Block num 1 - data 00000000000000000000000000000000
Block num 2 - data 00000000000000000000000000000000
Block num 3 - data 000000000000FF078069FFFFFFFFFFFF
NbrBlock = 4 for sector 1
error = Tag was lost.
So I don't understand what happens.
Thank for help
Try to change:
for (int k = 0; k < nbrBlock; k++){
byte[] data = mfc.readBlock(k);
Log.w("ISI", "Block num " + k + " - data " + ByteArrayToHexString(data));
}
with this
byte[] data = mfc.readBlock(bIndex);
for (int k = 0; k < nbrBlock; k++){
bIndex = mfc.sectorToBlock(Cpt);
bIndex++;
Log.w("ISI", "Block num " + k + " - data " + ByteArrayToHexString(data));
}
from: http://mifareclassicdetectiononandroid.blogspot.it/
Set your code like this:
int bIndex = 0;
try{
mfc.connect();
int size = mfc.getSize();
Log.i("ISI", "size (byte) = " + size);
int sectorCount = mfc.getSectorCount();
Log.i("ISI", "NbrSector = " + sectorCount);
for (int Cpt = 0; Cpt < sectorCount; Cpt++){
boolean auth = mfc.authenticateSectorWithKeyA(Cpt, MifareClassic.KEY_DEFAULT);
if (auth){
int nbrBlock = mfc.getBlockCountInSector(Cpt);
Log.i("ISI", "NbrBlock = " + nbrBlock + " for sector " + Cpt);
for (int k = 0; k < nbrBlock; k++){
byte[] data = mfc.readBlock(bIndex);
Log.i("ISI", "Block num " + k + " - data " + ByteArrayToHexString(data));
bIndex++;
}
}else{
Log.i("ISI", " Impossible to connect at sector " + Cpt);
}
}
}catch(IOException e){
Log.i("ISI", " error = " + e.getMessage());
}
Related
When I transfer the bytes greater than 16384 bytes when the data will be lost,
I have tried libusb, but libusb I did not find the right development documentation for reference, I wonder if there is no better way to solve this problem?
Here is the code that I print through the bulktransfer, when the transmitted data is less than 16384, it is working!
//convert pic to ZPL
public class ZPLConveter {
private int blackLimit = 380;
private int total = -1;
private int widthBytes = -1;
private boolean compressHex = false;
private static Map<Integer, String> mapCode = new HashMap<Integer, String>();
{
mapCode.put(1, "G");
mapCode.put(2, "H");
mapCode.put(3, "I");
mapCode.put(4, "J");
mapCode.put(5, "K");
mapCode.put(6, "L");
mapCode.put(7, "M");
mapCode.put(8, "N");
mapCode.put(9, "O");
mapCode.put(10, "P");
mapCode.put(11, "Q");
mapCode.put(12, "R");
mapCode.put(13, "S");
mapCode.put(14, "T");
mapCode.put(15, "U");
mapCode.put(16, "V");
mapCode.put(17, "W");
mapCode.put(18, "X");
mapCode.put(19, "Y");
mapCode.put(20, "g");
mapCode.put(40, "h");
mapCode.put(60, "i");
mapCode.put(80, "j");
mapCode.put(100, "k");
mapCode.put(120, "l");
mapCode.put(140, "m");
mapCode.put(160, "n");
mapCode.put(180, "o");
mapCode.put(200, "p");
mapCode.put(220, "q");
mapCode.put(240, "r");
mapCode.put(260, "s");
mapCode.put(280, "t");
mapCode.put(300, "u");
mapCode.put(320, "v");
mapCode.put(340, "w");
mapCode.put(360, "x");
mapCode.put(380, "y");
mapCode.put(400, "z");
}
public String convertFromImg(Bitmap bitmap) {
String cuerpo = createBody(bitmap);
if(compressHex) {
cuerpo = encodeHexAscii(cuerpo);
}
return headDoc() + cuerpo + footDoc();
}
private String createBody(Bitmap originalImg) {
StringBuffer sb = new StringBuffer();
int width = originalImg.getWidth();
int height = originalImg.getHeight();
int rgb,red,green,blue,index = 0;
char binaryChar[] = {'0','0','0','0','0','0','0','0',};
widthBytes = width / 8;
if(width % 8 > 0) {
widthBytes = (((int)width / 8) + 1);
}else {
widthBytes = width / 8;
}
total = widthBytes * height;
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
rgb = originalImg.getPixel(w,h);
red = Color.red(rgb);
green =Color.green(rgb);
blue = Color.blue(rgb);
char auxChar = '1';
int totalColor = red + green + blue;
if(totalColor > blackLimit) {
auxChar = '0';
}
binaryChar[index] = auxChar;
index++;
if(index == 8 || w == (width - 1)) {
sb.append(fourByteBinary(new String(binaryChar)));
binaryChar = new char[]{'0','0','0','0','0','0','0','0'};
index = 0;
}
}
sb.append("\n");
}
return sb.toString();
}
private String fourByteBinary(String binary){
int decimal = Integer.parseInt(binary,2);
if(decimal > 15) {
return Integer.toString(decimal,16).toUpperCase();
}else {
return "0" + Integer.toString(decimal,16).toUpperCase();
}
}
private String encodeHexAscii(String code) {
int maxLine = widthBytes * 2;
StringBuffer sbCode = new StringBuffer();
StringBuffer sbLine = new StringBuffer();
String perviousLine = "";
int counter = 1;
char aux = code.charAt(0);
boolean firstChar = false;
for (int i = 0; i < code.length(); i++) {
if(firstChar) {
aux = code.charAt(i);
firstChar = false;
continue;
}
if(code.charAt(i) == '\n') {
if(counter >= maxLine && aux == '0') {
sbLine.append(",");
}else if(counter >= maxLine && aux == 'F'){
sbLine.append("!");
}else if (counter>20){
int multi20 = (counter/20)*20;
int resto20 = (counter%20);
sbLine.append(mapCode.get(multi20));
if(resto20!=0){
sbLine.append(mapCode.get(resto20) + aux);
} else {
sbLine.append(aux);
}
} else {
sbLine.append(mapCode.get(counter) + aux);
if(mapCode.get(counter)==null){
}
}
counter = 1;
firstChar = true;
if(sbLine.toString().equals(perviousLine)){
sbCode.append(":");
} else {
sbCode.append(sbLine.toString());
}
perviousLine = sbLine.toString();
sbLine.setLength(0);
}
if(aux == code.charAt(i)) {
counter++;
}else {
if(counter > 20) {
int multi20 = (counter/20)*20;
int resto20 = (counter%20);
sbLine.append(mapCode.get(multi20));
if(resto20!=0){
sbLine.append(mapCode.get(resto20) + aux);
} else {
sbLine.append(aux);
}
}else {
sbLine.append(mapCode.get(counter) + aux);
}
counter = 1;
aux = code.charAt(i);
}
}
return sbCode.toString();
}
private String headDoc(){
String str = "^XA " +
"^FO0,0^GFA,"+ total + ","+ total + "," + widthBytes +", ";
return str;
}
private String footDoc(){
String str = "^FS"+
"^XZ";
return str;
}
public void setCompressHex(boolean compressHex) {
this.compressHex = compressHex;
}
public void setBlacknessLimitPercentage(int percentage){
blackLimit = (percentage * 768 / 100);
}
}
And this is the code that I use for transferring the image
//Transferring data using bulktransfer
private void printTask(final UsbDeviceConnection conn) {
try {
convertPDFToImg();
ZPLConveter zp = new ZPLConveter();
zp.setCompressHex(false);
zp.setBlacknessLimitPercentage(50);
command = zp.convertFromImg(bit);
} catch (IOException e) {
e.printStackTrace();
}
bytes = command.getBytes(StandardCharsets.US_ASCII);
conn.bulkTransfer(pointBulkOut, bytes, bytes.length, 500);
}
i am a beginner.
I get String from SQLite.
WKT = cursor.getString(cursor.getColumnIndex(polygon));
WKT = WKT.replaceAll(",", ", ");
Its look like String = (1.00 2.00, 3.00 4.00, 5.00 6.00, .....).
How to switch it to String (2.00 1.00, 4.00 3.00, 6.00 5.00, ......).
Thanks.
try this
private static void testMethod() {
String result = "(A B, C D, E F)";
String resultTmp = result;
resultTmp = resultTmp.replace("(", "");
resultTmp = resultTmp.replace(")", "");
String[] aryResult = resultTmp.split(",");
String[] finalResult = reverseString(aryResult);
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < finalResult.length; i++) {
String dfgf = strBuilder.toString().equals("") ? "" : ",";
strBuilder.append(dfgf);
strBuilder.append(finalResult[i]);
}
String newString = strBuilder.toString();
System.out.println("RESULT : " + newString);
}
public static String[] reverseString(String[] words)
{
String[] t = new String[words.length];
for (int i = 0; i < words.length; i++)
{
t[i] = "";
for (int j = words[i].length() - 1; j >= 0; j--)
t[i] += words[i].charAt(j);
}
return t;
}
Follow below steps
1)Split string with ","
2)User Reverse() function to reverse the string(AB->BA)
3)Store the result in to an array.
Repeat the step until you split the last entry from sql lite.
Try this logic,its working in c and c++.
int Groups = 1; // Count 1 for the first group of letters
for ( int Loop1 = 0; Loop1 < strlen(String); Loop1++)
if (String[Loop1] == ' ') // Any extra groups are delimited by space
Groups += 1;
int* GroupPositions = new int[Groups]; // Stores the positions
for ( int Loop2 = 0, Position = 0; Loop2 < strlen(String); Loop2++)
{
if (String[Loop2] != ' ' && (String[Loop2-1] == ' ' || Loop2-1 < 0))
{
GroupPositions[Position] = Loop2; // Store position of the first letter
Position += 1; // Increment the next position of interest
}
}
try this..
private static void testTwo() {
String result = "(1.00 2.00, 3.00 4.00, 5.00 6.00)";
String resultTmp = result;
resultTmp = resultTmp.replace("(", "");
resultTmp = resultTmp.replace(")", "");
String[] aryResult = resultTmp.split(",");
for (int i = 0; i < aryResult.length; i++) {
String str = aryResult[i].trim();
String[] sdf = str.split(" ");
aryResult[i] = reverseArray(sdf);
}
String strResult = Arrays.toString(aryResult).replace("[", "(").replace("]", ")");
System.out.println("RESULT : " + strResult);
}
public static String reverseArray(String[] words)
{
for(int i = 0; i < words.length / 2; i++)
{
String temp = words[i];
words[i] = words[words.length - i - 1];
words[words.length - i - 1] = temp;
}
return ((Arrays.toString(words)).replace("[", "")).replace("]", "").replace(",", "");
}
#. If you want to swap sub-string, just use below method:
public String swapString(String str) {
str = str.replace("(", "");
str = str.replace(")", "");
String[] array = str.split(", ");
StringBuilder result = new StringBuilder();
result.append("(");
for (int i = 0; i < array.length; i++) {
String[] temp = String.valueOf(array[i]).split(" ");
result.append(temp[1]);
result.append(" ");
result.append(temp[0]);
if (i != array.length -1)
result.append(", ");
}
result.append(")");
return result.toString();
}
USE:
String yourString = "(1.00 2.00, 3.00 4.00, 5.00 6.00)";
Log.d("ARRAY", "Before Swap: " + yourString);
yourString = swapString(yourString);
Log.d("ARRAY", "After Swap: " + yourString);
OUTPUT:
D/ARRAY: Before Swap: (1.00 2.00, 3.00 4.00, 5.00 6.00)
D/ARRAY: After Swap: (2.00 1.00, 4.00 3.00, 6.00 5.00)
#. If you want to swap char, use below method:
public String swapChar(String str) {
// Convert string to char array
char[] array = str.toCharArray();
for (int i = 1; i < array.length - 1; i+=5) {
// Swap char
char temp = array[i];
array[i] = array[i+2];
array[i+2] = temp;
}
return String.valueOf(array);
}
USE:
String yourString = "(A B, C D, E F, G H, I J)";
Log.d("ARRAY", "Before Swap: " + yourString);
yourString = swapChar(yourString);
Log.d("ARRAY", "After Swap: " + yourString);
OUTPUT:
D/ARRAY: Before Swap: (A B, C D, E F, G H, I J)
D/ARRAY: After Swap: (B A, D C, F E, H G, J I)
Hope this will help~
I'm new with android and java, so I apologize if what I say is not entirely correct.
In my application I'd like to convert an ArrayList to integer
to increase each value with a +1. Please note the commented out part to understand where is my problem. I can't find the right way..
This is what I do for now:
public String mRequest(String mUrl, String mAuth, String mParam, String customerId, ArrayList filter) {
InputStream mStreamResponse;
String mString = null;
try {
URL obj = new URL(mUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", mAuth);
con.setRequestProperty("X-Limit", String.valueOf(xLimit));
con.setRequestProperty("X-Skip", String.valueOf(xSkip));
con.setRequestProperty("X-Sort", "{\"created\":-1}");
String parameters = null;
System.out.println("Value of mParam -> " + mParam);
if (mParam != null && customerId != null) {
Log.e("ERROR", "Ricerca per parametro e customerId");
} else if (mParam != null) {
parameters = "\"number\":{\"$regex\":" + mParam + "}";
} else if (customerId != null) {
parameters = "\"customer.id\":{\"$eq\":" + "\"" + customerId + "\"" + "}";
} else {
parameters = "\"number\":{\"$regex\":\"\"}";
}
System.out.println("parameters");
System.out.println(parameters);
if (filter != null) {
//convert ArrayList to Array
Object[] mArray = filter.toArray();
String filterGroup = mArray[0].toString() + ".id";
System.out.println("Group selected -> " + filterGroup);
for (int i = 1; i < mArray.length; i++) {
System.out.println("Value -> " + mArray[i]);
}
String pFilter = null;
for (int i = 1; i < mArray.length; i++) {
/*
*
* This is where I need to change value in
* pos i with i + 1
*
*/
switch (mArray[i].toString()) {
case "0":
mArray[i] = "1";
break;
case "1":
mArray[i] = "2";
break;
case "2":
mArray[i] = "3";
break;
case "3":
mArray[i] = "4";
break;
case "4":
mArray[i] = "5";
break;
case "5":
mArray[i] = "6";
break;
case "6":
mArray[i] = "7";
break;
case "7":
mArray[i] = "8";
break;
case "8":
mArray[i] = "9";
break;
case "9":
mArray[i] = "10";
break;
case "10":
mArray[i] = "11";
break;
case "11":
mArray[i] = "12";
break;
case "12":
mArray[i] = "13";
break;
}
if (mArray.length == 2){
pFilter = mArray[i].toString();
} else {
if (mArray[i] != mArray[mArray.length - 1]) {
if (pFilter != null) {
pFilter = pFilter + mArray[i].toString() + ",";
} else {
pFilter = mArray[i].toString() + ",";
}
} else {
pFilter = pFilter + mArray[i].toString();
}
}
}
String mFilter = "[" + pFilter + "]";
System.out.println("Insert value in a string -> " + mFilter);
String tempParam = null;
if (filterGroup.equals("assignee")) {
tempParam = "{\"$eq\":" + mFilter + "}";
} else {
tempParam = "{\"$in\":" + mFilter + "}";
}
//Override the value with the same filterGroup
if (filterMap.containsKey(filterGroup)) {
String toOverride = filterGroup;
filterMap.remove(filterGroup);
filterMap.put(toOverride, tempParam);
} else {
filterMap.put(filterGroup, tempParam);
}
//iterate
for (Map.Entry<String, String> entry : filterMap.entrySet()) {
switch (entry.getKey()) {
case "status.id":
status = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "queue.id":
queues = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "type.id":
types = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "severity.id":
severities = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "assignee.id":
mytickets = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
}
}
filterMapValues = parameters ;
if (status != null) {
filterMapValues += ", " + status;
}
if (queues != null) {
filterMapValues += ", " + queues;
}
if (types != null) {
filterMapValues += ", " + types;
}
if (severities != null) {
filterMapValues += ", " + severities;
}
if (mytickets != null) {
filterMapValues += ", " + mytickets;
}
String myFilter = "{" + filterMapValues + "}";
System.out.println("myFilter -> " + myFilter);
//setup request header
con.setRequestProperty("X-Filter", myFilter);
} else {
String xFilter = "{\"status.id\":" + statusAll + ", \"queue.id\":" + queueAll + ", \"type.id\":" + typeAll + ", \"severity.id\":" + severityAll + "," + parameters + "}";
con.setRequestProperty("X-Filter", xFilter);
System.out.println("Reset all -> " + xFilter);
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + mUrl);
System.out.println("Response Code : " + responseCode);
mStreamResponse = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(mStreamResponse));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
mStreamResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mString = sb.toString();
} catch (Exception e) {
}
return mString;
}
How can I do?
Thanks in advance.
Edit
I started the for loop in pos #1 because in pos #0 I save filterGroup value, and that's a String, I need to menage as int only values in pos > 0
First off:
I'd like to convert an ArrayList to integer [...]
ArrayList<E> is a collection object with type E that can be any object or primitive. What you are really asking for is how to convert an ArrayList<String> (see that it is an ArrayList of type String) into an integer array. I can see you have already converted the ArrayList<String> into an Object[] (Object array that can hold both integers and Strings) using the following line in the example code given above:
Object[] mArray = filter.toArray();
Getting back to the original answer, this would do it:
int[] mArray = new int[filter.size()];
for (int i = 0; i < filter.size(); i++) {
int value = Integer.parseInt(filter.get(i));
mArray[i] = value++;
}
Your code is correct just change the for loop initial value to start from 0 rather than 1 like this:
int tempValue = 0;
for (int i = 0; i < mArray.length; i++) {
{
// increasing your mArray value
tempValue = (Integer) mArray[i] + 1;
mArray[i] = tempValue;
//Rest of your code
}
Can you try this please.
Remove your switch case inside for and replace it with below. Hope you want something like this.
for(int i=0; i<mArray.length(); i++){
mArray[i] = i+1;
}
let me know..
Do follwoing
Step 1: Create a method
private List<Integer> stringToIncrementedString(ArrayList<String> stringArrayList){
List<Integer> arrayInt;
arrayInt = new ArrayList<Integer>();
for(int i=1 ;i<stringArrayList.size();i++)
arrayInt.add(Integer.parseInt(stringArrayList.get(i))+1);
return arrayInt;
}
Step 2 :Call this method from where you want.It will return the Arraylist with incremented value.
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
In the above code we can send data like just "0" and "1". But want to send in 8-bits like 00000000 and 00000001. It should display in Arduino board. If press to send data 1 it should show 00000001 and 00000000.
Use this:
String str = "25789";
int i = Integer.parseInt(str);
String binarystr = Integer.toBinaryString(i);
char[] buffer = new char[binarystr.length()];
binarystr.getChars(0,binarystr.length(), buffer, 0);
System.out.println("char array:: "+Arrays.toString(buffer));
byte[] binaryFormat = getbyteFromString(buffer);
for (byte b : binaryFormat) {
System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1));
}
method:
private byte[] getbyteFromString(char[] binarystr){
int length = binarystr.length/8;
if(binarystr.length % 8 > 0)
length++;
int iterationCount = length ;
byte[] binaryFormat = new byte[iterationCount];
int iter = iterationCount - 1;
for(int i = binarystr.length - 1; i >=0 ;){
byte byt = 0x0;
for(int j = 0; j < 8 ; j++){
if(i < 0)
break;
int b = binarystr[i] - 48;
byt = (byte) (byt + (b << j));
i--;
}
binaryFormat[iter] = byt;
iter--;
}
return binaryFormat;
}
I want to do the replication between Android sqlite & MS SQL server.That Time i want to take Tables values from Databse.
This is my JSON
{
"Table1":[
{
"BusinessUnit":"MASS",
"ProductCode":"SLD0201",
"Description":"Lou Difan C.Blue 12"3- Commode",
"Description2":"301 0201"
},
{
"BusinessUnit":"MASS",
"ProductCode":"SLN0502",
"Description":"Lou Napoli I"vory- Cistern",
"Description2":"2011 0502"
},
{
"BusinessUnit":"MASS",
"ProductCode":"LDMBL6H",
"Description":"Dortek Taper Bullet Handle 6"5 serr ",
"Description2":"Taper Bullet Ha"
}
],
"Table2":[
{
"chk":6,
"currentchk":1
}
]
}
In Here JSON Description column value contain "(double quotation) .If we check http://jsonformatter.curiousconcept.com/ , it show error.Its a Invalid JSON.
WCF service I have converted DataSet to JSON. Some table column contain special charters.
I converted like this :
public String ConverTableToJson(DataSet dsDownloadJson,int currentSplit)
{
StringBuilder Sb = new StringBuilder();
String result = "";
int start = 0;
int end =500;
int chk = 0;
int currentChk = currentSplit;
if (dsDownloadJson.Tables.Count > 0)
{
Sb.Append("{");
foreach (DataTable dt in dsDownloadJson.Tables)
{
DataTable dtDownloadJson = dt;
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
double total = dtDownloadJson.Rows.Count;
Console.WriteLine("--1--" + dtDownloadJson.Rows.Count);
if (dtDownloadJson.Rows.Count < 500)
{
end = dtDownloadJson.Rows.Count;
}
if (chk == 0)
{
if (dtDownloadJson.Rows.Count > 500)
{
if ((dtDownloadJson.Rows.Count / 500) == 0)
{
chk = dtDownloadJson.Rows.Count / 500;
}
else
{
chk = dtDownloadJson.Rows.Count / 500 + 1;
}
}
else
{
chk = 1;
}
currentChk = 1;
}
else
{
currentChk = currentChk + 1;
start = currentChk * 500;
end = start + 500;
currentChk = chk;
}
Sb.Append("\"" + dtDownloadJson.TableName + "1\" : [");
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
Console.WriteLine("--2--" + start);
Console.WriteLine("--3--" + end);
for (int i = start; i < end; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
TempStr = TempStr.Replace(""", '\"');
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
}
}
else
{
}
Sb.Append("],");
if (chk > 1)
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
else
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
}
// Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("}");
return Sb.ToString();
}
else
{
return "0";
}
}
My problem is removing special charters OR How to allow special characters.?
Please help me anybody...
You shouldn't use a StringBuilder to convert an object to a JSON string. Use the JsonConverter class in JayRock JSON library and it takes care of Serialising/Deserialising Json for you (including escaping)
try to use inbuilt json serialization
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}