get url from String in android - android

Currently I am using the following method to get a URL from a string and insert into a TextView. It works fine, but does see anybody any issues with this approach?
public String StringURL(String args) {
String s = args;
String [] parts = s.split("\\s");
String withURL = "";
for( String item : parts ){
if (Patterns.WEB_URL.matcher(item).matches()) {
if (!item.startsWith("http://") && !item.startsWith("https://")){
item = "http://" + item;
}
withURL += ""+ item + " ";
}
else {
withURL += item + " ";
}
}
return withURL;
}
In the TextView I set the returned String the following way:
TextView.setText(Html.fromHtml(StringURL(P)));
TextView.setMovementMethod(LinkMovementMethod.getInstance());
This method works only for SdkVersions 8+ since Patterns.WEB_URL was introduced as of SdkVersion 8.

Related

in email mutipart message body (with attachment) is comming as plain text instead html format

I am writing an email client android app. In it, I am using JavaMail. While reading emails from server everything is coming properly except for a few mails which have attachments. In those cases the email body is coming as plain text instead of HTML format.
My code is as follows:
String str; //=bodyPart.toString();//(bodyPart.getContent());
if (bodyPart instanceof Part) {
if (bodyPart.getContent() instanceof String) {
str = bodyPart.getContent().toString();
}
else {
MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent();
str = getTextFromMimeMultipart(mimeMultipart);
}
}
else
str = bodyPart.getContent().toString();
//
//*****************************
//
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
String result = "";
int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result = result + "\n" + bodyPart.getContent();
break; // without break same text appears twice in my tests
}
else if (bodyPart.isMimeType("text/html")) {
String html = (String) bodyPart.getContent();
result = result + "\n" + Jsoup.parse(html).text();//html;// + org.Jsoup.parse(html).text();
}
else if (bodyPart.getContent() instanceof MimeMultipart) {
result = result + getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
}
}
return result;
}

Problems splitting string at first empty space

I have a string which i need to split at the first empty space.
Somehow I can not get it to split, the string stays untouched.
Could somebody help?
String in question:
https://test.com/info/dsfs76/933/TT Maps 2015.12
https://test.com/info/dsfs76/933/TT and Maps 2015.12 need to be 2 seperate parts which are added to an arraylist.
My code attempt:
if (str.contains(linkElem.getLinkAddress() + " ")) {
String[] temp = str.split(" ");
for (String temp : Arrays.asList(temp)) {
arraytest.add(temp);
}
}
From the code you provided, there is no such String strtemp
Maybe you should be splitting str instead?
String[] temp = str.split(" ");
You can use String tokenizer to do that like this:
StringTokenizer st = new StringTokenizer(linkElem.getLinkAddress(), " ");
String a = st.nextToken();//string before " "
String b = st.nextToken();//string after " "
i know it is completely unelegant and dumb but it works %)
String string = "https://test.com/info/dsfs76/933/TT Maps 2015.12";
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> list = new ArrayList<>();
boolean whiteSpaceFound = false;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == ' ' && !whiteSpaceFound) {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
whiteSpaceFound = true;
} else {
stringBuilder.append(string.charAt(i));
}
}
if (whiteSpaceFound || list.isEmpty()) {
list.add(stringBuilder.toString());
}

Android: android:autoLink=“web” does not support query parameters after domains

I have a TextView with autoLink set as
<TextView
android:id="#+id/messageDetail_privateText_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web|phone|email" />
But when I set a text with an url like http://www.test.com?p1=v1&p2=v2 the TextView's autolink doesn't recognize the query parameters after the domain.
I can understand that this kind of URL's doesn't have too much sense, but is there any workaround to this problem?
iOS is recognizing the parameters just fine.
Answering to my own question, what finally worked for me was to check the urls of the string and adding the slash manually. Not the coolest solution in the world but worked in this case.
Below the code:
protected String normalizeURLs(String html)
{
String[] pieces = html.split(" ");
ArrayList<String> textParts = new ArrayList<>();
for(String piece : pieces) {
try {
URL isURL = new URL(piece);
String protocol = isURL.getProtocol();
String host = isURL.getHost();
String query = isURL.getQuery();
String path = isURL.getPath();
String questionMark = "?";
if (path.equals("")) {
path = "/";
}
if (query == null) {
query = "";
questionMark = "";
}
String url = protocol + "://" + host + path + questionMark + query;
textParts.add(url);
} catch (MalformedURLException exception) {
textParts.add(piece);
}
}
String resultString = "";
for (String s : textParts)
{
resultString += s + " ";
}
return resultString;
}

How to sort a list of array from a-z?

