I use the follow code to parse price from Google Play In-app Billing:
private static Number parsePrice(String priceFromGoogle) {
Locale currencyLocale = getCurrencyLocale(priceFromGoogle);
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(currencyLocale);
Number number = null;
try {
number = numberFormat.parse(priceFromGoogle);
} catch (ParseException e) {
e.printStackTrace();
}
return number;
}
private Locale getCurrencyLocale(String price) {
Locale locale = null;
for (Locale availableLocale : Locale.getAvailableLocales()) {
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(availableLocale);
try {
numberFormat.parse(price);
locale = availableLocale;
break;
} catch (ParseException e) {
//do nothing
}
}
return locale;
}
It works fine on my test devices and in my locale. But on some devices and in some countries I encounter prices like this: "Php1,337.07", "US$ 29.99", "MX$374.79". My approach doesn't work in this case.
Is there an universal approach to solve this problem?
Check their In-app billing sample project and modify SkuDetails.java so that you can get that information as well:
import org.json.JSONException;
import org.json.JSONObject;
/**
* Represents an in-app product's listing details.
*/
public class SkuDetails {
String mItemType;
String mSku;
String mType;
int mPriceAmountMicros;
String mPriceCurrencyCode;
String mPrice;
String mTitle;
String mDescription;
String mJson;
public SkuDetails(String jsonSkuDetails) throws JSONException {
this(IabHelper.ITEM_TYPE_INAPP, jsonSkuDetails);
}
public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException {
mItemType = itemType;
mJson = jsonSkuDetails;
JSONObject o = new JSONObject(mJson);
mSku = o.optString("productId");
mType = o.optString("type");
mPrice = o.optString("price");
mPriceAmountMicros = o.optInt("price_amount_micros");
mPriceCurrencyCode = o.optString("price_currency_code");
mTitle = o.optString("title");
mDescription = o.optString("description");
}
public String getSku() { return mSku; }
public String getType() { return mType; }
public String getPrice() { return mPrice; }
public String getTitle() { return mTitle; }
public String getDescription() { return mDescription; }
public int getPriceAmountMicros() { return mPriceAmountMicros; }
public String getPriceCurrencyCode() { return mPriceCurrencyCode; }
#Override
public String toString() {
return "SkuDetails:" + mJson;
}
}
You can get the price in micros in the JSON retrieved by IabHelper.
This is not officially documented but here is how I've done it by editing SkuDetails.java :
public class SkuDetails {
...
Double mPriceMicros;
public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException {
...
String priceMicros = o.optString("price_amount_micros");
if (priceMicros != null) {
String format = new StringBuilder(priceMicros).insert(priceMicros.length() - 6, ".").toString();
mPriceMicros = Double.parseDouble(format);
}
}
...
public Double getPriceMicros() { return mPriceMicros; }
}
Hope this helps !
PS : I tried your Price class but it parsed 0.8 for 0,89 €
As Google Play may return prices in currency format which is unsupported by java.text.NumberFormat, I wrote my own implementation
public class Price {
private double value;
private String currency;
private String pattern;
private DecimalFormat decimalFormat;
private Price() {}
private static String currencyToDecimalFormat(String value, Price price) {
char decimalSeparator = '.';
char groupingSeparator = 0;
if (value.length() >= 3) {
char[] chars = value.toCharArray();
if (chars[chars.length - 2] == ',') {
decimalSeparator = ',';
chars[chars.length - 2] = '.';
} else if (chars[chars.length - 3] == ',') {
decimalSeparator = ',';
chars[chars.length - 3] = '.';
}
value = new String(chars);
}
if (value.contains(",")) {
groupingSeparator = ',';
value = value.replaceAll(",", "");
} else if (value.contains(" ")) {
groupingSeparator = ' ';
value = value.replaceAll(" ", "");
} else if (value.contains("\u00A0")) {
groupingSeparator = '\u00A0';
value = value.replaceAll("\u00A0", "");
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
if (groupingSeparator != 0) {
price.decimalFormat = new DecimalFormat("###,###.00");
symbols.setGroupingSeparator(groupingSeparator);
} else {
price.decimalFormat = new DecimalFormat("######.00");
}
symbols.setDecimalSeparator(decimalSeparator);
price.decimalFormat.setDecimalFormatSymbols(symbols);
return value.replaceAll(",", "");
}
public static Price parsePrice(String priceFromGoogle) {
Price price = new Price();
StringBuilder patternBuilder = new StringBuilder();
Pattern pattern = Pattern.compile("(?:[0-9]{1,3})(?:[0-9,.\\s\u00A0]+)");
Matcher matcher = pattern.matcher(priceFromGoogle);
matcher.find();
String priceString = matcher.group();
if (priceFromGoogle.indexOf(priceString) == 0) {
if (priceFromGoogle.length() != priceString.length()) {
price.currency = priceFromGoogle.substring(priceString.length());
} else {
price.currency = "";
}
} else {
price.currency = priceFromGoogle.substring(0, priceFromGoogle.indexOf(priceString));
}
price.currency = price.currency.trim();
if (priceFromGoogle.startsWith(price.currency)) {
patternBuilder.append("%1s");
char nextChar = priceFromGoogle.charAt(price.currency.length());
if (nextChar == ' ' || nextChar == 0xA0) {
patternBuilder.append(' ');
}
patternBuilder.append("%2$s");
} else {
patternBuilder.append("%2$s");
char prevChar = priceFromGoogle.charAt(priceFromGoogle.indexOf(price.currency) - 1);
if (prevChar == ' ' || prevChar == 0xA0) {
patternBuilder.append(' ');
}
patternBuilder.append("%1s");
}
price.pattern = patternBuilder.toString();
priceString = trim(priceString);
priceString = currencyToDecimalFormat(priceString, price);
price.value = Double.parseDouble(priceString);
return price;
}
#Override
public String toString() {
if (pattern != null) {
return String.format(pattern, currency, decimalFormat.format(value));
} else {
return "";
}
}
}
EDIT1:
Because of Google uses non-breaking space instead of usual space you need check this and use custom trim function:
public static String trim(String text) {
int start = 0, last = text.length() - 1;
int end = last;
while ((start <= end) && (text.charAt(start) <= ' ' || text.charAt(start) == 0xA0)) {
start++;
}
while ((end >= start) && (text.charAt(end) <= ' ' || text.charAt(end) == 0xA0)) {
end--;
}
if (start == 0 && end == last) {
return text;
}
return text.substring(start, end);
}
Related
I have converted below kotlin file from existing options
#Entity
data class DatabaseVideo constructor(
#PrimaryKey
val url: String,
val updated: String,
val title: String,
val description: String,
val thumbnail: String)
/**
* Map DatabaseVideos to domain entities
*/
fun List<DatabaseVideo>.asDomainModel(): List<DevByteVideo> {
return map {
DevByteVideo(
url = it.url,
title = it.title,
description = it.description,
updated = it.updated,
thumbnail = it.thumbnail)
}
}
The Java out put file is here as below
#Metadata(
mv = {1, 1, 18},
bv = {1, 0, 3},
k = 2,
d1 = {"\u0000\u0010\n\u0000\n\u0002\u0010 \n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\u001a\u0016\u0010\u0000\u001a\b\u0012\u0004\u0012\u00020\u00020\u0001*\b\u0012\u0004\u0012\u00020\u00030\u0001¨\u0006\u0004"},
d2 = {"asDomainModel", "", "Lcom/example/android/devbyteviewer/domain/DevByteVideo;", "Lcom/example/android/devbyteviewer/database/DatabaseVideo;", "app_debug"}
)
public final class DatabaseEntitiesKt {
#NotNull
public static final List asDomainModel(#NotNull List $this$asDomainModel) {
Intrinsics.checkParameterIsNotNull($this$asDomainModel, "$this$asDomainModel");
Iterable $this$map$iv = (Iterable)$this$asDomainModel;
int $i$f$map = false;
Collection destination$iv$iv = (Collection)(new ArrayList(CollectionsKt.collectionSizeOrDefault($this$map$iv, 10)));
int $i$f$mapTo = false;
Iterator var6 = $this$map$iv.iterator();
while(var6.hasNext()) {
Object item$iv$iv = var6.next();
DatabaseVideo it = (DatabaseVideo)item$iv$iv;
int var9 = false;
String var10002 = it.getUrl();
String var10003 = it.getTitle();
String var10004 = it.getDescription();
String var10005 = it.getUpdated();
String var10 = it.getThumbnail();
String var11 = var10005;
String var12 = var10004;
String var13 = var10003;
String var14 = var10002;
DevByteVideo var16 = new DevByteVideo(var13, var12, var14, var11, var10);
destination$iv$iv.add(var16);
}
return (List)destination$iv$iv;
}
}
// DatabaseVideo.java
package com.example.android.devbyteviewer.database;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
#Metadata(
mv = {1, 1, 18},
bv = {1, 0, 3},
k = 1,
d1 = {"\u0000\"\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0012\n\u0002\u0010\u000b\n\u0002\b\u0002\n\u0002\u0010\b\n\u0002\b\u0002\b\u0087\b\u0018\u00002\u00020\u0001B-\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u0012\u0006\u0010\u0004\u001a\u00020\u0003\u0012\u0006\u0010\u0005\u001a\u00020\u0003\u0012\u0006\u0010\u0006\u001a\u00020\u0003\u0012\u0006\u0010\u0007\u001a\u00020\u0003¢\u0006\u0002\u0010\bJ\t\u0010\u000f\u001a\u00020\u0003HÆ\u0003J\t\u0010\u0010\u001a\u00020\u0003HÆ\u0003J\t\u0010\u0011\u001a\u00020\u0003HÆ\u0003J\t\u0010\u0012\u001a\u00020\u0003HÆ\u0003J\t\u0010\u0013\u001a\u00020\u0003HÆ\u0003J;\u0010\u0014\u001a\u00020\u00002\b\b\u0002\u0010\u0002\u001a\u00020\u00032\b\b\u0002\u0010\u0004\u001a\u00020\u00032\b\b\u0002\u0010\u0005\u001a\u00020\u00032\b\b\u0002\u0010\u0006\u001a\u00020\u00032\b\b\u0002\u0010\u0007\u001a\u00020\u0003HÆ\u0001J\u0013\u0010\u0015\u001a\u00020\u00162\b\u0010\u0017\u001a\u0004\u0018\u00010\u0001HÖ\u0003J\t\u0010\u0018\u001a\u00020\u0019HÖ\u0001J\t\u0010\u001a\u001a\u00020\u0003HÖ\u0001R\u0011\u0010\u0006\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\t\u0010\nR\u0011\u0010\u0007\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\u000b\u0010\nR\u0011\u0010\u0005\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\f\u0010\nR\u0011\u0010\u0004\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\r\u0010\nR\u0016\u0010\u0002\u001a\u00020\u00038\u0006X\u0087\u0004¢\u0006\b\n\u0000\u001a\u0004\b\u000e\u0010\n¨\u0006\u001b"},
d2 = {"Lcom/example/android/devbyteviewer/database/DatabaseVideo;", "", "url", "", "updated", "title", "description", "thumbnail", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "getDescription", "()Ljava/lang/String;", "getThumbnail", "getTitle", "getUpdated", "getUrl", "component1", "component2", "component3", "component4", "component5", "copy", "equals", "", "other", "hashCode", "", "toString", "app_debug"}
)
#Entity
public final class DatabaseVideo {
#PrimaryKey
#NotNull
private final String url;
#NotNull
private final String updated;
#NotNull
private final String title;
#NotNull
private final String description;
#NotNull
private final String thumbnail;
#NotNull
public final String getUrl() {
return this.url;
}
#NotNull
public final String getUpdated() {
return this.updated;
}
#NotNull
public final String getTitle() {
return this.title;
}
#NotNull
public final String getDescription() {
return this.description;
}
#NotNull
public final String getThumbnail() {
return this.thumbnail;
}
public DatabaseVideo(#NotNull String url, #NotNull String updated, #NotNull String title, #NotNull String description, #NotNull String thumbnail) {
Intrinsics.checkParameterIsNotNull(url, "url");
Intrinsics.checkParameterIsNotNull(updated, "updated");
Intrinsics.checkParameterIsNotNull(title, "title");
Intrinsics.checkParameterIsNotNull(description, "description");
Intrinsics.checkParameterIsNotNull(thumbnail, "thumbnail");
super();
this.url = url;
this.updated = updated;
this.title = title;
this.description = description;
this.thumbnail = thumbnail;
}
#NotNull
public final String component1() {
return this.url;
}
#NotNull
public final String component2() {
return this.updated;
}
#NotNull
public final String component3() {
return this.title;
}
#NotNull
public final String component4() {
return this.description;
}
#NotNull
public final String component5() {
return this.thumbnail;
}
#NotNull
public final DatabaseVideo copy(#NotNull String url, #NotNull String updated, #NotNull String title, #NotNull String description, #NotNull String thumbnail) {
Intrinsics.checkParameterIsNotNull(url, "url");
Intrinsics.checkParameterIsNotNull(updated, "updated");
Intrinsics.checkParameterIsNotNull(title, "title");
Intrinsics.checkParameterIsNotNull(description, "description");
Intrinsics.checkParameterIsNotNull(thumbnail, "thumbnail");
return new DatabaseVideo(url, updated, title, description, thumbnail);
}
// $FF: synthetic method
public static DatabaseVideo copy$default(DatabaseVideo var0, String var1, String var2, String var3, String var4, String var5, int var6, Object var7) {
if ((var6 & 1) != 0) {
var1 = var0.url;
}
if ((var6 & 2) != 0) {
var2 = var0.updated;
}
if ((var6 & 4) != 0) {
var3 = var0.title;
}
if ((var6 & 8) != 0) {
var4 = var0.description;
}
if ((var6 & 16) != 0) {
var5 = var0.thumbnail;
}
return var0.copy(var1, var2, var3, var4, var5);
}
#NotNull
public String toString() {
return "DatabaseVideo(url=" + this.url + ", updated=" + this.updated + ", title=" + this.title + ", description=" + this.description + ", thumbnail=" + this.thumbnail + ")";
}
public int hashCode() {
String var10000 = this.url;
int var1 = (var10000 != null ? var10000.hashCode() : 0) * 31;
String var10001 = this.updated;
var1 = (var1 + (var10001 != null ? var10001.hashCode() : 0)) * 31;
var10001 = this.title;
var1 = (var1 + (var10001 != null ? var10001.hashCode() : 0)) * 31;
var10001 = this.description;
var1 = (var1 + (var10001 != null ? var10001.hashCode() : 0)) * 31;
var10001 = this.thumbnail;
return var1 + (var10001 != null ? var10001.hashCode() : 0);
}
public boolean equals(#Nullable Object var1) {
if (this != var1) {
if (var1 instanceof DatabaseVideo) {
DatabaseVideo var2 = (DatabaseVideo)var1;
if (Intrinsics.areEqual(this.url, var2.url) && Intrinsics.areEqual(this.updated, var2.updated) && Intrinsics.areEqual(this.title, var2.title) && Intrinsics.areEqual(this.description, var2.description) && Intrinsics.areEqual(this.thumbnail, var2.thumbnail)) {
return true;
}
}
return false;
} else {
return true;
}
}
}
It is seems to be buggy. very difficult to understand.is there any options to get pure java code ? please let me know if we can able to perform conversion other than android studio
You have to realise that kotlin runs on JVM, hence it can do everything that Java can and nothing more. The extra features that Kotlin provides such as not null types etc are implemented using same byte code that java uses.
All the extra java code that you call "buggy", is there for some specific feature requirement of kotlin.
For example all the Intrinsics.checkParameterIsNotNull checks are there on variables that are declared non nullable, that is how kotlin makes sure that nulls are not introduced in such variables.
So the java output you see doesn't contain any extra code, its the actual java equivalent code of your kotlin class.
Is there a way in which I can display the list of Time zones in a format like (GMT+1.00) Windhoek like the way we see in S Planner on the Android app?
Can anyone help me in sorting out this issue?
Thanks in adavance
First I suggest you to create a wrapper class to manage the format of TimeZone objects as follow:
public class TimeZoneWrapper {
private final TimeZone timeZone;
private String timeZoneID;
private String timeZoneDisplay;
private String timeZoneRawDisplayName;
public TimeZoneWrapper(final TimeZone timeZone) {
this.timeZone = timeZone;
setDisplayStrings();
}
private void setDisplayStrings() {
this.timeZoneID = timeZone.getID().replaceAll("_", " ");
int offset = timeZone.getRawOffset();
if (timeZone.inDaylightTime(new Date())) {
offset = offset + timeZone.getDSTSavings();
}
this.timeZoneRawDisplayName = timeZone.getDisplayName(false,
TimeZone.SHORT);
final int offsetHrs = offset / 1000 / 60 / 60;
final int offsetMins = offset / 1000 / 60 % 60;
if (offsetHrs + offsetMins == 0) {
this.timeZoneDisplay = "GMT";
} else {
String suffix = "";
if (offset < 0) {
suffix += "-";
} else {
suffix += "+";
}
if (offsetMins != 0) {
suffix += offsetHrs + "." + offsetMins;
} else {
suffix += offsetHrs;
}
this.timeZoneDisplay = "GMT" + suffix;
}
}
public String getTimeZoneID() {
return timeZoneID;
}
public String getTimeZoneDisplay() {
return timeZoneDisplay;
}
public String getTimeZoneRawDisplayName() {
return timeZoneRawDisplayName;
}
public TimeZone getTimeZone() {
return timeZone;
}
#Override
public final boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TimeZoneWrapper)) {
return false;
}
final TimeZoneWrapper that = (TimeZoneWrapper) o;
return that.timeZone.equals(this.timeZone);
}
}
Once you have created (if you want) this wrapper class you can retrieve the TimeZones from your device with the following method in your mainActivity.
private List<TimeZoneWrapper> buildTimeZoneWrappers() {
final List<TimeZoneWrapper> timeZoneWrappers = new ArrayList<TimeZoneWrapper>();
final List<TimeZone> timeZones = new ArrayList<TimeZone>();
final String[] timeZoneIds = TimeZone.getAvailableIDs();
for (final String id : timeZoneIds) {
timeZones.add(TimeZone.getTimeZone(id));
}
for (final TimeZone timeZone : timeZones) {
timeZoneWrappers.add(new TimeZoneWrapper(timeZone));
}
return timeZoneWrappers;
}
Now you have a list of "well" formatted timezone, so if you need a picker with this value you simply have to create one with them.
String[] temp;
for (int i=0;i<timeZoneWrappers.size();i++){
temp[i]=timeZoneWrappers.get(i).getTimeZoneDisplay();
}
NumberPicker picker = new NumberPicker(getApplicationContext());
picker.setDisplayedValues(temp);
Let me know;)
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";
}
I am trying to create a text to QR code converter.
I used the core2.2.jar from http://code.google.com/p/zxing/downloads/list and the code as told in Integrating the ZXing library directly into my Android application.
My Main.Activity is as shown below
package com.example.qr_androidone;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.qrCode);
String qrData = "Data I want to encode in QR code";
int qrCodeDimention = 500;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I used the "Contents.java" and "QRCodeEncoder.java" as shown in link Integrating the ZXing library directly into my Android application. I changed "activity_main.xml" also , as shown in above link
There are no errors in compiling, but there is error when the app runs
Could not find class 'com.google.zxing.EncodeHintType', referenced
from method com.example.qr_androidone.QRCodeEncoder.encodeAsBitmap
Could not find class 'com.google.zxing.MultiFormatWriter', referenced
from method com.example.qr_androidone.QRCodeEncoder.encodeAsBitmap
java.lang.NoClassDefFoundError: com.google.zxing.BarcodeFormat
Please help me solve the error
Download de JAR file, go to your Build Path and Import it from External JARs.
http://repo1.maven.org/maven2/com/google/zxing/core/2.2/
Then import it in your project.
you need the class of QRCodeEncoder.java..
public class QRCodeEncoder {
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
// private int dimension = Integer.MAX_VALUE;
private String contents = null;
private String displayContents = null;
private String title = null;
private BarcodeFormat format = null;
private boolean encoded = false;
public QRCodeEncoder(String data, Bundle bundle, String type, String format) {
// this.dimension = dimension;
encoded = encodeContents(data, bundle, type, format);
}
public String getContents() {
return contents;
}
public String getDisplayContents() {
return displayContents;
}
public String getTitle() {
return title;
}
private boolean encodeContents(String data, Bundle bundle, String type, String formatString) {
// Default to QR_CODE if no format given.
format = null;
if (formatString != null) {
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
}
}
if (format == null || format == BarcodeFormat.QR_CODE) {
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(data, bundle, type);
} else if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
return contents != null && contents.length() > 0;
}
private void encodeQRCodeContents(String data, Bundle bundle, String type) {
if (type.equals(Contents.Type.TEXT)) {
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
} else if (type.equals(Contents.Type.EMAIL)) {
data = trim(data);
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = "E-Mail";
}
} else if (type.equals(Contents.Type.PHONE)) {
data = trim(data);
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "Phone";
}
} else if (type.equals(Contents.Type.SMS)) {
data = trim(data);
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "SMS";
}
} else if (type.equals(Contents.Type.CONTACT)) {
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
uniquePhones.add(phone);
}
}
for (String phone : uniquePhones) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
uniqueEmails.add(email);
}
}
for (String email : uniqueEmails) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
String url = trim(bundle.getString(Contents.URL_KEY));
if (url != null) {
// escapeMECARD(url) -> wrong escape e.g. http\://zxing.google.com
newContents.append("URL:").append(url).append(';');
newDisplayContents.append('\n').append(url);
}
String note = trim(bundle.getString(Contents.NOTE_KEY));
if (note != null) {
newContents.append("NOTE:").append(escapeMECARD(note)).append(';');
newDisplayContents.append('\n').append(note);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = "Contact";
} else {
contents = null;
displayContents = null;
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
if (bundle != null) {
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = "Location";
}
}
}
}
public Bitmap encodeAsBitmap() throws WriterException {
if (!encoded) return null;
Hashtable<EncodeHintType, String> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result =writer.encode(contents, format, 300, 300, hints);
int width = result.getWidth();
int height =result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
if(result.get(x, y) )
{
pixels[offset + x] = BLACK ;
}
else
pixels[offset + x] = WHITE ;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) { return "UTF-8"; }
}
return null;
}
private static String trim(String s) {
if (s == null) { return null; }
String result = s.trim();
return result.length() == 0 ? null : result;
}
private static String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) { return input; }
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}
and also need content.java class..
public class Contents {
private Contents() {
}
public static final class Type {
public static final String TEXT = "TEXT_TYPE";
public static final String EMAIL = "EMAIL_TYPE";
public static final String PHONE = "PHONE_TYPE";
public static final String SMS = "SMS_TYPE";
public static final String CONTACT = "CONTACT_TYPE";
public static final String LOCATION = "LOCATION_TYPE";
private Type() {
}
}
public static final String URL_KEY = "URL_KEY";
public static final String NOTE_KEY = "NOTE_KEY";
public static final String[] PHONE_KEYS = {
ContactsContract.Intents.Insert.PHONE, ContactsContract.Intents.Insert.SECONDARY_PHONE,
ContactsContract.Intents.Insert.TERTIARY_PHONE
};
public static final String[] PHONE_TYPE_KEYS = {
ContactsContract.Intents.Insert.PHONE_TYPE,
ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE,
ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE
};
public static final String[] EMAIL_KEYS = {
ContactsContract.Intents.Insert.EMAIL, ContactsContract.Intents.Insert.SECONDARY_EMAIL,
ContactsContract.Intents.Insert.TERTIARY_EMAIL
};
public static final String[] EMAIL_TYPE_KEYS = {
ContactsContract.Intents.Insert.EMAIL_TYPE,
ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE,
ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE
};
}
also need the core.jar file..
its perfectly work...
Can someone please help me with some code I have it is supposed to check that the string being passed is of 2 string and 3 ints which works fine, but if the 1 int is a zero it doesn't work
so if it was CM044 it won't work, CM450 will work can someone please help.
public boolean checkModule(String Module) {
if(Module.length() == 5){
boolean hasString = false;
boolean hasInt = false;
String letters = Module.substring(0, 2);
Pattern p = Pattern.compile("^[a-zA-Z]+$");
Matcher m = p.matcher(letters);
if (m.matches()) {
hasString = true;
}
String numbers=Module.substring(2,5);
try {
int num = Integer.parseInt(numbers);
String n = num + "";
if (num >0 && n.length() == 3)
hasInt = true;
} catch (Exception e) {
}
if (hasInt && hasString) {
return true;
}
}else{
return false;
}
return false;
}
Thanks
If you are going to use regular expressions you should definitely stick with them and not vary in and out.
package com.examples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
new Main();
}
public Main() {
String[] testInputs = new String[] {"CM045", "CM450"};
for(String input : testInputs) {
System.out.println("The module " + input + " is " + (checkModule(input) ? "valid" : "invalid"));
}
}
public boolean checkModule(String Module){
Pattern p = Pattern.compile("[A-Z]{2}[0-9]{3}");
Matcher m = p.matcher(Module.toUpperCase());
return m.matches();
}
}
if the String is "045" the Integer value is 45 and so the length of num can't be 3
Use this
if(num>=0) {
hasInt = true;
}
and it has to work