How to customize x axis value in horizontal mpandroidchart? - android

It may be dumb question am using horizontal mpandroid barchart am having numbers in x axis like 6,000,000 so x axis getting collapsed so what is need to do is convert the number into indian rupees like 6 cr how can i do this so far what i have tried is:
This is where am setting value for horizontal barchart:
ArrayList<BarEntry> entries = new ArrayList<>();
ArrayList<String> labels = new ArrayList<String>();
Format format = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
// System.out.println(format.format(new BigDecimal("100000000")));
for(int i=0;i<listobj.size();i++){
String s= format.format(listobj.get(i).getData());
// Log.e("ss", s);
// Integer numberformat=Integer.parseInt(s);
entries.add(new BarEntry(listobj.get(i).getData(),i));
labels.add(listobj.get(i).getLabel());
}
XAxis axis=barChart.getXAxis();
BarDataSet dataset = new BarDataSet(entries, "# of Calls");
//dataset.setValueFormatter(new LargeValueFormatter());
BarData datas = new BarData(labels, dataset);
/// datas.setValueFormatter(new LargeValueFormatter());
barChart.setData(datas);
barChart.setDescription("Description");
barChart.getLegend().setWordWrapEnabled(true);
This is value Formatter:
/**
* Created by 4264 on 30-05-2016.
*/
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.text.DecimalFormat;
/**
* Predefined value-formatter that formats large numbers in a pretty way.
* Outputs: 856 = 856; 1000 = 1k; 5821 = 5.8k; 10500 = 10k; 101800 = 102k;
* 2000000 = 2m; 7800000 = 7.8m; 92150000 = 92m; 123200000 = 123m; 9999999 =
* 10m; 1000000000 = 1b; Special thanks to Roman Gromov
* (https://github.com/romangromov) for this piece of code.
*
* #author Philipp Jahoda
* #author Oleksandr Tyshkovets <olexandr.tyshkovets#gmail.com>
*/
class LargeValueFormatter implements ValueFormatter {
private static String[] SUFFIX = new String[]{
"", "k", "m", "b", "t"
};
private static final int MAX_LENGTH = 4;
private DecimalFormat mFormat;
private String mText = "";
public LargeValueFormatter() {
mFormat = new DecimalFormat("###E0");
}
/**
* Creates a formatter that appends a specified text to the result string
*
* #param appendix a text that will be appended
*/
public LargeValueFormatter(String appendix) {
this();
mText = appendix;
}
// ValueFormatter
#Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return makePretty(value) + mText;
}
// YAxisValueFormatter
/**
* Set an appendix text to be added at the end of the formatted value.
*
* #param appendix
*/
public void setAppendix(String appendix) {
this.mText = appendix;
}
/**
* Set custom suffix to be appended after the values.
* Default suffix: ["", "k", "m", "b", "t"]
*
* #param suff new suffix
*/
public void setSuffix(String[] suff) {
if (suff.length == 5) {
SUFFIX = suff;
}
}
/**
* Formats each number properly. Special thanks to Roman Gromov
* (https://github.com/romangromov) for this piece of code.
*/
private String makePretty(double number) {
String r = mFormat.format(number);
r = r.replaceAll("E[0-9]", SUFFIX[Character.getNumericValue(r.charAt(r.length() - 1)) / 3]);
while (r.length() > MAX_LENGTH || r.matches("[0-9]+\\.[a-z]")) {
r = r.substring(0, r.length() - 2) + r.substring(r.length() - 1);
}
return r;
}
}
I don't know how to customize the x axis value how can i do this can anyone help me out thanks in advance!!

You have 2 options that you can try to solve your issue
1) While inserting the value you can divide the value by 1000,000 and change your label to 6Cr . I have a chart that has values from 0 to 30 and one value is 4000. While storing the value in database I divide it by 100 and while displaying I change the label to show the correct value
Sample SQL insert value :
Float.valueOf(LEUCO_COUNT.getText().toString()) / 1000,
2) Option 2 is to divide the value by 1000,000 before displaying it and also modify your babel to show Cr. You can go throught he API to find how to set a custom label
Hope this helps.

You need to replace existing function with below function.It working for me.
private String makePretty(double number) {
double Cr = 10000000;
double Lac = 100000;
String result = mFormat.format(number);
try {
double LAmt = Double.parseDouble(result);
String Append = "";
if (LAmt > Cr) {//1Crore
LAmt /= Cr;
Append = "Cr";
} else {
LAmt /= Lac;
Append = "L";
}
result = CommonUtils.GetFormattedString("" + LAmt) + Append;
} catch (NumberFormatException e) {
Log.d("", "");
}
return result;
}

