twitter linkify android all #mentions - java

I want to give a link all twitter #mentions on mytweets app in android. If I click on #mentions I want to open another page about of the #mentions.
This code do not work. Firstly I want to search #mentions in tweet and I give link this #mentions and if I click this #mentions in tweet I want to open another page about of the this #mentions.
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
Pattern atMentionPattern = Pattern.compile("#([A-Za-z0-9_]+)");
String atMentionScheme = "http://twitter.com/";
TransformFilter transformFilter = new TransformFilter() {
public String transformUrl(final Matcher match, String url) {
return match.group(1);
}
};
Linkify.addLinks(bt, Linkify.ALL);
Linkify.addLinks(bt, atMentionPattern, atMentionScheme, null, transformFilter);

try like this
textView.setAutoLinkMask(0);
// Recognize phone numbers and web URLs
Linkify.addLinks(text, Linkify.PHONE_NUMBERS | Linkify.WEB_URLS);
// Recognize all of the default link text patterns
Linkify.addLinks(text, Linkify.ALL);
// Disable all default link detection
Linkify.addLinks(text, 0);
see here is documentation
http://polamreddyn.blogspot.in/2013/01/android-text-links-using-linkify.html

Related

Make link inside of string clickable: Java

I am creating a messaging system in Java using android studio.
People can send messages back and forth. But if they send a link, it just shows up as regular text. I want the part that is the link to show up as a clickable link and the rest just text.
I checked all day on this site and others but no seems to do this in the way I'm trying too. Most of the answers I see are people using a TexView to accomplish their goal. I'm using a string. Can someone please help me figure this out ?
private void showMessages(){
DatabaseReference userMessageKeyRef = RootRef.child("Messages").child(messageSenderID).child(messageReceiverID);
userMessageKeyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
Messages messages = new Messages();
String strMessage = snapshot1.child("message").getValue().toString();
String strFrom = snapshot1.child("from").getValue().toString();
String strType = snapshot1.child("type").getValue().toString();
messages.setMessage(strMessage);
messages.setFrom(strFrom);
messages.setType(strType);
messagesList.add(messages);
// Pattern for recognizing a URL, based off RFC 3986
final Pattern urlPattern = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~#!:/{};']*)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
// separate input by spaces ( URLs don't have spaces )
String [] parts = strMessage.split("\\s+");
// get every part
for( String item : parts ) {
if(urlPattern.matcher(item).matches()) {
//it's a good url
System.out.print(""+ item + " " );
} else {
// it isn't a url
System.out.print(item + " ");
}
}
}
messageAdapter = new MessageAdapter(ChatActivity.this,messagesList);
userMessagesList.setAdapter(messageAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
There are two common ways to do this. One, like you have done, is to add html to the string. The second is to use the TextView's auto link mask feature.
Using HTML
Once you have identified URLs in your incoming string and added the appropriate html tags to turn them into links, you just need to use HtmlCompat when you go to actually display it in the TextView. You also need to make sure to call setMovementMethod or you won't be able to click the link. The advantage of using HTML is that you can have the link text be a readable phrase instead of a URL.
String txt = "This is www.google.com";
TextView link = findViewById(R.id.link);
link.setMovementMethod(LinkMovementMethod.getInstance());
link.setText(HtmlCompat.fromHtml(txt,HtmlCompat.FROM_HTML_MODE_LEGACY));
If you choose to go this route, your existing code just needs to be modified a bit to save the HTML string in the messages list passed to the adapter, then add the TextView calls above inside the adapter when you set the text.
String [] parts = strMessage.split("\\s+");
// replace URL parts with html links
for( int i = 0; i < parts.length; ++i ) {
if(urlPattern.matcher(parts[i]).matches()) {
parts[i] = "" + parts[i] + "";
}
}
// re-join parts back into a single string
String htmlMessage = String.join(" ", parts);
// save a list of html strings to pass to your adapter
htmlMessageStrings.add(htmlMessage);
Using Link Mask
This method doesn't require you to edit the string at all. If you use Linkify.ALL it also recognizes things like web links, emails, phone numbers, and physical addresses - not just web links. If you only want it to recognize web links use Linkify.WEB_URLS instead. This requires a lot less code on your part - you no longer have to try to parse the string for links.
String txt = "This is www.google.com"; // no need to modify the string
TextView link = findViewById(R.id.link);
link.setAutoLinkMask(Linkify.ALL); // or Linkify.WEB_URLS
link.setText(txt);
You can also add android:autoLink="all" to the TextView XML definition instead of calling it in-code.
Both methods produce this output

How to build a short Dynamic Link with a Desktop Fallback URL on Android?

I have implemented deep link in my Android App to share content. The problem is on Android I can't find a way to set a Fallback URL when the user open the short link on his desktop.
With the Firebase DynamicLink.Builder I can set iOS fallback URL because my app doesn't exist on iOS but I can't find a way to set the dfl parameters in my link.
Which lead the user to an error page like this :
Here how I build my short dynamic link:
//link example : https://app.example.com/details/ebLvAV9fi9S7Pab0qR3a
String link = domainUri + "/details/" + object.getUid();
FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse(link))
.setDomainUriPrefix(domainUri)
.setAndroidParameters(new DynamicLink.AndroidParameters.Builder().setMinimumVersion(1).build())
// Fallback Url for iOS
.setIosParameters(new DynamicLink.IosParameters.Builder("").setFallbackUrl(Uri.parse(RMP_WEB_BASE_URL)).build())
.setSocialMetaTagParameters(
new DynamicLink.SocialMetaTagParameters.Builder()
.setTitle(title)
.setDescription(description)
.setImageUrl(Uri.parse(imageUrl))
.build())
.buildShortDynamicLink()
.addOnCompleteListener(new OnCompleteListener<ShortDynamicLink>() {
#Override
public void onComplete(#NonNull Task<ShortDynamicLink> task) {
if (task.isSuccessful() && task.getResult() != null) {
shortLink = task.getResult().getShortLink();
//Create Shareable Intent
//...
}
}
});
I have read that I need to specify a Desktop Fallback URL like the iOS one but DynamicLink.Builder doesn't seems to include one.
I would like to redirect my user to the home page https://example.com when they open the link from a non-android device.
I have tried to use setLongLink(longLink) in the DynamicLink.Builder with the parameters ?dfl=https://example.com but it doesn't seems to work and it even break my dynamic link on android.
This is a Swift solution but may be helpful to others-
Unfortunately, there is currently no built-in method to handle this programmatically through the Firebase url editor. You must manually add an 'ofl' parameter to the link. The easiest way to do this:
// Grab link from Firebase builder
guard var longDynamicLink = shareLink.url else { return }
// Parse URL to string
var urlStr = longDynamicLink.absoluteString
// Append the ofl fallback (ofl param specifies a device other than ios or android)
urlStr = urlStr + "&ofl=https://www.google.com/"
// Convert back to a URL
var urlFinal = URL(string: urlStr)!
// Shorten the url & check for errors
DynamicLinkComponents.shortenURL(urlFinal, options: nil, completion:{ [weak self] url,warnings,error in
if let _ = error{
return
}
if let warnings = warnings{
for warning in warnings{
print("Shorten URL warnings: ", warning)
}
}
guard let shortUrl = url else {return}
// prompt the user with UIActivityViewController
self?.showShareSheet(url: shortUrl)
})
The final URL can then be used to present the shareable panel with another function like:
self.showShareSheet(url: finalUrl) which triggers the UIActivityViewController
Credit to http://ostack.cn/?qa=168161/ for the original idea
More about ofl: https://firebase.google.com/docs/dynamic-links/create-manually?authuser=3#general-params

