android, Comparator sort wrong - android

I have a Comparator to sort by 3 values:
ORDER_BY_Points
ORDER_BY_Gdif // goals difference
ORDER_BY_Goals
First I get a array from a json string. I send the array to StandingsSort.ORDER_BY_RULES
Arrays.sort(addressArray, StandingsSort.ORDER_BY_RULES);
Here is my code:
static final Comparator<Standings> ORDER_BY_Points = new Comparator<Standings>() {
public int compare(Standings a1, Standings a2) {
return a1.points.compareTo(a2.points);
}
};
static final Comparator<Standings> ORDER_BY_Gdif = new Comparator<Standings>() {
public int compare(Standings a1, Standings a2) {
return a1.Gdif.compareTo(a2.Gdif);
}
};
static final Comparator<Standings> ORDER_BY_Goals = new Comparator<Standings>() {
public int compare(Standings a1, Standings a2) {
return a1.goalsP.compareTo(a2.goalsP);
}
};
static final Comparator<Standings> ORDER_BY_RULES = new Comparator<Standings>() {
public int compare(Standings a1, Standings a2) {
int i = ORDER_BY_Points.compare(a1,a2);
if(i == 0){
i = ORDER_BY_Gdif.compare(a1,a2);
if(i == 0){
i = ORDER_BY_Goals.compare(a1,a2);
}
}
return i;
}
};
class Standings {
String teamName;
String goalsP;
String goalsM;
String Gdif;
String points;
#Override
public String toString() {
return "" + teamName + "," + goalsP + ":" + goalsM + "," + Gdif + "," + points + "";
}
public Standings(String teamName, String goalsP,
String goalsM, String Gdif, String points) {
super();
this.teamName = teamName;
this.goalsP = goalsP;
this.goalsM = goalsM;
this.Gdif = Gdif;
this.points = points;
}
}
But the result is not OK! Here is the result
Name, Goals, GDif, Points
Team,11:9,2,10
Team,5:3,2,10
Team,9:2,7,11
Team,0:6,-6,2
Team,3:9,-6,2
Team,6:9,-3,3
Team,8:13,-5,3
Team,8:9,-1,5
Team,8:11,-3,5
Team,8:7,1,5
Why does the Comparator sort wrong?

Since you store the points as Strings, "10" comes before "2", "3", and "5". If you want to compare these in order by the numerical value, you need to convert them into ints first.
Similarly, Gdif and Goals are compared as Strings which is probably not what you want.

Related

How to sort a listview by string numbers?