Related

TextView misbehaving when appending two strings

I am working on writing a simple temperature conversion program, to familiarize myself with Android programming. The user types in a number to an EditText, and it converts it from Fahrenheit to Celsius, or vice versa, then puts the answer in a TextView. I want to append a Unicode Celsius/Fahrenheit symbol to the end of the answer before displaying it. When I don't have it appending the symbol, it works fine and displays the correct number, but when it is trying to append the symbol to the end, the output displays all wrong, with a long string of numbers at the end (and still no Unicode symbol).
Here's my code:
This is the converter utility class:
public class ConverterUtil {
//Convert to celsius
public static String convertFahrenheitToCelsius(float fahrenheit) {
float temperature = (fahrenheit - 32) * 5 / 9;
DecimalFormat df = new DecimalFormat("#.#");
return df.format(temperature) + R.string.celsius_symbol;
}
//Convert to fahrenheit
public static String convertCelsiustoFahrenheit(float celsius) {
float temperature = (celsius * 9) / 5 + 32; //Append the unicode Celsius symbol (\u2103), then return
DecimalFormat df = new DecimalFormat("#.#");a
return df.format(temperature) + R.string.fahrenheit_symbol; //Append the unicode Fahrenheit symbol (\u2109), then return
}
}
And this is where I call it:
public void calculateTemperature(){
RadioButton celsiusButton = (RadioButton) findViewById(R.id.button2);
TextView output = (TextView) findViewById(R.id.output);
if (text.getText().length() == 0) {
output.setText("");
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
String outputText = celsiusButton.isChecked() ? ConverterUtil.convertFahrenheitToCelsius(inputValue) : ConverterUtil.convertCelsiustoFahrenheit(inputValue);
output.setText(outputText);
}
If I take out the part where I append the Unicode symbols, it looks like this:
And if I put that back in, I get this:
How do I fix that?
Looks like the resourceID of your fahrenheit_symbol & celsius_symbol are getting appended to your text than the actual character.
Try this,
public class ConverterUtil {
//Convert to celsius
public static String convertFahrenheitToCelsius(Context context, float fahrenheit) {
float temperature = (fahrenheit - 32) * 5 / 9;
DecimalFormat df = new DecimalFormat("#.#");
return df.format(temperature) + context.getResources().getString(R.string.celsius_symbol);
}
//Convert to fahrenheit
public static String convertCelsiustoFahrenheit(Context context, float celsius) {
float temperature = (celsius * 9) / 5 + 32; //Append the unicode Celsius symbol (\u2103), then return
DecimalFormat df = new DecimalFormat("#.#");a
return df.format(temperature) + context.getResources().getString(R.string.fahrenheit_symbol); //Append the unicode Fahrenheit symbol (\u2109), then return
}
}
Change where you call it like this,
public void calculateTemperature(){
RadioButton celsiusButton = (RadioButton) findViewById(R.id.button2);
TextView output = (TextView) findViewById(R.id.output);
if (text.getText().length() == 0) {
output.setText("");
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
String outputText = celsiusButton.isChecked() ? ConverterUtil.convertFahrenheitToCelsius(YourActivity.this, inputValue) : ConverterUtil.convertCelsiustoFahrenheit(YourActivity.this, inputValue);
output.setText(outputText);
}
Change
return df.format(temperature) + R.string.fahrenheit_symbol;
return df.format(temperature) + R.string.celsius_symbol;
to
return df.format(temperature) + getString(R.string.fahrenheit_symbol);
return df.format(temperature) + getString(R.string.celsius_symbol);
R.string.fahrenheit_symbol and R.string.celsius_symbol are both integers. You will need to look up the relevant string resource using Context.getResources().getString().
You will need to pass a Context (such as the calling Activity) to your ConverterUtil.

Sqlite: select items based on distance (latitude and longitude)

I have a table in wich items are stored using the geographic location based on latitude and longitude. At one point I want to retrieve only those items from the database that are in a specific range (distance or radius) of my current position.
Item (latitude, longitude)
So I followed this really nice post and tried to implement the answer with the highest votes. First thing: I had to add some more columns when storing the items. This enables the select-statement later on:
Item (lat, lat_cos, lat_sin, lng, lng_cos, lng_sin)
So far so good, but when I then try to build the query, I go nuts. If I use the less-symbol < then all items are retrieved (even if too far away). But if I use the greater-symbol > no items are retrieved. But I know that there are items in my range.
Question: So what am I doing wrong with that term?
WHERE (coslat * LAT_COS * (LNG_COS * coslng + LNG_SIN * sinlng)) + sinlat * LAT_SIN > cos_allowed_distance
Here's the code that I'm using for querying my ContentProvider. The ContentInfo class has fields for sortOrder, selection and selectionArgs:
public static ContentInfo buildDistanceWhereClause(double latitude, double longitude, double distanceInKilometers) {
final double coslat = Math.cos(Math.toRadians(latitude));
final double sinlat = Math.sin(Math.toRadians(latitude));
final double coslng = Math.cos(Math.toRadians(longitude));
final double sinlng = Math.sin(Math.toRadians(longitude));
// (coslat * LAT_COS * (LNG_COS * coslng + LNG_SIN * sinlng)) + sinlat * LAT_SIN > cos_allowed_distance
final String where = "(? * ? * (? * ? + ? * ?)) + ? * ? > ?";
final String[] whereClause = new String[] {
String.valueOf(coslat),
ItemTable.COLUMN_LATITUDE_COS,
ItemTable.COLUMN_LONGITUDE_COS,
String.valueOf(coslng),
ItemTable.COLUMN_LONGITUDE_SIN,
String.valueOf(sinlng),
String.valueOf(sinlat),
ItemTable.COLUMN_LATITUDE_SIN,
String.valueOf(Math.cos(distanceInKilometers / 6371.0))
};
return new ContentInfo(null, where, whereClause);
}
}
I don't actually see the problem, but I re-engineered the selection/where so it's easier to read. And now it works. You can also checkout this fiddle.
public static String buildDistanceWhereClause(double latitude, double longitude, double distanceInKilometers) {
// see: http://stackoverflow.com/questions/3126830/query-to-get-records-based-on-radius-in-sqlite
final double coslat = Math.cos(Math.toRadians(latitude));
final double sinlat = Math.sin(Math.toRadians(latitude));
final double coslng = Math.cos(Math.toRadians(longitude));
final double sinlng = Math.sin(Math.toRadians(longitude));
final String format = "(%1$s * %2$s * (%3$s * %4$s + %5$s * %6$s) + %7$s * %8$s) > %9$s";
final String selection = String.format(format,
coslat, COLUMN_LATITUDE_COS,
coslng, COLUMN_LONGITUDE_COS,
sinlng, COLUMN_LONGITUDE_SIN,
sinlat, COLUMN_LATITUDE_SIN,
Math.cos(distanceInKilometers / 6371.0)
);
Log.d(TAG, selection);
return selection;
}

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;
}
}