I am trying to sort a list of array based on the name in alphabetical order which contain type, name, url and date. I retrieved the information from Browser.BookmarkColumns except for type.
Before:
Default Browser Google www.Google.com 14/12/2013
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Amazon www.Amazon.com 11/11/2014
After:
Default Browser Amazon www.Amazon.com 11/11/2014
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Google www.Google.com 14/12/2013
Here is what i have tried but it is not working.
int j = mCur.getCount();
String[] mType = new String[j];
String[] mTitles = new String[j];
String[] murls = new String[j];
long[] date = new long[j];
for (int q=0; q<(j-1); q++) {
String a = (mTitles[q]).toLowerCase();
String b = (mTitles[q+1].toLowerCase());
char[] c = a.toCharArray();
char[] d = b.toCharArray();
String temp, temp2, temp3 = null;
long temp4 = 0;
int lenc = c.length;
int lend = d.length;
int min =0;
int count =0;
if (lenc < lend)
min = lenc;
else
min = lend;
if (c[count] > d[count]) {
temp = mTitles[count];
temp2 = mType[count];
temp3 = murls[count];
temp4 = date[count];
mTitles[count] = mTitles[count + 1];
mType[count] = mType[count + 1];
murls[count] = murls[count + 1];
date[count] = date[count + 1];
mTitles[count + 1] = temp;
mType[count + 1] = temp2;
murls[count + 1] = temp3;
date[count + 1] = temp4;
} else if (c[count] == d[count]) {
for (int w = 1; w < min; w++) {
if (c[w] > d[w]) {
temp = mTitles[w];
temp2 = mType[w];
temp3 = murls[w];
temp4 = date[w];
mTitles[w] = mTitles[w + 1];
mType[w] = mType[w + 1];
murls[w] = murls[w + 1];
date[w] = date[w + 1];
mTitles[w + 1] = temp;
mType[w + 1] = temp2;
murls[w + 1] = temp3;
date[w + 1] = temp4;
}
}
}
}
Above answers are giving best example for efficient sorting Array list in java.
Before it please read description of above mentioned answer here
I just simplified above answer for your better understanding it gives exact output what u required.
ArrayList<UserContainer> userList = new ArrayList<>();
userList.add(new UserContainer("www.Google.com", "Google", "14/12/2013"));
userList.add(new UserContainer("www.BBC.com", "BBC", "13/12/2015"));
userList.add(new UserContainer("www.Amazon.com", "Amazon", "11/11/2014"));
Log.i("Before Sorting :", "==========================>>");
for (UserContainer obj : userList) {
System.out.println("Default Browser: \t" + obj.name + "\t" + obj.date + "\t" + obj.webSite);
}
Collections.sort(userList, new Comparator<UserContainer>() {
#Override
public int compare(UserContainer first, UserContainer second) {
return first.name.compareToIgnoreCase(second.name);
}
});
Log.i("After Sorting :", "==========================>>");
for (UserContainer obj : userList) {
System.out.println("Default Browser: \t" + obj.name + "\t" + obj.date + "\t" + obj.webSite);
}
Model Class:
public class UserContainer {
public UserContainer(String webSite, String name, String date) {
this.webSite = webSite;
this.name = name;
this.date = date;
}
public String webSite = "";
public String name = "";
public String date = "";
}
First of all it would be much simplier task if instead of sorting 3 string arrays + long array You encapsulate all the fields and create a class (lets call it MyData) containing all four fields. Then you can use put all newly create objects in some collection (for example ArrayList).
So, when you have your ArrayList<MyData> you can easliy use Collections.sort passing both your list and implementation of Comparator<T> interface where all the sorting logic would be.
For example, if you want to sort whole list using only String title field it can look like this:
Comparator<MyData> with implemented compare function compare(MyData o1, MyData o2){return o1.title.compareTo(o2);
My advice to create custom array list.
private ArrayList<UserContainer> userList=new ArrayList<UserContainer>();
UserContainer usercontainer=new UserContainer()
usercontainer.name=Amazon;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
UserContainer usercontainer2=new UserContainer()
usercontainer.name=Google;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
UserContainer usercontainer3=new UserContainer()
usercontainer.name=BBC;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
Collections.sort(userList, new Comparator<UserContainer>() {
#Override
public int compare(UserContainer s1, UserContainer s2) {
return s1.name.compareToIgnoreCase(s2.name);
}
});
Model:-
public class UserContainer {
public String name = "";
public String date = "";
}
I hope to help you.
Create a class and use comparator or comparable.
for further reference please check (How to sort an ArrayList in Java)
Arrays.sort(stringArray);
Its a nice way to sort.
I recommend you to create a Object for example 'BrowserStoredData' for each element of the list. With the strings required:
public class BrowserStoredData implements Comparable<BrowserStoredData> {
String browserType;
String browserName;
String browserUrl;
String browserDate;
public BrowserStoredData(String browserType, String browserName,
String browserUrl, String browserDate) {
super();
this.browserType = browserType;
this.browserName = browserName;
this.browserUrl = browserUrl;
this.browserDate = browserDate;
}
public int compareTo(BrowserStoredData bsd) {
return (this.browserName).compareTo(bsd.browserName);
}
#Override
public String toString() {
return browserType + "\t\t" + browserName + "\t\t" + browserUrl
+ "\t\t" + browserDate;
}
}
With that object you easily can order a list of BrowserStoredData objects simply by using Collections.sort(yourList)
For example:
BrowserStoredData bsd1 = new BrowserStoredData("Default Browser", "Google", "www.Google.com", "14/12/2013");
BrowserStoredData bsd2 = new BrowserStoredData("Default Browser", "BBC", "www.BBC.com", "13/12/2015");
BrowserStoredData bsd3 = new BrowserStoredData("Default Browser", "Amazon", "www.Amazon.com", "11/11/2014");
List<BrowserStoredData> listBrowsers = new ArrayList<BrowserStoredData>();
listBrowsers.add(bsd1);
listBrowsers.add(bsd2);
listBrowsers.add(bsd3);
Collections.sort(listBrowsers);
for (int i = 0 ; i < listBrowsers.size() ; i++){
BrowserStoredData bsd = listBrowsers.get(i);
System.out.println(bsd.toString());
}
The exit will be:
Default Browser Amazon www.Amazon.com 11/11/2014
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Google www.Google.com 14/12/201

Android/Java String Concatenation with Unwanted "\n"

I am writing an Android program that parses data from the Translink API web page. The program works, but I am having an issue with the data that I am storing. It seems that each time the program loops, a "\n" is added to the String itself. Here is the code itself:
private class DownloadWebpageText extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String...urls) {
// params comes from the execute() call: params[0] is the url.
try {
// Test Code
for(int h=0; h<prev_stops.size(); h++) {
Document doc = Jsoup.connect("http://api.translink.ca/rttiapi/v1/stops/" + prev_stops.get(h) + "/estimates?&timeframe=120&apikey=XMy98rbwFPLcWWmNcKHc").get();
nextbuses = doc.select("nextbus");
schedules = doc.select("schedules");
String bus_times = "";
temp += "Arrival Times for Stop " + prev_stops.get(h) /*+ " (Previous Stop: " + prev_stop + "): \n" + "\nPrevious Stops: " + prev_stop*/;
for(int i=0; i<nextbuses.size(); i++) {
temp += parseData(nextbuses.get(i).select("routeno").toString()) + ": ";
schedule = schedules.get(i).children();
expectedleavetime = schedule.select("expectedleavetime");
for(int j=0; j<expectedleavetime.size(); j++) {
if(j != 0) {
temp = temp.concat(", ");
}
temp = temp.concat(parseData(expectedleavetime.get(j).toString()));
}
temp += "\n";
}
temp += "\n";
}
return "";
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
Where the parseData() function is just this:
public String parseData(String input) {
int beg = input.indexOf(">") + 1;
int end = input.lastIndexOf("<") - 1;
return input.substring(beg, end);
}
Here is the output from the console:
Arrival Times for Stop 56549
402:
4:10pm,
4:40pm,
5:10pm,
5:40pm
What I want the output to be like is this:
Arrival Times for Stop 56549
402: 3:40pm, 4:10pm, 4:40pm, 5:10pm
403: .....
You could use an ArrayList, which you define outside all for-loops
// Define our ArrayList
ArrayList<String> allStops = new ArrayList<String>();
// Define a string that holds information about the current stop
String currentStopInfo = "Arrival Times for Stop " + prev_stops.get(h);
for(int i=0; i<nextbuses.size(); i++) {
// Define a temporary String that holds all the times for a specific bus
String temp_2 = parseData(nextbuses.get(i).select("routeno").toString()) + ": ";
schedule = schedules.get(i).children();
expectedleavetime = schedule.select("expectedleavetime");
for(int j=0; j<expectedleavetime.size(); j++) {
if(j != 0) {
temp_2 += ", ";
}
temp_2 = temp_2.concat(parseData(expectedleavetime.get(j).toString()));
}
// Add the string that holds info for one bus to our Array
allStops.add(temp_2);
}
And when you want to print all of your strings(all of your stops for each bus)(every string contains information about one bus) you just do:
//Print the line that holds the current stop information
System.out.println(currentStopInfo);
for(String x : allStops) {
// Loop through our ArrayList, and print the information
System.out.println(x);
}

Categories

Resources