Regex for android calculator - android

I am writing a regex for an android calculator. The "+/-*" are okay for non decimal values but the problem lies in the ".". How do i check for the "." ?
Here is my regex :
"(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"
This is my method for calculations:
private double calc(String resultString) {
String[] result = resultString.split("(?<=[^\\\\d.])(?=\\\\d)|(?<=\\\\d)(?=[^\\\\d.])");
String op = null;
double res = 0;
for (String s : result) {
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") ) {
op = s;
}
else if(s.equals(".")){
}
else {
if (op == null) {
res = Double.parseDouble(s);
} else {
if (op.equals("+")) {
res = res + Double.parseDouble(s);
} else if (op.equals("-")) {
res = res - Double.parseDouble(s);
} else if (op.equals("*")) {
res *= Double.parseDouble(s);
} else if (op.equals("/")) {
res /= Double.parseDouble(s);
}
}
}
}
return res;
}

Exclude the . from the \D shorthand with a negated character class [^\d.] that will match any char but a digit and a literal . (note the . does not have to be escaped in the character class to be parsed as a literal dot):
"(?<=[^\\d.])(?=\\d)|(?<=\\d)(?=[^\\d.])"
See the regex demo
And an online demo (in Java):
String resultString = "1-1+0.4/2+0.5*4";
String[] result = resultString.split("(?<=[^\\d.])(?=\\d)|(?<=\\d)(?=[^\\d.])");
String op = null;
double res = 0;
for (String s : result) {
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") ) {
op = s;
}
else {
if (op == null) {
res = Double.parseDouble(s);
} else {
if (op.equals("+")) {
res = res + Double.parseDouble(s);
} else if (op.equals("-")) {
res = res - Double.parseDouble(s);
} else if (op.equals("*")) {
res *= Double.parseDouble(s);
} else if (op.equals("/")) {
res /= Double.parseDouble(s);
}
}
}
}
System.out.println(res); // => 2.8 (= 1-1+0.4/2+0.5*4)

Related

Remove Unknown tags (C3, BF40, C2) from TLV using TLVUtility on terminalSdk-2.0.3.jar

