Display a array of values in a single view in android - android

Is there any android library to handle this
Above image is a singe view
There should be one view for which I pass array of values like city above

You can try some thing like this , I don't think library is needed
private String getTextToShow(String[] list){
String text="";
if(list==null||list.length==0){
text="No items";
}else if(list.length==1){
text=list[0];
}else if(list.length==2){
text=list[0]+", "+list[1];
}else {
text=list[0]+list[1]+ "+ " +(list.length-2)+" more";
}
return text;
}

you don't need an additional library for this specific task, just concatenate the array elements or list into a single element and display it int the view. An example is given below
public void setView(ArrayList<String> elements){
String result="";
for(String element: elements){
result=result + " " + elements;
}
textview.setText(result);
}

You can use this method which returns a String to bind in the view
private String buildString(ArrayList<String> list, int count) {
StringBuilder ch = new StringBuilder();
if (count <= list.size()) {
for (int i = 0; i < count; i++) {
ch.append(list.get(i)).append(",");
}
return ch.replace(ch.lastIndexOf(","), ch.lastIndexOf(",") + 1, String.format("+ %d more", list.size() - count)).toString();
} else {
for (String s : list) {
ch.append(s).append(",");
}
return ch.substring(0, ch.length() - 1);
}
}

Related

Emoji in profile avatar

I'm in need to setting profile name as profile picture, For this i'll take the first character of word
String getImageText(String name) {
StringBuilder avatarText = new StringBuilder();
try {
if (!TextUtils.isEmpty(name)) {
String[] words = name.split("\\s");//splits the string based on whitespace
for (int count = 0; (count <= 1 && count < words.length); count++) { // taking first letter of first two words
avatarText.append(words[count].charAt(0)); // appending first letter of the string
}
}
} catch (Exception exception) {
Log.e(TAG, "Exception while getting image text : " + exception.getMessage(), exception);
}
return avatarText.toString();
}
This works pretty good when text contains only words/numbers/special characters.But while setting the emoji as profile name it is not working good.
It displayed like
this
Try this to remove all emojis:
Your edited code:
String removeEmoji(text){
String regex = "[^\\p{L}\\p{N}\\p{P}\\p{Z}]";
String result = text.replaceAll(regex, "");
return result;
}
String getImageText(String inputName) {
StringBuilder avatarText = new StringBuilder();
String name = "";
try {
if (!TextUtils.isEmpty(inputName)) {
name = removeEmoji(inputName);
String[] words = name.split("\\s");//splits the string based on whitespace
for (int count = 0; (count <= 1 && count < words.length); count++) { // taking first letter of first two words
avatarText.append(words[count].charAt(0)); // appending first letter of the string
}
}
} catch (Exception exception) {
Log.e(TAG, "Exception while getting image text : " + exception.getMessage(), exception);
}
return avatarText.toString();
}
Checkout this for more information

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

receive a string message from user input in android and parse to an int so can be stored in an array and compared with another array of integers

I am having a problem with the above task in my android application. I am accepting user input from the EditText widget in the form of String. I accepting numbers from the user so I have to parse them to integers so they can be compared with another array of integers. I have the line:
String message = editText.getText().toString()
then to try and parse the String to an int I have the code line:
int userNumbers = Integer.parseInt(message).
However when I attempt to compare the array userArray with the array numbers I am getting the error that "Incompatible operand types String and Integer.
Can anyone see where my problem is or how I can solve it? Here's my code:
Thanks in advance.
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = ".com.example.lotterychecker.MESSAGE";
static boolean bonus = false;
static boolean jackpot = false;
static int lottCount = 0;
Button check;
Integer [] numbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//link to the intended web site and get the lottery numbers while the app is opening
try {
Document doc = Jsoup.connect("http://www.national-lottery.co.uk/player/p/drawHistory.do").userAgent("Mozilla").get();
Elements elements = doc.getElementsByClass("drawhistory");
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String [] split = noElement.text().split(" - ");
// set up an array to store numbers from the latest draw on the lottery web page
Integer [] numbers = new Integer [split.length];
int i = 0;
for (String strNo : split) {
numbers [i] = Integer.valueOf(strNo);
i++;
}
for (Integer no : numbers) {
System.out.println(no);
}
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
System.out.println("Bonus ball: " + bonusBall);
} catch (IOException e) {
// TODO Auto-generated catch block
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;
}
//called when the user clicks the send button
public void checkNumbers(View view) {
final int SIZE =6;
String [] userArray = new String[SIZE];
//create an intent to display the numbers
Intent intent = new Intent(this, DisplayNumbersActivity.class);
EditText editText = (EditText) findViewById(R.id.enter_numbers);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message );
startActivity(intent);
//parse string message to an int for user numbers
try{
int userNumbers = Integer.parseInt(message); //is this right?
}//try
catch (NumberFormatException e)
{
System.out.println("Not a number" + e.getMessage());
}
Toast.makeText(MainActivity.this, "Here are your numbers", Toast.LENGTH_LONG).show();
for (int count =0; count < SIZE; count ++)
{
if (check.isPressed())
{
userArray[count] = editText.getText().toString();
}
}//for
//compare the two arrays of integers
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (userArray[loop] == numbers[loopOther]) //how do I parse this?
{
lottCount++;
}else if (userArray[loop] == bonus)
{
bonus = true;
}
}//for
}//for main
You have this
Integer [] numbers; // numbers is an integer array
You have string array
String [] userArray = new String[SIZE]; // userArray is a string array
You compare like below
if (userArray[loop] == numbers[loopOther])
So you get the error Incompatible operand types String and Integer.
try
if (Integer.parseInt(userArray[loop]) == numbers[loopOther])
Enclosing the above with try catch block
String message = editText.getText().toString();
try{
int userNumbers = Integer.parseInt(message);
//is this right? yes
}
catch (NumberFormatException e)
{
e.printStacktrace();
}
Change String to Int here:
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (Integer.valueOf(userArray[loop]) == numbers[loopOther]) //how do I parse this?
{
lottCount++;
}else if (Integer.valueOf(userArray[loop]) == bonus)
{
bonus = true;
}
}//for
}//for main
Parse Like this :
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (Integer.parseInt(userArray[loop]) == numbers[loopOther])
{
lottCount++;
}else if (userArray[loop] == bonus)
{
bonus = true;
}
}
}

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

