I got a very annoying problem here and I hope you can help me.
I have a List of Plants (Self defined Class). These Plants got a Name, an ID and some characteristics. The characteristics are saved in Strings.
F.e. Characteristic1 is the size of a plant, characteristic2 is the design of the leafs and so on..
I have some Spinners now, and in each of these Spinners a Selection of one characteristic should be available (Spinner1 got all characteristics from the variable characteristics1 from all plants, ...)
The goal is that I can use these Spinners to give the User the Plants, which suits to the User's Selection of the characteristics.
Any ideas how I can implement that in a non-spaghetti way? I'm a bit new to programming so I could really need your help.
I Hope I explained it well, it's quite hard for me explaining it in my second language.
My Code:
Plant - Class
private int pd_id;
private String pd_plantname;
private String pd_longinfo;
private String pd_infochar1;
private String pd_infochar2;
private String pd_infochar3;
private String pd_infochar4;
private String pd_infochar5;
Image-Class
private int i_id;
private int i_p_id;
private String i_path;
private Calendar i_date;
In my Activity i got a List of Images and a List of Plants.
To Fill a Spinner with the characteristics i use this Code.
ArrayList<String> sInfo1 = new ArrayList<String>();
while (i < plantlist.size()) {
sInfo1.add(plantlist.get(i).getPd_infochar1());
i++;
}
ArrayAdapter<String> spInfo2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sInfo1);
spArt.setTag(1);
spArt.setAdapter(spInfo1);
spAlter.setOnItemSelectedListener(new MyOnItemSelectedListener(spAlter));
I got this 5 times for 5 spinners. Now to the OnItemSelectedListener
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (sp.getTag() == spAlter.getTag()) {
int i2 = 0;
while (i2 < plantlist.size()) {
if (plantlist.get(i2).getPd_infochar1()
.equalsIgnoreCase((String) sp.getSelectedItem())) {
}
else{
if(((String) sp.getSelectedItem()).equalsIgnoreCase("--Bitte auswählen--")){
}
else{
int pid = plantlist.get(i2).getPd_id();
plantlist.remove(i2);
ArrayList<Image> localIlist = getImageListFromPlantID(pid);
int x = 0;
while (x < localIlist.size()){
Toast.makeText(entscheidungsbaum.this, localIlist.get(x).getI_path(), Toast.LENGTH_SHORT).show();
imageList.remove(localIlist.get(x));
x++;
}
}
}
i2++;
}
}
So I delete for each characteristic which is wrong the images from the imagelist (which is the source for a gridview).
Firstly, this works not very well, I get some wrong images...
Secondly, that code is very bad, I know that. Can you help me find a better way to adapt the imagelist to the Spinner Selection?
Related
I have a collection of object assigned to an adapter set to a listview. I know how to sort an adapter value when it contains single object. My question is how do I sort the collection only on the data datatype. Below is my collection
you = new MyVideoAdapter(getActivity(),vDancers,video, vName, vDanceStyle, vOwner, dCountry, vPic, vCreated, fullname,
vLikes,vComments, vViews,vRepost, objectID, nLikes, nComments, nRepost, vUserID, postType);
//you.comp
listView.setAdapter(you);
I want to sort this adapter (you) by the vCreated which is an array of dates. Thanks in advance for any help.
For those looking for a solution, this is how I went about it (I don't know if its the best solution but it does work for my case).
1. Instead of populating the adapter with the individual arrays, I created an ArrayList and populated it with my arrays.I sorted it using compareTo().
public class Items implements Comparable<Items>{
private final Number vLikes; private final Number vComments; private final Number vRepost; private final Number vViews;
private final Date vCreated;
public Items(Number vLikes, Number vComments, Number vViews, Number vRepost, Date created) {
this.vCreated = vCreated;
this.fullname = fullname;
this.vLikes = vLikes;
this.vComments = vComments;
this.vViews = vViews;
this.vRepost = vRepost;
}
#Override
public int compareTo(Items o) {
if (getvCreated() == null || o.getvCreated() == null)
return 0;
return o.getvCreated().compareTo(getvCreated());
}
public Number getvLikes() {
return vLikes;
}
public Number getvComments() {
return vComments;
}
public Number getvViews() {
return vViews;
}
public Number getvRepost() {
return vRepost;
}
public Date getvCreated() {
return vCreated;
}
}
2. I then sort the arraylist using the date column and using Collections to apply the sorting.
List<Items> myList = new ArrayList<Items>();
Items item = new Items(a,b,c,d);//a, b, are my variables
myList.add(item);
3. I populated my adapter with the sorted arraylist.
Collections.sort(myList);
you = new MyAdapter(getActivity(), myList);
I hope this helps.
I would like to know a way to store an image and associated text in something like a List. I tried doing something like this
List<NameValuePair>cars = new ArrayList<NameValuePair>();
cars.add(new BasicNameValuePair("Hyundai Elantra",Integer.toString(R.drawable.hyundai_elantra)));
I know this is wrong but I'm posting it so you get an idea of what I'm trying to achieve.
It looks like the best thing for you would be to create a custom class called Car to store each car, and then create an ArrayList<Car> to store the data.
Here is what your Car class would look like:
public class Car
{
public String type;
public int imageID;
public Car(String t, int i)
{
type = t;
imageID = i;
}
public String toString()
{
return type + " " + String.valueOf(imageID);
}
}
Then you would declare the ArrayList, and add values:
ArrayList<Car> carList = new ArrayList<Car>();
carList.add(new Car("Hyundai Elantra", R.drawable.hyundai_elantra));
carList.add(new Car("Lexus RX350", R.drawable.lexus_rx350));
Then, you could iterate through the list when you want to populate your UI:
for (Car c : carList){
String s = c.type;
int image = c.imageID;
//use the values.......
}
Note that you could use this ArrayList as the data source for a custom adapter for displaying the text and images in a ListView, if that's what you're looking to do.
you can create a class named NameValue with Textand Image and you can declare an array list as follows
List<NameValue >cars = new ArrayList<NameValue >();
I searched for related questions but didn´t find a solution (at least i don´t know if i named it correctly)
So, i have two ArrayLists and i would like to randomize all of them to get a value:
public class ListBox {
public static ArrayList listOne(){
ArrayList<Lists> listOne = new ArrayList<>();
listOne.add(new Item("Text One"));
listOne.add(new Item("Text Two"));
return listOne;
}
public static ArrayList listTwo(){
ArrayList<Lists> listTwo = new ArrayList<>();
listTwo.add(new Item("Text Three"));
listTwo.add(new Item("Text Four"));
return listTwo;
}
}
in other activity:
public void buttonClick(View view){
ArrayList<Lists> algumasListas = ListBox.listOne();
...
}
This is where i shuffle it
public class ListMixer extends ListBox{
public ArrayList<Lists> listas = null;
public ListMixer(ArrayList<Lists> listas ) {
this.listas = listas;
}
protected String mixList(){
Double randomNumber = new Double(Math.random() * listas.size());
int randomNum = randomNumber.intValue();
Lista lista= listas.get(randomNum);
String listaString2 = String.valueOf(lista);
String message = ("This is your list: " + listas);
return message;
}
}
my desired output would be one of the four listItems.
Appreciate the help!
Merge arrays into single one of size N.
Choose a random number in range 0..N-1.
Choose an element by index.
The first bug I'm seeing in your code is that listOne() returns object listTwo when called, which doesn't exist. It probably shouldn't even compile, unless something funky is going on with global scope variables.
The following code should do what you want by merging the two lists into one and then returning a random object from them.
public Object randomFromList(List<Object> listOne, List<Object> listTwo){
List<Object> bigList = new ArrayList<Object>(listOne.size() + listTwo.size());
bigList.addAll(listOne);
bigList.addAll(listTwo);
return bigList.get(new Random().nextInt(bigList.size()));
}
For optimization, if you call this a lot, I would save the Random() object outside of the method to avoid instantiating it every time you make the call.
I have two lists of Default and Chrome browsers history.
I want to merge these two lists into one list.
I need to update item if I find it duplicate (is common between two lists).
So, my "BrowserRecord" class is like this:
public class BrowserRecord {
private long id;
private int bookmark;
private long created;
private long date;
private String title;
private String url;
private long visits;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BrowserRecord record = (BrowserRecord) o;
return url.equals(record.url);
}
#Override
public int hashCode() {
return url.hashCode();
}
// other getter setter methods
...
}
and finally, I have a method that gets browsers histories and does merging:
public List<BrowserRecord> getHistory() {
List<BrowserRecord> browserList = new ArrayList<BrowserRecord>();
// get history of default and chrome browsers
List<BrowserRecord> defaultList = getDefaultBrowserHistory();
List<BrowserRecord> chromeList = getChromeBrowserHistory();
Log.e(TAG, "=> size of Default browser:" + defaultList.size());
Log.e(TAG, "=> size of Chrome browser:" + chromeList.size());
// compare list A with B, update A item if equal item found in B and push it to tempList
for(int i=0; i<chromeList.size(); i++) {
BrowserRecord chromeBrowser = chromeList.get(i);
for(int j=0; j<defaultList.size(); j++) {
BrowserRecord defaultBrowser = defaultList.get(j);
if(chromeBrowser.equals(defaultBrowser)) {
if(chromeBrowser.getBookmark() != defaultBrowser.getBookmark())
chromeBrowser.setBookmark(1);
chromeBrowser.setVisits(chromeBrowser.getVisits() + defaultBrowser.getVisits());
}
}
browserList.add(chromeBrowser);
}
// compare list B with A, jump if equal item found in A, push to tempList if item not found
for(int i=0; i<defaultList.size(); i++) {
BrowserRecord defaultBrowser = defaultList.get(i);
boolean found = false;
for(int j=0; j<chromeList.size(); j++) {
BrowserRecord chromeBrowser = chromeList.get(j);
if(defaultBrowser.equals(chromeBrowser)) {
found = true;
break;
}
}
if(!found)
browserList.add(defaultBrowser);
}
Log.e(TAG, "=> size of final browser:" + browserList.size());
return browserList;
}
I have tested this method and is working fine. Since my history records on mobile device after 3 years didn't exceed more than 200 records on one list and 150 for others, I assume something similar is happening for other users. But I'm sure is not optimum way.
What do you recommend?
any suggestion would be appreciated. Thanks.
Not sure I understand correctly, but it seems like what you're trying to do is, given both lists, create a final list which will contain all of the elements from both lists, removing any duplicates.
If this is the case, then take a look at Java's TreeSet class. If you iterate over all of the elements from both your lists and insert them into a TreeSet, you will basically get the result you're looking for. You can then use an Iterator to create an ArrayList containing all of the non-duplicate items from both your lists. As a side-effect of using a TreeSet, they will ordered (you can also use either a HashSet if you don't care about the order or a LinkedHashSet if you want to preserve the order of insertion).
Dear all i am comparing two List in android if both values are same and it is returning true that is fine but i want to know how many values have been correct between the list string if it is not matching how to achieve this Help is appreciated. Below is my code.
List<String> list1 = new ArrayList<String>(i1.values());
///list 1 = [-ful; to be full of; play; playful; full of play]
List<String> acct_Rte_Cdes_A = Arrays.asList(result) ;
///acct_Rte_Cdes_A = [-ful; to be full of; play; playful; full of play]
if (list1.equals(acct_Rte_Cdes_A)) {
// do what you want to do if the string is there
//System.out.println("True");
} else {
System.out.println("False");
}
Use Collection#retainAll(). like
List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);
// common now contains only the elements which are contained in listA and listB.
So you can check for size if it is greater than 0 it meanse some elements are common. And which are common elements common will tell.
You can use containsAll method on Java collection. Here is an example.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainClass {
public static void main(String[] a) {
String elements[] = { "A", "B", "C", "D", "E" };
List<String> list = new ArrayList<String>(Arrays.asList(elements));
elements = new String[] { "A", "B", "C" };
List<String> list2 = new ArrayList<String>(Arrays.asList(elements));
System.out.println(list.containsAll(list2)); // true
System.out.println(list2.containsAll(list)); // false
}
}
Otherwise, you can use apache CollectionUtils library to improve performances. Depending on the type of Collection provided, this method will be much faster than calling Collection.containsAll(Collection) instead.
See the doc of apache containsAll here.
int correctCount=0, incorrectCount = 0;
List<String> list1 = new ArrayList<String>(i1.values());
List<String> acct_Rte_Cdes_A = Arrays.asList(result)
for(String tmp1: list1) {
for(String tmp2: list2) {
if(tmp1.compareTo(tmp2) == 0) {
correctCount++;
} else {
incorrectCount++;
}
}
}
it's time complexity is high but it will do the trick.
You can iterate through the lists yourself checking for equality and at the same time keeping a counter to indicate on which position they differ.
Sample (pseudo) code:
//if equal return 0, else position of difference
//keep in mind that item at index [0] is first, so return would be 1 if lists differ there
public int checkEquality(List list1, List list2) {
for (int i = 0; i < list1.size(); ++i) {
if (list1[i] != list2[i])
return i + 1;
}
return 0;
}
Also keep in mind, that you'd have to check if the lists are of the same size, and decide what to do if they are not (for example, return -1 to indicated this).
list1.containsAll(acct_Rte_Cdes_A)
boolean containsAll(Collection<?> c)
Returns true if this list contains all of the elements of the
specified collection.