How can I autolink #mentions in my adapter itemview?

I'm using Linkify to search for strings that come after the #symbol. Why don't they turn into links in my TextView? Do I have to set something else in the XML like android:linksClickable="true"?
feedItemView.messageText.setText(message.getString("messageText"));
Pattern userMatcher = Pattern.compile("\\B#[^:\\s]+");
String userViewURL = ".activity.UserProfileActivity://";
Linkify.addLinks(feedItemView.messageText, userMatcher, userViewURL);
I used the following code:
feedItemView.messageText.setText(yeet.getString(ParseConstants.KEY_NOTIFICATION_TEXT));
Linkify.TransformFilter filter = (match, url) -> match.group();
Pattern mentionPattern = Pattern.compile("#([A-Za-z0-9_-]+)");
String mentionScheme = "http://www.twitter.com/";
Linkify.addLinks(feedItemView.messageText, mentionPattern, mentionScheme, null, filter);
I also made sure to remove android:autoLink="all" from that TextView's XML. This will remove auto link functionality for web links so then you'd want to add this to method that handles displaying that TextView:
Pattern urlPattern = Patterns.WEB_URL;
Linkify.addLinks(tweet, urlPattern, null, null, filter);

Android: TextView with url end with -/\n Linkify wrongly

Currently, I have a String like
http://www.example.com/defg-/\nletters
I put this String into a TextView, and make the url clickable by setAutoLinkMask(Linkify.WEB_URLS) and setMovementMethod(LinkMovementMethod.getInstance())
However, the link is recognize wrongly, where only
http://www.example.com/defg   <--missing "-/"
is highlighted but not
http://www.example.com/defg-/  <--I want this
, and results in a wrong url.
What should I do such that the url can be recognized correctly?
The Sample Result (2nd link is wrongly recognized)
Code Implementation
txtNorm = (TextView) findViewById(R.id.txtNorm);
txtNorm.setText("http://www.example.com/defg-/");
txtNorm.setAutoLinkMask(Linkify.WEB_URLS);
txtNorm.setMovementMethod(LinkMovementMethod.getInstance());
txtCustom = (TextView) findViewById(R.id.txtCustom);
txtCustom.setText("http://www.example.com/defg-/\nletters");
txtCustom.setAutoLinkMask(Linkify.WEB_URLS);
txtCustom.setMovementMethod(LinkMovementMethod.getInstance());
i found a way you can try this.. at first you need to know that if you add -/ at the end of url this is not common format of standard Web Url. so i made a custom pattern ..
String urlRegex="[://.a-zA-Z_-]+-/"; // carefully set your pattern.
Pattern pattern = Pattern.compile(urlRegex);
String url1="press http://www.example.com/defg-/\\ or on Android& to search it on google";
text.setText(url1);
Matcher matcher1=Pattern.compile(urlRegex).matcher(url1);
while (matcher1.find()) {
final String tag = matcher1.group(0);
Linkify.addLinks(text, pattern, tag);
}
text.setMovementMethod(LinkMovementMethod.getInstance());

How to get a photo with a certain title from Picasa using the Java API

Does anybody know how to get a photo from Picasa by its title without knowing the album it belongs to? I'm already authenticated.
I suppose you can do something like this:-
URL baseSearchUrl = new URL("yourPicasaURL");
Query myQuery = new Query(baseSearchUrl);
myQuery.setStringCustomParameter("kind", "photo");
myQuery.setMaxResults(10);
myQuery.setFullTextQuery("hello"); // search photo that has the word "hello"
AlbumFeed searchResultsFeed = myService.query(myQuery, AlbumFeed.class);
for (PhotoEntry photo : searchResultsFeed.getPhotoEntries()) {
System.out.println(photo.getTitle().getPlainText());
}

Categories