Here is my main issue, after some researches, I didn't find a solution so... I would like to sort my list of custom objects. These items have a price, but for a reason they are strings not int. I would like to know how to achieve this, thanks for helping !
Little personnal question, sorting a listview and a recyclerview are they done the same way ?
EDIT:
public class Product implements Parcelable {
private String imgUrl, titre, description, prix, nomAgence, pays, ville, type_produit, nbPieces = null;
List<String> urlImageList_thumb = new ArrayList<>();
List<String> urlImageList_full = new ArrayList<>();
private int isAdded = 0;
/* getters and setters*/
}
EDIT 2 :After your help, here's my code for comparable
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "");
String tmp2 = otherProduct.prix.replace(" €", "");
//Integer p1 = Integer.valueOf(tmp); --> does not work
//Integer p2 = Integer.valueOf(tmp2); --> does not work
Integer p1 = Integer.parseInt(tmp); //same error
Integer p2 = Integer.parseInt(tmp2); // same error
return p1.compareTo(p2);
}
Here's the code in the activity:
bouton_tri.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Collections.sort(productList);
}
});
EDIT 3 :
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "").replaceAll(" ", "");
String tmp2 = otherProduct.prix.replace(" €", "").replaceAll(" ", "");
Integer p1 = Integer.valueOf(tmp);
Integer p2 = Integer.valueOf(tmp2);
return p1.compareTo(p2);
}
I still have an error, but when I just take off " €" the value is "5 300 000", if only spaces "5300000€". But putting both together gives me this error java.lang.NumberFormatException: Invalid int: "-" ... Any ideas ? Thanks
You can make modify your Product class to implement Comparable
Before converting the String to an Integer you need to remove the €and all spaces.
public class Product implements Parcelable, Comparable<Product> {
private String prix;
//...
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "").replaceAll(" ", "");
String tmp2 = otherProduct.prix.replace(" €", "").replaceAll(" ", "");
Integer p1 = Integer.valueOf(tmp);
Integer p2 = Integer.valueOf(tmp2);
return p1.compareTo(p2);
}
}
Once done to sort your collection you can use : Collections.sort(...); this method will take as parameter the list of custom objects you are using in your adapter.
For example:
List<Product> l = new ArrayList();
Collections.sort(l);
Note that sorting the collection will not refresh the views of the recyclerview.
You will have to call notifyDataSetChanged() on your adapter to refresh the recyclerview:
You can do this in your main activity where you have declared your adapter :
yourAdapter.notifyDataSetChanged();
Just assuming you have List<String> sampleData object
Collections.sort(sampleData, new Comparator<String>() {
#Override
public int compare(String c1, String c2) {
return Integer.valueOf(c1) - Integer.valueOf(c2);
}
});
This will sort your data.
(int) Integer.parseInt(p2.getNumberOfRecords()) - Integer.parseInt(p1.getNumberOfRecords())
So the simple compare of an integer in a String data type would not result correctly but to parse the string first by:
int value = Integer.parseInt(string)
Try this:
Collections.sort (list, new Comparator<String> () {
#Override
public int compare (String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
OR
Collections.sort (list, new Comparator<String> () {
#Override
public int compare (String s1, String s2) {
//cast string price to integer
int price1 = Integer.parseInt(s1);
int price2 = Integer.parseInt(s2);
if (price1 > price1) {
return 1;
}
else if (price2 > price1) {
return -1;
}
else {
return 0;
}
}
});

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: sort by date in the JSON data

I am new to Android. I'm trying to sort by the date in the JSON data, but nothing works. I'm not even getting an error. I've tried so many different ways, but its not working.
I did a lot of searching but could not figure out how to implement this. How can I sort this by the days column? Thank you in advance.
Here's my code
public class ParseJSONTask extends AsyncTask< Void , Void , Void > {
public Handler handler = new Handler();
public Activity act = null;
private static String TAG_SERVICES = "services";
private static String TAG_ID = "id";
private static String TAG_COMMAND = "command";
private static String TAG_DAYS = "days";
private static String TAG_HOURS = "hours";
private static String TAG_OSMS = "osms";
private static String TAG_ISMS = "isms";
private static String TAG_TIMEOUT = "timeout";
public String SMS_SENT = "SMS Gönderildi";
public String SMS_DELIVERED = "SMS İletildi";
public String serviceString = "";
ArrayList<ServiceData> services;
#Override
public void onPreExecute() {
super.onPreExecute();
services = new ArrayList<ServiceData>();
}
#Override
public Void doInBackground(Void... params) {
WebServiceHandler webServiceHandler = new WebServiceHandler();
String JsonStr = webServiceHandler.getJSONData("http://jsonblob.com/55e34310e4b01190df36e861");
try {
JSONObject jsonObject = new JSONObject(JsonStr);
final JSONArray contactsJSON = jsonObject.getJSONArray(TAG_SERVICES);
for (int i = 0; i < contactsJSON.length(); i++) {
ServiceData aServiceData = new ServiceData();
//json parse istedimiz veriyi kullanabiliriz.
JSONObject serviceObject = contactsJSON.getJSONObject(i);
aServiceData.id = serviceObject.getString(TAG_ID);
aServiceData.command = serviceObject.getString(TAG_COMMAND);
aServiceData.days = serviceObject.getString(TAG_DAYS);
aServiceData.hours = serviceObject.getString(TAG_HOURS);
aServiceData.osms = serviceObject.getString(TAG_OSMS);
aServiceData.isms = serviceObject.getString(TAG_ISMS);
aServiceData.timeout = serviceObject.getString(TAG_TIMEOUT);
String input = aServiceData.days + " " + aServiceData.hours;
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(input);
long milliseconds = date.getTime();
final long millisecondsFromNow = milliseconds - (new Date()).getTime();
aServiceData.milliseconds = milliseconds;
services.add(aServiceData);
if(millisecondsFromNow > 0) {
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Thread.sleep(Integer.parseInt(aServiceData.timeout) * 60000);
}
//Timeout aşağı kısımda sürelendirilecek
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String serviceString = "";
for (ServiceData aServiceData:services){
serviceString+=aServiceData.toString();
}
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
// here is sorted data
for (ServiceData aServiceData : services) {
// move DateSendSMS here. above you can add additional logic about millis
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Log.d("+++++", aServiceData.toString());
}
}
}
ServiceData Class:
public static class ServiceData {
public long milliseconds;
public String id = "";
public String command = "";
public String days = "";
public String hours = "";
public String osms = "";
public String isms = "";
public String timeout = "";
#Override
public String toString() {
return id + ", " + command + ", " + days + ", " + hours + ", " + osms + ", " + isms
+ ", " + timeout + "\n \n ";
}
}
Add time field to ServiceData class
ServiceDate {
...
long milliseconds;
...
}
Fill this field in for loop:
long milliseconds = date.getTime();
aServiceData.milliseconds = milliseconds;
Sort services in onPostExecute
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
I am not sure you can directly sort Json Data (I dont know weather there is a library that will actually do it - if so go for it). I Suggest you to put all the ServiceData into a collection (Which you do at the moment) and then Sort it.
You can write your own sorting algorithm or you can use a Java Collections library to do the sorting by implimention Comparable on your ServiceData class or using a Comparable and them you can use Colletions.sort() to sort your list.
Here is a good tutorial.

Display list of time zones similar to that of timezones displayed in S Planner app

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

Sort ArrayList<String[]> by any column and "print" result

I filled array list with values. Each row is item with properties. Now I would like to sort items by one of properties and "print" them to textview.
ArrayList<String[]> arrayList = new ArrayList<String[]>();
final String[] rowToArray = new String[7];
rowToArray[0] = itemName;
rowToArray[1] = itemProperties1;
rowToArray[2] = itemProperties2;
rowToArray[3] = itemProperties3;
rowToArray[4] = itemProperties4;
rowToArray[5] = itemProperties5;
rowToArray[6] = itemProperties6;
arrayList.add(rowToArray);
Could you please help me to sort it by properties and then show me how to print item one by one with properties.
Thank you in advance.
EDIT:
SOLVED BY ppeterka66
I just had to add his code and call Collections.sort(arrayList,new StringArrayComparator(column)); where column is required column to be sortby.
int i=0;
final int column=2;
Collections.sort(arrayList,new StringArrayComparator(column));
for(String[] line :arrayList)
{
Log.d(Integer.toString(i),line[column].toString());
}
Collections.sort
for example
class User {
String name;
String age;
public User(String name, String age) {
this.name = name;
this.age = age;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.util.Comparator;
public class ComparatorUser implements Comparator {
public int compare(Object arg0, Object arg1) {
User user0 = (User) arg0;
User user1 = (User) arg1;
int flag = user0.getAge().compareTo(user1.getAge());
if (flag == 0) {
return user0.getName().compareTo(user1.getName());
} else {
return flag;
}
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortTest {
public static void main(String[] args) {
List userlist = new ArrayList();
userlist.add(new User("dd", "4"));
userlist.add(new User("aa", "1"));
userlist.add(new User("ee", "5"));
userlist.add(new User("bb", "2"));
userlist.add(new User("ff", "5"));
userlist.add(new User("cc", "3"));
userlist.add(new User("gg", "6"));
ComparatorUser comparator = new ComparatorUser();
Collections.sort(userlist, comparator);
for (int i = 0; i < userlist.size(); i++) {
User user_temp = (User) userlist.get(i);
System.out.println(user_temp.getAge() + "," + user_temp.getName());
}
}
}
You could create a reusable String[] Comparator you could specify which indexes to compare the arrays on:
public class StringArrayComparator implements Comparator<String[]> {
//we store the index to compare the arrays by in this instance variable
private final int stringIndexToCompare;
//constructor accepting the value for the index to check
public StringArrayComparator(int whichString) {
stringIndexToCompare=whichString;
}
#Override
public int compare(String[] o1, String[] o2) {
//checking if any of the arrays is null
if(o1==null) { return o2==null?0:1; } //if o1 is null, o2 determines the resuult
else if(o2==null) { return -1; } //this only gets evaluated if o1 is not null
//get the strings, by checking if the arrays are long enough
String first = o1.length>stringIndexToCompare?o1[stringIndexToCompare]:null;
String second= o2.length>stringIndexToCompare?o2[stringIndexToCompare]:null;
//null checking the strings themselves -- basically same as above
if(first==null) { return second==null?0:1; }
else if(second==null) { return -1; }
//if both non-null, compare them.
return first.compareTo(second);
}
}
To be used on your list:
Collections.sort(myList,new StringArrayComparator(3));
Note: the 3 specifies the index of the array to be compared.
You didn't specify the expected output of how the printed string should look, but just to print the list, you could use this oneliner:
System.out.println(Arrays.deepToString(a.toArray()));
EDIT
I would like to see something like Log.d("line number",column[0]+","+column1+","+column[2]+...);
Hey, that looks almost OK... Basically you only have to put it into a loop: this prints it line by line:
int lineNo=0;
for(String[] line :myList) {
StringBuilder sb = new StringBuilder();
sb.append(++i); //line number, incrementing too
//iterating through the elements of the array
for(int col=0;col<line.lenght;col++) {
sb.append(",");
if(line[col]!=null) { //check for null....
sb.append(line[col]);
}
}
Log.d(sb.toString()); //append the value from the builder to the log.
}
To get it in one big string:
int lineNo=0;
StringBuilder sb = new StringBuilder(); //create it here
for(String[] line :myList) {
sb.append(++i); //line number, incrementing too
//iterating through the elements of the array
for(int col=0;col<line.lenght;col++) {
sb.append(",");
if(line[col]!=null) { //check for null....
sb.append(line[col]);
}
}
sb.append("\n"); //append line break
}
Log.d(sb.toString()); //append the value from the builder to the log.
Or, maybe it would be nicer (though slower) to use String.format() for this purpose,a s that offers better formatting:
//assembly format string
//if no line number was needed: String format = "";
String format = "%d"; //line number, %d means integer
for(int i=0;i<7;i++) {
format+=",%20s"; //%20s means left aligned, 20 wide string
}
format += "\n"; //line break;
int lineNumber=0;
for(String[] line:myArray) {
//if you didn't need the line number, it would be so easy here
//String.format(format,line); //one line, but this doesn't have the line number yet...
//with line numbers:
int iamLazyNow = 0;
String formatted = String.format(format,++lineNumber,
line[iamLazyNow++], line[iamLazyNow++],
line[iamLazyNow++], line[iamLazyNow++],
line[iamLazyNow++], line[iamLazyNow++],
line[iamLazyNow++]); //practically one line, but ugly
//you can append formatted to a StringBuilder, or print it here...
}

Categories

Resources