I have a Model and I want make an array of this. The problem is I do it like this :
My code :
final WifiModel itemsData[] = {
new WifiModel(nearbyAccessPoints.get(0).SSID, "name"),
new WifiModel(nearbyAccessPoints.get(1).SSID, "name"),
new WifiModel(nearbyAccessPoints.get(2).SSID, "name"),
new WifiModel(nearbyAccessPoints.get(3).SSID, "name"),
new WifiModel(nearbyAccessPoints.get(4).SSID, "name"),
};
And I would like to do a i++ form to i=4 for example.
How can I do that ?
My Model :
public class WifiModel {
private String SSID;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
WifiModel(String SSID, String name) {
this.SSID = SSID;
this.name = name;
}
public String getSSID() {
return SSID;
}
public void setSSID(String SSID) {
this.SSID = SSID;
}
}
easy :)
WifiModel itemsData[] = new WifiModel[5];
for(int i=0; i<5; i++) itemsData[i]=new WifiModel(nearbyAccessPoints.get(i).SSID, "name");
Arrays are not for dynamic length. You can use ArrayList instead to acheive this goal as following:
ArrayList<WifiModel> itemsData = new ArrayList<>();
int n=4; // any number you want
for(int i=0;i<n;i++)
{
itemData.add(new WifiModel(nearbyAccessPoints.get(i).SSID, "name"));
}
try this :
List<WifiModel> list = new ArrayList<>();
WifiModel wifi=null;
int i;
for(i=0; i<4; i++){
wifi = new WifiModel(nearbyAccessPoints.get(i).SSID, "name");
list.add(wifi);
}
Related
I have a spinner which I am filling using the below code:
String[] routeList = response.split("\\^");
List<PresetDetails> list = new ArrayList<PresetDetails>();
for (String x : routeList) {
list.add(new PresetDetails(Arrays.asList(x.split(",")).get(0), Arrays.asList(x.split(",")).get(1), Arrays.asList(x.split(",")).get(2), Arrays.asList(x.split(",")).get(3)));
}
ArrayAdapter<PresetDetails> adap = new ArrayAdapter<PresetDetails>(activity, android.R.layout.simple_spinner_item, list);
TrackingLocations_Spinner_Presets.setAdapter(adap);
PresetDetails
public class PresetDetails {
public String PresetID;
public String Latitude;
public String Longitude;
public String PresetName;
public PresetDetails( String PresetID, String Latitude, String Longitude,String PresetName ) {
this.PresetID = PresetID;
this.Latitude = Latitude;
this.Longitude = Longitude;
this.PresetName = PresetName;
}
#Override
public String toString() {
return PresetName;
}
In another piece of code, I have PresetID and have to programatically select corresponding item in the filled spinner. How can I achieve that.
for(int i = 0; i < list.size(); i++) {
if(list.get(i).equals("your id")) {
spinnerObject.setSelection(i);
break;
}
}
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;
}
}
});
So, I have at this point a collections.sort of java values as you can see
and I have two keys that are integers (let's say for the sake of the example that the values of tipo are 1,2 and the values of id are 3 and 4) and I want to sort the result of theyr multiplication:
Something like this:
valA = a.get(KEY_ONE)*a.get(KEY_TWO);
valB = b.get(KEY_ONE)*b.get(KEY_TWO);
Then compare them.
How can I do it??
here is the code that I have at this point.
Collections.sort( jsonValues, new Comparator<JSONObject>() {
private static final String KEY_ONE = "tipo";
private static final String Key_TWO = "id";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_ONE.toString());
valB = (String) b.get(KEY_ONE.toString());
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
tvJson.setText(sortedJsonArray.toString());
}
}
Thanks in advance !
Photos url links, title, user name are loaded from Parse and packed as map, and then the maps are stored as an arraylist, as follows:
public class Photos
{
private String user_name;
private String photo_title;
private String photo_ref;
public void set_user_name(String name) {this.user_name = name;}
public void set_photo_ref(String photo_ref) {this.photo_ref = photo_ref;}
public void set_photo_title(String photo_title) {this.photo_title = photo_title;}
public String get_user_name() {return user_name;}
public String get_photo_ref() {return photo_ref;}
public String get_photo_title() {return photo_title;}
}
and then downloading from Parse for database,
for (ParseObject photo_data : ob)
{
ParseFile image = (ParseFile) photo_data.get("photo_file");
Photos map = new Photos();
String photo_url = image.getUrl(); map.set_photo_ref(photo_url);
int photo_id = (Integer) photo_data.get("photo_id"); map.set_photo_id(photo_id);
String status = (String) photo_data.get("status"); map.set_photo_status(status);
String photo_user_name = (String) photo_data.get("user_name"); map.set_user_name(photo_user_name);
String photo_title = (String) photo_data.get("photo_title");
if (status.equals("accepted"))
{
map_all_info_photoarraylist.add(map);
}
Question:
How could I create another string array of photo_ref only by fetching from the above map using the method get_photo_ref()
String[] stockArr = new String[map_all_info_photoarraylist.size()];
stockArr = map_all_info_photoarraylist.???????.toArray(stockArr);
Thanks!
If you want an array:
String[] stockArr = new String[map_all_info_photoarraylist.size()];
for(int i =0; i<map_all_info_photoarraylist.size(); i++){
stockArr[i] = map_all_info_photoarraylist.get(i).get_photo_ref();
}
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...
}