I am trying to remove some Unknown tags (C3, BF40, C2,.. etc) from ByteArray using TLVUtility (mastercard class from terminalSdk-2.0.3.jar), Tags was not removing from the ByteArray. I am trying like this,
Here is my TLV Data I have,
ppseResponse = ByteUtility.hexStringToByteArray("6F54840E325041592E5359532E4444463031C30F4920414D2054484520424553542033BF4003C20101A52BBF0C28610C4F07A0000000041010870101610C4F07A0000000043060870103610A4F05B0123456788701099000")
I am trying this to remove the Unknown tags like,
"BEFORE << ${ByteUtility.byteArrayToHexString(ppseResponse)}".toLog(activity, TAG) //To print Log
val unknownTags = byteArrayOf((0x00C3).toByte(),(0xBF40).toByte(), (0x00C2).toByte())
var removed = TLVUtility.removeTag(ppseResponse, ContentType.TLV,unknownTags)
"AFTER << ${ByteUtility.byteArrayToHexString(removed)}".toLog(activity, TAG) //To print Log
Here is the function removeTag on terminalSdk-2.0.3.jar function look likes,
public static byte[] removeTag(byte[] var0, ContentType var1, byte[] var2) {
int var10000;
Throwable var10001;
String var28;
label698: {
var10000 = 2 % 2;
if (var0 != null) {
label691: {
var10000 = g + 85;
f = var10000 % 128;
if (var10000 % 2 == 0) {
byte[] var26 = var2;
byte var27;
label676: {
label675: {
try {
null.hashCode();
if (var26 == null) {
break label675;
}
} catch (Throwable var25) {
throw var25;
}
var27 = 42;
break label676;
}
var27 = 74;
}
switch(var27) {
case 42:
break;
case 74:
default:
break label691;
}
} else if (var2 == null) {
break label691;
}
var10000 = f + 55;
g = var10000 % 128;
switch(var10000 % 2 != 0 ? 0 : 1) {
case 0:
default:
if (var2.length >= 1) {
break label698;
}
break;
case 1:
if (var2.length >= 1) {
break label698;
}
}
}
}
var28 = e(31, '卆', 490).intern();
try {
((Class)q.b(38, 8595, '\ue0f7')).getMethod("e", String.class).invoke((Object)null, var28);
} catch (Throwable var22) {
var10001 = var22.getCause();
if (var10001 != null) {
throw var10001;
}
throw var22;
}
throw new LibraryUncheckedException(ExceptionCode.X6F44);
}
label700: {
if (var1 == ContentType.T) {
var10000 = g + 15;
f = var10000 % 128;
if (var10000 % 2 == 0) {
if (var0.length < 0) {
break label700;
}
} else if (var0.length < 1) {
break label700;
}
}
switch(var1 != ContentType.TLV ? 81 : 64) {
case 81:
if (var1 != ContentType.TDO) {
break;
}
case 64:
default:
if (var0.length < 3) {
var28 = e(47, '\u0000', 560).intern();
try {
((Class)q.b(38, 8595, '\ue0f7')).getMethod("e", String.class).invoke((Object)null, var28);
} catch (Throwable var23) {
var10001 = var23.getCause();
if (var10001 != null) {
throw var10001;
}
throw var23;
}
throw new LibraryUncheckedException(ExceptionCode.X6F43);
}
}
ArrayList var3 = conditionalTlvParsing(var0, var1, e(1, '\u0000', 140).intern(), true);
Iterator var4 = var3.iterator();
while(var4.hasNext()) {
BerTlv var5 = (BerTlv)var4.next();
switch(var5.getTagObject().getNTag() == ByteUtility.byteArrayToInt(var2) ? 39 : 84) {
case 39:
default:
var4.remove();
case 84:
}
}
return formByteArrayFromTlvList(var3, var1);
}
var28 = e(39, '\u0000', 521).intern();
try {
((Class)q.b(38, 8595, '\ue0f7')).getMethod("e", String.class).invoke((Object)null, var28);
} catch (Throwable var24) {
var10001 = var24.getCause();
if (var10001 != null) {
throw var10001;
}
throw var24;
}
throw new LibraryUncheckedException(ExceptionCode.X6F43);
}
I fixed this issue by creating new custom function. Here is the function. Now on this function I am removing all the Unknown Tags and its Skipping all Known Tags and Third party data and Optional Tags Tags
First we need to define optional Tag,
private var optionalTags: ArrayList<ByteArray> = getOptionalTags()
Here is the function I am adding Optional Tags,
private fun getOptionalTags(): ArrayList<ByteArray> {
optionalTags = ArrayList()
optionalTags.add(ByteUtility.hexStringToByteArray("9F3E")) //Terminal Categories Supported List
optionalTags.add(ByteUtility.hexStringToByteArray("9F3F")) //Selection Data Object List
optionalTags.add(ByteUtility.hexStringToByteArray("9F2A")) //Kernel Identifier
optionalTags.add(ByteUtility.hexStringToByteArray("9F0A")) //Application Selection Registered Proprietary Data
return optionalTags
}
Here is the function to remove the Unknown tags,
private fun removeUnknownTags(ppseResponse: ByteArray): ByteArray {
var parentTags: MutableMap<ByteArray, Int> = LinkedHashMap()
var ppseResp = ppseResponse;
var i = 0
"PPSE (Length: ${ppseResp.size}) : HexString: ${ByteUtility.byteArrayToHexString(ppseResp)} \n ByteArray: ${ppseResp.toList()}".toLog()
while (i < ppseResp.size - 1) {
var removeTag = false;
var currentTag = TLVUtility.getCurrentTag(ppseResp, i);
var nextIndex = i + currentTag.size;
var tLVLengthInfo = TLVUtility.getTLVLengthInfo(ppseResp, nextIndex);
val tagLength = tLVLengthInfo.expectedNumberOfBytes
var tagValueSize = tLVLengthInfo.lengthBytes.size
var tagValue = ByteUtility.getSubByteArray(ppseResp, nextIndex + tagValueSize, tagLength)
"<==- ${i} : ${ByteUtility.byteArrayToHexString(currentTag)} (${TLVUtility.getReferenceTagDetails(currentTag).name}) , Length:${tagLength} (${tLVLengthInfo.lengthBytes.toList()} : ${ByteUtility.byteArrayToHexString(tLVLengthInfo.lengthBytes)}) , Max:${TLVUtility.getReferenceTagDetails(currentTag).maxLen} , Min:${TLVUtility.getReferenceTagDetails(currentTag).minLen} -==>".toLog()
"Value : ${ByteUtility.byteArrayToHexString(tagValue)} , Bytes:${tagValue.toList()}".toLog()
var tagNameLengthValue = ByteUtility.getSubByteArray(ppseResp, i, currentTag.size + tagValueSize + tagLength)
if (TLVUtility.getReferenceTagDetails(currentTag).name.contentEquals("Unknown Tag")) {
var optionalTag = false;
for (optTag in optionalTags) {
if (currentTag.contentEquals(optTag)) {
"${ByteUtility.byteArrayToHexString(currentTag)} is Optional Tag".toLog()
i = nextIndex + tagValueSize + tagLength;
optionalTag = true;
break
}
}
if (!optionalTag)
removeTag = true
} else if (TLVUtility.getReferenceTagDetails(currentTag).name.contentEquals("Third Party Data")) {
i = nextIndex + tagValueSize + tagLength;
} else {
if (!removeTag) {
if (TLVUtility.isTLVEncoded(tagValue)) {
parentTags.put(currentTag, i)
parentTags.entries.stream()
.sorted(Map.Entry.comparingByValue<ByteArray, Int>().reversed())
.forEachOrdered { x -> parentTags.put(x.key, x.value) }
if (tagValue.contentEquals(ByteUtility.hexStringToByteArray("00"))) {
i = nextIndex + tagValueSize + tagLength;
} else
i = nextIndex + tagValueSize
} else {
i = nextIndex + tagValueSize + tagLength;
}
}
}
if (removeTag) {
"-*-*-*-Removing TAG ${ByteUtility.byteArrayToHexString(currentTag)}-*-*-*-".toLog()
ppseResp = ByteUtility.getSubByteArray(ppseResp, 0, i) + ByteUtility.getSubByteArray(ppseResp, i + tagNameLengthValue.size)
var byteDiff = tagNameLengthValue.size
"--Updating Tag Length (Removed Bytes ${byteDiff})--".toLog()
for (tag in parentTags.entries.reversed()) {
var parentBytes = tag.key
var index = tag.value
var sizeIndex = index + parentBytes.size
var unknownTLVLengthInfo = TLVUtility.getTLVLengthInfo(ppseResp, sizeIndex);
val length = unknownTLVLengthInfo.expectedNumberOfBytes
if (i > index && i <= index + length) { //To Check is Parent Tag
"Parent Tag ${ByteUtility.byteArrayToHexString(tag.key)} (Bytes:${tag.key.toList()}) , Position:${tag.value}".toLog()
var lengthByteArray = unknownTLVLengthInfo.lengthBytes
var newLengthByteArray = ByteUtility.intToBerEncodedLength(length - byteDiff).bytes
var lengthDiff = lengthByteArray.size - newLengthByteArray.size;
byteDiff = byteDiff + lengthDiff
ppseResp = ByteUtility.getSubByteArray(ppseResp, 0, sizeIndex) + newLengthByteArray + ByteUtility.getSubByteArray(ppseResp, sizeIndex + lengthByteArray.size)
if (lengthDiff > 0) {
i = i - lengthDiff
for (child in parentTags.entries) {
if (child.value > tag.value) {
parentTags.replace(child.key, child.value - lengthDiff)
}
}
}
// "PPSE After (Length: ${ppseResp.size}): ${ByteUtility.byteArrayToHexString(ppseResp)} \n ByteArray: ${ppseResp.toList()}".toLog()
}
}
}
}
return ppseResp;
}