regular-expressions android

i have string like these for example
309\306\308\337_338
309\306\337_338
310
311\315_316\336_337
311\315_316\336_337
311\335_336
these strings means list of page number , for example string "309\306\308\337_339" means
pages 309,306,308,337,338,339
i want to pass one of these string to function which return it as string like this
309,306,308,337,338,339
this function do that but in c# , i want to impalement in android
private static string Get_PageNumbers(string str)
{
ArrayList arrAll = new ArrayList();
MatchCollection match;
string[] excar;
string strid, firstNumber, lastlNumber;
int fn, ln;
ArrayList arrID = new ArrayList();
//***In Case The Range Number Between "_"
if (str.Contains("_"))
{
// match_reg = new Regex("(w?[\\d]+)*(_[\\d]+)");
Regex matchReg = new Regex("(w?[\\69]+_[\\d]+)*(q?[\\d]+//)*(a?[\\d]+_[\\d]+)*(y?[\\d]+)*");
match = matchReg.Matches(str);
int count = match.Count;
excar = new string[0];
for (int i = 0; i < count; i++)
{
Array.Resize(ref excar, count);
excar[i] = match[i].Groups[0].Value;
if (excar[i] != string.Empty)
arrID.Add(excar[i]);
}
//******IF Array Contains Range Of Number Like"102_110"
if (str.Contains("_"))
{
for (int i = 0; i < arrID.Count; i++)
{
strid = arrID[i].ToString();
if (arrID[i].ToString().Contains("_"))
{
int idy = strid.LastIndexOf("_");
firstNumber = strid.Substring(0, idy);
if (idy != -1)
{
lastlNumber = strid.Substring(idy + 1);
fn = int.Parse(firstNumber);
arrAll.Add(fn);
ln = int.Parse(lastlNumber);
for (int c = fn; c < ln; c++)
{
fn++;
arrAll.Add(fn);
}
}
}
else
{
arrAll.Add(arrID[i].ToString());
}
}
//******If Array Contain More Than One Number
if (arrAll.Count > 0)
{
str = "";
for (int i = 0; i < arrAll.Count; i++)
{
if (str != string.Empty)
str = str + "," + arrAll[i];
else
str = arrAll[i].ToString();
}
}
}
}
//***If string Contains between "/" only without "_"
else if (str.Contains("/") && !str.Contains("_"))
{
str = str.Replace("/", ",");
}
else if (str.Contains("\\"))
{
str = str.Replace("\\", ",");
}
return str;
}
I think this is easier to do with split function:
public static String Get_PageNumbers(String str) {// Assume str = "309\\306\\308\\337_338"
String result = "";
String[] pages = str.split("\\\\"); // now we have pages = {"309","306","308","337_338"}
for (int i = 0; i < pages.length; i++) {
String page = pages[i];
int index = page.indexOf('_');
if (index != -1) { // special case i.e. "337_338", index = 3
int start = Integer.parseInt(page.substring(0, index)); // start = 337
int end = Integer.parseInt(page.substring(index + 1)); // end = 338
for (int j = start; j <= end; j++) {
result += String.valueOf(j);
if (j != end) { // don't add ',' after last one
result += ",";
}
}
} else { // regular case i.e. "309","306","308"
result += page;
}
if (i != (pages.length-1)) { // don't add ',' after last one
result += ",";
}
}
return result; // result = "309,306,308,337,338"
}
For example this function when called as follows:
String result1 = Get_PageNumbers("309\\306\\308\\337_338");
String result2 = Get_PageNumbers("311\\315_316\\336_337");
String result3 = Get_PageNumbers("310");
Returns:
309,306,308,337,338
311,315,316,336,337
310
if i can suggest different implementation....
first, split string with "\" str.split("\\");, here you receive an array string with single number or a pattern like "num_num"
for all string founded, if string NOT contains "" char, put string in another array (othArr named), than, you split again with "" str.split("_");, now you have a 2 position array
convert that 2 strings in integer
now create a loot to min val form max val or two strings converted (and put it into othArr)
tranform othArr in a string separated with ","

Categories

Resources