Ordered List in XML in Android?

I am trying to make an ordered list from XML in a textview. This list would be bulleted and properly justified with subheadings. Unfortunately, it seems that the support for this in the xml is minimal. I have tried the following in strings.xml:
<ol>
<li> item 1\n
<li>sub-item1\n</li>
<li>sub-item2\n</li>
<li>item2\n</li>
<li>item3</li>
</ol>
with various permutations having ol around each item etc etc. The result typically shows subitem2 and item 2 being indented away from the bullet. I have been really scratching my head on this one. Any guidance on this would be great.
First, create a Custom Tag handler class:
package com.thecitybank.myca.ui;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.style.BulletSpan;
import android.text.style.LeadingMarginSpan;
import android.util.Log;
import org.xml.sax.XMLReader;
import java.util.Stack;
public class MyTagHandler implements Html.TagHandler {
private static final String OL_TAG = "ol";
private static final String UL_TAG = "ul";
private static final String LI_TAG = "li";
private static final int INDENT_PX = 10;
private static final int LIST_ITEM_INDENT_PX = INDENT_PX * 2;
private static final BulletSpan BULLET_SPAN = new BulletSpan(INDENT_PX);
private final Stack<ListTag> lists = new Stack<ListTag>();
#Override
public void handleTag(final boolean opening, final String tag, final Editable output, final XMLReader xmlReader) {
if (UL_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <ul>
lists.push(new Ul());
} else { // handle </ul>
lists.pop();
}
} else if (OL_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <ol>
lists.push(new Ol()); // use default start index of 1
} else { // handle </ol>
lists.pop();
}
} else if (LI_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <li>
lists.peek().openItem(output);
} else { // handle </li>
lists.peek().closeItem(output, lists.size());
}
} else {
Log.d("TagHandler", "Found an unsupported tag " + tag);
}
}
/**
* Abstract super class for {#link Ul} and {#link Ol}.
*/
private abstract static class ListTag {
/**
* Opens a new list item.
*
* #param text
*/
public void openItem(final Editable text) {
if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') {
text.append("\n");
}
final int len = text.length();
text.setSpan(this, len, len, Spanned.SPAN_MARK_MARK);
}
/**
* Closes a list item.
*
* #param text
* #param indentation
*/
public final void closeItem(final Editable text, final int indentation) {
if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') {
text.append("\n");
}
final Object[] replaces = getReplaces(text, indentation);
final int len = text.length();
final ListTag listTag = getLast(text);
final int where = text.getSpanStart(listTag);
text.removeSpan(listTag);
if (where != len) {
for (Object replace : replaces) {
text.setSpan(replace, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
protected abstract Object[] getReplaces(final Editable text, final int indentation);
/**
* Note: This knows that the last returned object from getSpans() will be the most recently added.
*
* #see Html
*/
private ListTag getLast(final Spanned text) {
final ListTag[] listTags = text.getSpans(0, text.length(), ListTag.class);
if (listTags.length == 0) {
return null;
}
return listTags[listTags.length - 1];
}
}
/**
* Class representing the unordered list ({#code <ul>}) HTML tag.
*/
private static class Ul extends ListTag {
#Override
protected Object[] getReplaces(final Editable text, final int indentation) {
// Nested BulletSpans increases distance between BULLET_SPAN and text, so we must prevent it.
int bulletMargin = INDENT_PX;
if (indentation > 1) {
bulletMargin = INDENT_PX - BULLET_SPAN.getLeadingMargin(true);
if (indentation > 2) {
// This get's more complicated when we add a LeadingMarginSpan into the same line:
// we have also counter it's effect to BulletSpan
bulletMargin -= (indentation - 2) * LIST_ITEM_INDENT_PX;
}
}
return new Object[]{
new LeadingMarginSpan.Standard(LIST_ITEM_INDENT_PX * (indentation - 1)),
new BulletSpan(bulletMargin)
};
}
}
/**
* Class representing the ordered list ({#code <ol>}) HTML tag.
*/
private static class Ol extends ListTag {
private int nextIdx;
/**
* Creates a new {#code <ul>} with start index of 1.
*/
public Ol() {
this(1); // default start index
}
/**
* Creates a new {#code <ul>} with given start index.
*
* #param startIdx
*/
public Ol(final int startIdx) {
this.nextIdx = startIdx;
}
#Override
public void openItem(final Editable text) {
super.openItem(text);
text.append(Integer.toString(nextIdx++)).append(". ");
}
#Override
protected Object[] getReplaces(final Editable text, final int indentation) {
int numberMargin = LIST_ITEM_INDENT_PX * (indentation - 1);
if (indentation > 2) {
// Same as in ordered lists: counter the effect of nested Spans
numberMargin -= (indentation - 2) * LIST_ITEM_INDENT_PX;
}
return new Object[]{new LeadingMarginSpan.Standard(numberMargin)};
}
}
}
Then add a string in your string.xml as done below:
<string name="change_password_note"><![CDATA[<ol><li>Your password should contain at least one character of a-z, A-Z and 0-9. No special character is allowed.</li> <li>Please do not use any of your last three passwords.</li> <li>Please do not enter your User ID as password.</li> <li>Password minimum of 8 and maximum of 20 characters.</li></ol>]]></string>
Lastly, set text into your TextView as below:
txtNotesDescription.setText(Html.fromHtml(getString(R.string.change_password_note),null,new MyTagHandler()));
This worked for me. You can use un-ordered list by using the (ul) tag.
<string name="accessibility_service_instructions">
1. Enable TalkBack (Settings -> Accessibility -> TalkBack).
\n\n2. Enable Explore-by-Touch (Settings -> Accessibility -> Explore by Touch).
\n\n3. Touch explore the Clock application and the home screen.
\n\n4. Go to the Clock application and change the time of an alarm.
\n\n5. Enable ClockBack (Settings -> Accessibility -> ClockBack).
\n\n6. Go to the Clock application and change an alarm.
\n\n7. Set the ringer to vibration mode and change an alarm.
\n\n8. Set the ringer to muted mode and change an alarm.
</string>

Android Linkify both web and #mentions all in the same TextView

Ok so I asked this yesterday:
AutoLink #mentions in a twitter client
I got my #mentions linking correctly. But in order to get it to work I had to take android:autoLink="web" out my xml for the TextView. So now I get links to #mentions but it no longer links URLs. I tried doing two seperate Linkify.addLinks() calls like this:
mentionFilter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return match.group(1);
}
};
// Match #mentions and capture just the username portion of the text.
//pattern = Pattern.compile("#([A-Za-z0-9_-]+)");
pattern = Pattern.compile("(#[a-zA-Z0-9_]+)");
scheme = "http://twitter.com/";
tweetTxt = (TextView) v.findViewById(R.id.tweetTxt);
Linkify.addLinks(tweetTxt, pattern, scheme, null, mentionFilter);
Linkify.addLinks(tweetTxt, Linkify.WEB_URLS);
But which ever gets called last is the one that gets applied. Can anyone tell me how I can make it link both the #mentions and still autoLink the URLs?
Edited to clarify some more of the code.
Here's my code to linkify all Twitter links (mentions, hashtags and URLs):
TextView tweet = (TextView) findViewById(R.id.tweet);
TransformFilter filter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return match.group();
}
};
Pattern mentionPattern = Pattern.compile("#([A-Za-z0-9_-]+)");
String mentionScheme = "http://www.twitter.com/";
Linkify.addLinks(tweet, mentionPattern, mentionScheme, null, filter);
Pattern hashtagPattern = Pattern.compile("#([A-Za-z0-9_-]+)");
String hashtagScheme = "http://www.twitter.com/search/";
Linkify.addLinks(tweet, hashtagPattern, hashtagScheme, null, filter);
Pattern urlPattern = Patterns.WEB_URL;
Linkify.addLinks(tweet, urlPattern, null, null, filter);
I had to Linkify.ALL before Linkify-ing the # mentions for it to work.
Also, do not use 'android:autoLink' in the TextView in your XML layout file
TextView textView = (TextView) findViewById(R.id.tweet);
Pattern atMentionPattern = Pattern.compile("#([A-Za-z0-9_]+)");
String atMentionScheme = "http://twitter.com/";
TransformFilter transformFilter = new TransformFilter() {
//skip the first character to filter out '#'
public String transformUrl(final Matcher match, String url) {
return match.group(1);
}
};
Linkify.addLinks(textView, Linkify.ALL);
Linkify.addLinks(textView, atMentionPattern, atMentionScheme, null, transformFilter);
My TextView looks like this:
<TextView
android:id="#+id/tweet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColorLink="#449def"/>
Ok finally got some time to properly put in the #mention and #hashtags to a Linkify class. Instead of just overriding some of the other types of links to get it working.
This class works just like the normal Linkify, but also can do those two things.
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.use.your.own.package;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.URLSpan;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.webkit.WebView;
import android.widget.TextView;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Linkify take a piece of text and a regular expression and turns all of the
* regex matches in the text into clickable links. This is particularly
* useful for matching things like email addresses, web urls, etc. and making
* them actionable.
*
* Alone with the pattern that is to be matched, a url scheme prefix is also
* required. Any pattern match that does not begin with the supplied scheme
* will have the scheme prepended to the matched text when the clickable url
* is created. For instance, if you are matching web urls you would supply
* the scheme <code>http://</code>. If the pattern matches example.com, which
* does not have a url scheme prefix, the supplied scheme will be prepended to
* create <code>http://example.com</code> when the clickable url link is
* created.
*/
public class LinkifyWithTwitter {
/**
* Bit field indicating that web URLs should be matched in methods that
* take an options mask
*/
public static final int WEB_URLS = 0x01;
/**
* Bit field indicating that email addresses should be matched in methods
* that take an options mask
*/
public static final int EMAIL_ADDRESSES = 0x02;
/**
* Bit field indicating that phone numbers should be matched in methods that
* take an options mask
*/
public static final int PHONE_NUMBERS = 0x04;
/**
* Bit field indicating that twitter #mentions should be matched in methods that
* take an options mask
*/
public static final int AT_MENTIONS = 0x05;
/**
* Bit field indicating that #hash-tags should be matched in methods that
* take an options mask
*/
public static final int HASH_TAGS = 0x06;
/**
* Bit field indicating that street addresses should be matched in methods that
* take an options mask
*/
public static final int MAP_ADDRESSES = 0x08;
/**
* Bit mask indicating that all available patterns should be matched in
* methods that take an options mask
*/
public static final int ALL = WEB_URLS | EMAIL_ADDRESSES | PHONE_NUMBERS | AT_MENTIONS| HASH_TAGS |MAP_ADDRESSES;
/**
* Don't treat anything with fewer than this many digits as a
* phone number.
*/
private static final int PHONE_NUMBER_MINIMUM_DIGITS = 5;
/**
* Filters out web URL matches that occur after an at-sign (#). This is
* to prevent turning the domain name in an email address into a web link.
*/
public static final MatchFilter sUrlMatchFilter = new MatchFilter() {
public final boolean acceptMatch(CharSequence s, int start, int end) {
if (start == 0) {
return true;
}
if (s.charAt(start - 1) == '#') {
return false;
}
return true;
}
};
/**
* Filters out URL matches that don't have enough digits to be a
* phone number.
*/
public static final MatchFilter sPhoneNumberMatchFilter = new MatchFilter() {
public final boolean acceptMatch(CharSequence s, int start, int end) {
int digitCount = 0;
for (int i = start; i < end; i++) {
if (Character.isDigit(s.charAt(i))) {
digitCount++;
if (digitCount >= PHONE_NUMBER_MINIMUM_DIGITS) {
return true;
}
}
}
return false;
}
};
/**
* Transforms matched phone number text into something suitable
* to be used in a tel: URL. It does this by removing everything
* but the digits and plus signs. For instance:
* &apos;+1 (919) 555-1212&apos;
* becomes &apos;+19195551212&apos;
*/
public static final TransformFilter sPhoneNumberTransformFilter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return Regex.digitsAndPlusOnly(match);
}
};
/**
* MatchFilter enables client code to have more control over
* what is allowed to match and become a link, and what is not.
*
* For example: when matching web urls you would like things like
* http://www.example.com to match, as well as just example.com itelf.
* However, you would not want to match against the domain in
* support#example.com. So, when matching against a web url pattern you
* might also include a MatchFilter that disallows the match if it is
* immediately preceded by an at-sign (#).
*/
public interface MatchFilter {
/**
* Examines the character span matched by the pattern and determines
* if the match should be turned into an actionable link.
*
* #param s The body of text against which the pattern
* was matched
* #param start The index of the first character in s that was
* matched by the pattern - inclusive
* #param end The index of the last character in s that was
* matched - exclusive
*
* #return Whether this match should be turned into a link
*/
boolean acceptMatch(CharSequence s, int start, int end);
}
/**
* TransformFilter enables client code to have more control over
* how matched patterns are represented as URLs.
*
* For example: when converting a phone number such as (919) 555-1212
* into a tel: URL the parentheses, white space, and hyphen need to be
* removed to produce tel:9195551212.
*/
public interface TransformFilter {
/**
* Examines the matched text and either passes it through or uses the
* data in the Matcher state to produce a replacement.
*
* #param match The regex matcher state that found this URL text
* #param url The text that was matched
*
* #return The transformed form of the URL
*/
String transformUrl(final Matcher match, String url);
}
/**
* Scans the text of the provided Spannable and turns all occurrences
* of the link types indicated in the mask into clickable links.
* If the mask is nonzero, it also removes any existing URLSpans
* attached to the Spannable, to avoid problems if you call it
* repeatedly on the same text.
*/
public static final boolean addLinks(Spannable text, int mask) {
if (mask == 0) {
return false;
}
URLSpan[] old = text.getSpans(0, text.length(), URLSpan.class);
for (int i = old.length - 1; i >= 0; i--) {
text.removeSpan(old[i]);
}
ArrayList<LinkSpec> links = new ArrayList<LinkSpec>();
if ((mask & WEB_URLS) != 0) {
gatherLinks(links, text, Regex.WEB_URL_PATTERN,
new String[] { "http://", "https://" },
sUrlMatchFilter, null);
}
if ((mask & EMAIL_ADDRESSES) != 0) {
gatherLinks(links, text, Regex.EMAIL_ADDRESS_PATTERN,
new String[] { "mailto:" },
null, null);
}
if ((mask & PHONE_NUMBERS) != 0) {
gatherLinks(links, text, Regex.PHONE_PATTERN,
new String[] { "tel:" },
sPhoneNumberMatchFilter, sPhoneNumberTransformFilter);
}
if((mask & AT_MENTIONS) != 0){
gatherLinks(links, text, Pattern.compile("#([A-Za-z0-9_-]+)"),
new String[] { "http://www.twitter.com/" },
null, null);
}
if((mask & HASH_TAGS) != 0){
TransformFilter hashTagFilter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return match.group(0).replaceAll("#", "%23");
}
};
gatherLinks(links, text, Pattern.compile("#([A-Za-z0-9_-]+)"),
new String[] { "http://twitter.com/#!/search/" },
null,hashTagFilter);
}
if ((mask & MAP_ADDRESSES) != 0) {
gatherMapLinks(links, text);
}
pruneOverlaps(links);
if (links.size() == 0) {
return false;
}
for (LinkSpec link: links) {
applyLink(link.url, link.start, link.end, text);
}
return true;
}
/**
* Scans the text of the provided TextView and turns all occurrences of
* the link types indicated in the mask into clickable links. If matches
* are found the movement method for the TextView is set to
* LinkMovementMethod.
*/
public static final boolean addLinks(TextView text, int mask) {
if (mask == 0) {
return false;
}
CharSequence t = text.getText();
if (t instanceof Spannable) {
if (addLinks((Spannable) t, mask)) {
addLinkMovementMethod(text);
return true;
}
return false;
} else {
SpannableString s = SpannableString.valueOf(t);
if (addLinks(s, mask)) {
addLinkMovementMethod(text);
text.setText(s);
return true;
}
return false;
}
}
private static final void addLinkMovementMethod(TextView t) {
MovementMethod m = t.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (t.getLinksClickable()) {
t.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
/**
* Applies a regex to the text of a TextView turning the matches into
* links. If links are found then UrlSpans are applied to the link
* text match areas, and the movement method for the text is changed
* to LinkMovementMethod.
*
* #param text TextView whose text is to be marked-up with links
* #param pattern Regex pattern to be used for finding links
* #param scheme Url scheme string (eg <code>http://</code> to be
* prepended to the url of links that do not have
* a scheme specified in the link text
*/
public static final void addLinks(TextView text, Pattern pattern, String scheme) {
addLinks(text, pattern, scheme, null, null);
}
/**
* Applies a regex to the text of a TextView turning the matches into
* links. If links are found then UrlSpans are applied to the link
* text match areas, and the movement method for the text is changed
* to LinkMovementMethod.
*
* #param text TextView whose text is to be marked-up with links
* #param p Regex pattern to be used for finding links
* #param scheme Url scheme string (eg <code>http://</code> to be
* prepended to the url of links that do not have
* a scheme specified in the link text
* #param matchFilter The filter that is used to allow the client code
* additional control over which pattern matches are
* to be converted into links.
*/
public static final void addLinks(TextView text, Pattern p, String scheme,
MatchFilter matchFilter, TransformFilter transformFilter) {
SpannableString s = SpannableString.valueOf(text.getText());
if (addLinks(s, p, scheme, matchFilter, transformFilter)) {
text.setText(s);
addLinkMovementMethod(text);
}
}
/**
* Applies a regex to a Spannable turning the matches into
* links.
*
* #param text Spannable whose text is to be marked-up with
* links
* #param pattern Regex pattern to be used for finding links
* #param scheme Url scheme string (eg <code>http://</code> to be
* prepended to the url of links that do not have
* a scheme specified in the link text
*/
public static final boolean addLinks(Spannable text, Pattern pattern, String scheme) {
return addLinks(text, pattern, scheme, null, null);
}
/**
* Applies a regex to a Spannable turning the matches into
* links.
*
* #param s Spannable whose text is to be marked-up with
* links
* #param p Regex pattern to be used for finding links
* #param scheme Url scheme string (eg <code>http://</code> to be
* prepended to the url of links that do not have
* a scheme specified in the link text
* #param matchFilter The filter that is used to allow the client code
* additional control over which pattern matches are
* to be converted into links.
*/
public static final boolean addLinks(Spannable s, Pattern p,
String scheme, MatchFilter matchFilter,
TransformFilter transformFilter) {
boolean hasMatches = false;
String prefix = (scheme == null) ? "" : scheme.toLowerCase();
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
boolean allowed = true;
if (matchFilter != null) {
allowed = matchFilter.acceptMatch(s, start, end);
}
if (allowed) {
String url = makeUrl(m.group(0), new String[] { prefix },
m, transformFilter);
applyLink(url, start, end, s);
hasMatches = true;
}
}
return hasMatches;
}
private static final void applyLink(String url, int start, int end, Spannable text) {
URLSpan span = new URLSpan(url);
text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private static final String makeUrl(String url, String[] prefixes,
Matcher m, TransformFilter filter) {
if (filter != null) {
url = filter.transformUrl(m, url);
}
boolean hasPrefix = false;
for (int i = 0; i < prefixes.length; i++) {
if (url.regionMatches(true, 0, prefixes[i], 0,
prefixes[i].length())) {
hasPrefix = true;
// Fix capitalization if necessary
if (!url.regionMatches(false, 0, prefixes[i], 0,
prefixes[i].length())) {
url = prefixes[i] + url.substring(prefixes[i].length());
}
break;
}
}
if (!hasPrefix) {
url = prefixes[0] + url;
}
return url;
}
private static final void gatherLinks(ArrayList<LinkSpec> links,
Spannable s, Pattern pattern, String[] schemes,
MatchFilter matchFilter, TransformFilter transformFilter) {
Matcher m = pattern.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
if (matchFilter == null || matchFilter.acceptMatch(s, start, end)) {
LinkSpec spec = new LinkSpec();
String url = makeUrl(m.group(0), schemes, m, transformFilter);
spec.url = url;
spec.start = start;
spec.end = end;
links.add(spec);
}
}
}
private static final void gatherMapLinks(ArrayList<LinkSpec> links, Spannable s) {
String string = s.toString();
String address;
int base = 0;
while ((address = WebView.findAddress(string)) != null) {
int start = string.indexOf(address);
if (start < 0) {
break;
}
LinkSpec spec = new LinkSpec();
int length = address.length();
int end = start + length;
spec.start = base + start;
spec.end = base + end;
string = string.substring(end);
base += end;
String encodedAddress = null;
try {
encodedAddress = URLEncoder.encode(address,"UTF-8");
} catch (UnsupportedEncodingException e) {
continue;
}
spec.url = "geo:0,0?q=" + encodedAddress;
links.add(spec);
}
}
private static final void pruneOverlaps(ArrayList<LinkSpec> links) {
Comparator<LinkSpec> c = new Comparator<LinkSpec>() {
public final int compare(LinkSpec a, LinkSpec b) {
if (a.start < b.start) {
return -1;
}
if (a.start > b.start) {
return 1;
}
if (a.end < b.end) {
return 1;
}
if (a.end > b.end) {
return -1;
}
return 0;
}
public final boolean equals(Object o) {
return false;
}
};
Collections.sort(links, c);
int len = links.size();
int i = 0;
while (i < len - 1) {
LinkSpec a = links.get(i);
LinkSpec b = links.get(i + 1);
int remove = -1;
if ((a.start <= b.start) && (a.end > b.start)) {
if (b.end <= a.end) {
remove = i + 1;
} else if ((a.end - a.start) > (b.end - b.start)) {
remove = i + 1;
} else if ((a.end - a.start) < (b.end - b.start)) {
remove = i;
}
if (remove != -1) {
links.remove(remove);
len--;
continue;
}
}
i++;
}
}
}
class LinkSpec {
String url;
int start;
int end;
}
I figured out a way to make this work. It is a little bit hacky but it got the job done. If anyone knows of a more appropriate way to do this please do let me know.
To get it working I made myself a copy of the Linkify class and edited the part that handles the linkifying for phone numbers to do #mention links instead.
Here is where I found my copy of the linkify class
I changed this:
if ((mask & PHONE_NUMBERS) != 0) {
gatherLinks(links, text, Regex.PHONE_PATTERN,
new String[] { "tel:" },
sPhoneNumberMatchFilter, sPhoneNumberTransformFilter);
}
into this:
if ((mask & PHONE_NUMBERS) != 0) {
gatherLinks(links, text, Pattern.compile("#([A-Za-z0-9_-]+)"),
new String[] { "http://www.twitter.com/" },
null, null);
}
I called this class MyLinkify and used this code in my Activity to apply the links.
MyLinkify.addLinks(tweetTxt, Linkify.ALL);
To get the MyLinkify class to build I also had to add a copy of the Regex class into my project, here is where I found Regex.java
Im putting this as an answer incase anyone else looking for this effect finds this thread. I realized this is probably not the best way to go about getting this to work. If anyone knows a better way to get it working please add it here and I'll select it is the actual answer to this question.
use below code:
TextView textView = (TextView) findViewById(R.id.hello);
String str = "#aman_vivek how are u #aman_vivek <http://www.google.com> <http://www.tekritisoftware.com>";
textView.setText(str);
Pattern wikiWordMatcher = Pattern.compile("(#[a-zA-Z0-9_]+)");
String wikiViewURL = "http://www.twitter.com/";
Linkify.addLinks(textView, wikiWordMatcher, wikiViewURL);
Pattern wikiWordMatcher1 = Pattern.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]");
Linkify.addLinks(textView, wikiWordMatcher1, null);
Is tweetTxt the input String that you are linkifying or a handle to the TextView object?
If its the input string, then you are just overwriting the TextView with the output of the final call to addLinks. Given your observation, I'm guessing this is the case.
You need to pass the TextView to addLinks in both cases. Internally, Linkify will pluck the Spanned buffer from the TextView and use that, such that multiple calls to addLinks are cumulative. The WikiNotes example passes the TextView and so should you: http://developer.android.com/resources/articles/wikinotes-linkify.html

Categories

Resources