How do I sort a List<Type> by List<String> in flutter

I want to sort attribute attrlist list by their _weigth value and weight will be like weight='1',weight='2'....
class Attribute{
String _attributerowid;
String _grouprowid;
String _attributename;
String _weight;
}
List<Attribute> get attrlist => _attrlist;
I tried this code and it is working as you like
class Attribute{
String _attributerowid;
String _grouprowid;
String _attributename;
String _weight;
Attribute(this._attributerowid,this._grouprowid,this._attributename,this._weight);
static List<Attribute> sort(List<Attribute> attributes){
attributes.sort((a, b) => _compareAttributes(a, b));
}
static int _compareAttributes(Attribute a, Attribute b) {
if (a._weight != null && b._weight != null) {
int aWeight = int.tryParse(a._weight);
int bWeight = int.tryParse(b._weight);
if (aWeight >= bWeight) {
return 1;
} else {
return -1;
}
} else if (a._weight != null && b._weight == null) {
return 1;
} else if (a._weight == null && b._weight != null) {
return -1;
} else {
return -1;
}
}
}
void main(){
Attribute a = Attribute('test','me','case','2');
Attribute b = Attribute('test','me','case','1');
Attribute c = Attribute('test','me','case','4');
Attribute d = Attribute('test','me','case','3');
List<Attribute> list= <Attribute>[a,b,c,d];
Attribute.sort(list);
}
This should be fine
_attrlist.sort((a, b) => {
aWeight = int.tryParse(a._weight) ?? 0
bWeight = int.tryParse(b._weight) ?? 0
return aWeight.compareTo(bWeight);
})

Unexpected 0 as a result of mean calculation

As a part of my thread I want to calculate the mean value of 30 readings. To calculate it I am using formula
This is the code of run() method of my thread (the variables are defined before in thread - I've just put them to see the types of variables used):
//Thread's variables
float[] values;
String[] str1;
String[] str2;
int counter = 0;
int calibrationCounter = 0;
StringBuilder strBuilder;
ReadingsUpdateData updater;
String msg;
float[] calibrationValues;
public void run() {
while (true) {
try{
msg = inputList.poll();
} catch(NoSuchElementException nse){
continue;
}
if (msg == null) {
continue;
}
String[] msgArray = msg.split("!");
for (String m : msgArray) {
if (m.length() == 0) {
continue;
}
if(m.charAt(0)!='A'){
strBuilder.append(m);
continue;
} else {
str1 = strBuilder.toString().split(":");
if (str1.length != 2) {
if(str1.length>2){
strBuilder.delete(0,strBuilder.length());
continue;
}
strBuilder.append(m);
continue;
}
if (!str1[0].equals("ANG")) {
strBuilder.delete(0,strBuilder.length());
continue;
}
str2 = str1[1].split(",");
if (str2.length != 3) {
if(str2.length >3){
strBuilder.delete(0,strBuilder.length());
strBuilder.append(m);
continue;
}
strBuilder.append(m);
continue;
}
try {
if(readingsCalibration) {
if(calibrationCounter<30) {
Log.d(LOG_TAG,calibrationValues[0] + " = (1/(" +calibrationCounter +"+1))*("+calibrationValues[0] + "*"+calibrationCounter +"+"+str2[0]+"))");
calibrationValues[0] = (1/(calibrationCounter + 1))*
(calibrationValues[0]*calibrationCounter+Float.parseFloat(str2[0]));
calibrationValues[1] = (1/(calibrationCounter + 1))*
(calibrationValues[1]*calibrationCounter+Float.parseFloat(str2[1]));
calibrationValues[2] = (1/(calibrationCounter + 1))*
(calibrationValues[2]*calibrationCounter+Float.parseFloat(str2[2]));
calibrationCounter++;
} else {
readingsCalibration = false;
calibrationCounter = 0;
}
} else {
values[0] = Float.parseFloat(str2[0]) - calibrationValues[0];//x
values[1] = Float.parseFloat(str2[1]) - calibrationValues[1];//y
values[2] = Float.parseFloat(str2[2]) - calibrationValues[2];//z
updater.setData(values);
EventBus.getDefault().post(updater);
}
} catch (NullPointerException npe) {
} catch (NumberFormatException nfe) {
}
strBuilder.delete(0,strBuilder.length());
strBuilder.append(m);
}
}
}
}
Unfortunately, I am getting all the time only zeros as a result. Only at a first run I get some value but next one and each after gives 0. I was thinking about some problem with type casting but then I wouldn't get also first value.
Since you're dividing two ints, you're performing integer division, i.e., keeping only the whole part of the result.
to get a floating point result, it would suffice to define one of the operands as a double. e.g.:
double calibrationCounter = 0.0;

Android: Loading large txt file(120k lines) from raw folder has delay the first time

I am using an AsyncTask to parse a very large txt file in my application and i noticed something weird: The first time this AsyncTask is called it takes very long time to finish(10-20 seconds) and the next times it's almost instantly.
So i am guessing i should somehow load the txt file into memory when the app starts and go from there.
Is there any ways to do this or is this the right thing to do in the first place?
Should some kind of cache implementation solve my problem?
Would it be a good idea to use the Android Cache system?
This is my AsyncTask for referece:
public class AnalyzeReviewsAsync extends AsyncTask<ArrayList<Place.Review>, String, String> {
private final Activity activity;
private ProgressDialog progressDialog;
private SinglePlaceCallbacks callbacks;
public AnalyzeReviewsAsync(Activity activity, SinglePlaceCallbacks callbacks) {
this.activity = activity;
this.callbacks = callbacks;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Analyzing...");
progressDialog.show();
}
#Override
protected String doInBackground(ArrayList<Place.Review>... params) {
try {
return parseReviews(params[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
String review = s == null ? "Not present" : s;
callbacks.setReviewsTxt(review);
}
private String parseReviews(ArrayList<Place.Review> reviewArrayList) throws IOException {
if(reviewArrayList!=null && reviewArrayList.size()>0) {
String reviewOutput = "";
for (Place.Review r : reviewArrayList) {
reviewOutput += "<p> <font color='" + getReviewColor(SentiWordNet.getInstance().analyzeReview(r.text)) + "'>";
reviewOutput += r.text;
reviewOutput += "</font></p>";
}
return reviewOutput;
}else{
return null;
}
}
private String getReviewColor(String review) {
if (review.equals("very positive")) {
//return Constants.getContext().getResources().getString(R.color.very_positive);
return "lime";
} else if (review.equals("positive")) {
//return Constants.getContext().getResources().getString(R.color.positive);
return "teal";
} else if (review.equals("negative")) {
//return Constants.getContext().getResources().getString(R.color.negative);
return "maroon";
} else if (review.equals("very negative")) {
//return Constants.getContext().getResources().getString(R.color.very_negative);
return "red";
} else {
//return Constants.getContext().getResources().getString(R.color.neutral);
return "grey";
}
}
}
Nothing fails the first time, so it is nothing different in code, here is my SentiWordNet class for referece:
public class SentiWordNet {
private Map<String, Double> dictionary;
private static SentiWordNet _instance = null;
private SentiWordNet(Context context) throws IOException {
// This is our main dictionary representation
dictionary = new HashMap<String, Double>();
// From String to list of doubles.
HashMap<String, HashMap<Integer, Double>> tempDictionary = new HashMap<String, HashMap<Integer, Double>>();
InputStream rawRes = context.getResources().openRawResource(R.raw.swn);
BufferedReader csv = null;
try {
csv = new BufferedReader(new InputStreamReader(rawRes, "UTF8"));
int lineNumber = 0;
String line;
while ((line = csv.readLine()) != null) {
lineNumber++;
// If it's a comment, skip this line.
if (!line.trim().startsWith("#")) {
// We use tab separation
String[] data = line.split("\t");
String wordTypeMarker = data[0];
// Example line:
// POS ID PosS NegS SynsetTerm#sensenumber Desc
// a 00009618 0.5 0.25 spartan#4 austere#3 ascetical#2
// ascetic#2 practicing great self-denial;...etc
// Is it a valid line? Otherwise, through exception.
if (data.length != 6) {
throw new IllegalArgumentException(
"Incorrect tabulation format in file, line: "
+ lineNumber
);
}
// Calculate synset score as score = PosS - NegS
Double synsetScore = Double.parseDouble(data[2])
- Double.parseDouble(data[3]);
// Get all Synset terms
String[] synTermsSplit = data[4].split(" ");
// Go through all terms of current synset.
for (String synTermSplit : synTermsSplit) {
// Get synterm and synterm rank
String[] synTermAndRank = synTermSplit.split("#");
String synTerm = synTermAndRank[0] + "#"
+ wordTypeMarker;
int synTermRank = Integer.parseInt(synTermAndRank[1]);
// What we get here is a map of the type:
// term -> {score of synset#1, score of synset#2...}
// Add map to term if it doesn't have one
if (!tempDictionary.containsKey(synTerm)) {
tempDictionary.put(synTerm,
new HashMap<Integer, Double>());
}
// Add synset link to synterm
tempDictionary.get(synTerm).put(synTermRank,
synsetScore);
}
}
}
// Go through all the terms.
for (Map.Entry<String, HashMap<Integer, Double>> entry : tempDictionary
.entrySet()) {
String word = entry.getKey();
Map<Integer, Double> synSetScoreMap = entry.getValue();
// Calculate weighted average. Weigh the synsets according to
// their rank.
// Score= 1/2*first + 1/3*second + 1/4*third ..... etc.
// Sum = 1/1 + 1/2 + 1/3 ...
double score = 0.0;
double sum = 0.0;
for (Map.Entry<Integer, Double> setScore : synSetScoreMap
.entrySet()) {
score += setScore.getValue() / (double) setScore.getKey();
sum += 1.0 / (double) setScore.getKey();
}
score /= sum;
dictionary.put(word, score);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (csv != null) {
csv.close();
}
}
}
public static SentiWordNet getInstance() throws IOException {
if (_instance == null) {
_instance = new SentiWordNet(Constants.getContext());
}
return _instance;
}
public Double extract(String word) {
Double total = (double) 0;
if (dictionary.get(word + "#n") != null) {
total = dictionary.get(word + "#n") + total;
}
if (dictionary.get(word + "#a") != null) {
total = dictionary.get(word + "#a") + total;
}
if (dictionary.get(word + "#r") != null) {
total = dictionary.get(word + "#r") + total;
}
if (dictionary.get(word + "#v") != null) {
total = dictionary.get(word + "#v") + total;
}
return total;
}
public String analyzeReview(String review) {
String[] words = review.split("\\s+");
double totalScore = 0, averageScore;
for (String word : words) {
word = word.replaceAll("([^a-zA-Z\\s])", "");
if (_instance.extract(word) == null) {
continue;
}
Log.d("Total Score", String.valueOf(totalScore));
totalScore += _instance.extract(word);
}
averageScore = totalScore;
if (averageScore >= 0.75) {
return "very positive";
} else if (averageScore > 0.25 && averageScore < 0.5) {
return "positive";
} else if (averageScore >= 0.5) {
return "positive";
} else if (averageScore < 0 && averageScore >= -0.25) {
return "negative";
} else if (averageScore < -0.25 && averageScore >= -0.5) {
return "negative";
} else if (averageScore <= -0.75) {
return "very negative";
}
return "neutral";
}

add empty line between group of items in string

I know this is probably one of dumbest questions ever but my brain seems off.
I have this method which makes a string out of vCard:
public static String process(String vCard) {
ArrayList<ArrayList<String>> vCardData = parseData(vCard);
if (vCardData != null) {
StringBuilder readableVCard = new StringBuilder();
for (int i = 0; i < FIELD_COUNT; i++) {
ArrayList<String> vCardDataField = vCardData.get(i);
if (vCardDataField.size() > 0) {
String field = null;
if (i == FORMATTED_NAME) {
field = "Name: ";
} else if (i == PHONE_MOBILE) {
field = "Phone (mobile): ";
} else if (i == PHONE_HOME) {
field = "Phone (home): ";
} else if (i == PHONE_WORK) {
field = "Phone (work): ";
} else if (i == PHONE) {
field = "Phone: ";
} else if (i == FAX_HOME) {
field = "Fax (home): ";
} else if (i == FAX_WORK) {
field = "Fax (work): ";
} else if (i == PAGER) {
field = "Pager: ";
} else if (i == EMAIL_HOME) {
field = "Email (home): ";
} else if (i == EMAIL_WORK) {
field = "Email (work): ";
} else if (i == EMAIL) {
field = "Email: ";
} else if (i == ORGANISATION) {
field = "Company: ";
} else if (i == JOB_TITLE) {
field = "Job title: ";
} else if (i == ADDRESS_HOME) {
field = "Address (home): ";
} else if (i == ADDRESS_WORK) {
field = "Address (work): ";
} else if (i == ADDRESS) {
field = "Address: ";
} else if (i == IM_SKYPE) {
field = "Skype: ";
} else if (i == IM_GOOGLE) {
field = "Google Talk: ";
} else if (i == IM_JABBER) {
field = "Jabber: ";
} else if (i == IM_YAHOO) {
field = "Yahoo: ";
} else if (i == IM_MSN) {
field = "MSN: ";
} else if (i == IM_ICQ) {
field = "ICQ: ";
} else if (i == IM_AIM) {
field = "AIM: ";
} else if (i == TWITTER) {
field = "Twitter: ";
} else if (i == BIRTHDAY) {
field = "Birthday: ";
} else if (i == ANNIVERSARY) {
field = "Anniversary: ";
} else if (i == NOTES) {
field = "Notes: ";
} else if (i == WEBSITE) {
field = "Website: ";
} else {
continue;
}
if (readableVCard.length() != 0) {
readableVCard.append("\n");
}
readableVCard.append(field);
for (int j = 0; j < vCardDataField.size(); j++) {
if (j != 0) {
readableVCard.append("; ");
}
readableVCard.append(vCardDataField.get(j));
}
}
}
if (readableVCard.length() != 0) {
String textVCard = readableVCard.toString();
try {
textVCard = qpDecoder.decode(readableVCard.toString());
} catch (Exception e) {
Logger.e("VCard to UTF-8", e.getMessage());
}
return (textVCard);
}
}
return (null);
}
So my current output is like this:
Name: Marko
Phone(mobile):1312
Phone(fax):441231
Phone(home):543534
Email(home):dddd
Email(work):eeee
Email(other):aaaa
What I want is to add a line break between groups (name/phone/email) so I get something like this:
Name: Marko
Phone(mobile):1312
Phone(fax):441231
Phone(home):543534
Email(home):dddd
Email(work):eeee
Email(other):aaaa
Addressblablabla
.
.
.
IMsblablabla
.
.
.
Can someone help please?
Thanks.
You could iterate the string array, splitting by : and then checking if next item starts with current. If it does, then do nothing, if it doesn't you add the line break to current item and replace it in the array.
Note: splitting with : also separates all phone (xxx) types. To avoid this, you can create enum type, map type to Phone if the string starts with "phone" and use that enum as current type while iterating through the array. If current type if different than next type you add line break.
You can append line separator via
System.getProperty("line.separator");

Categories

Resources