Sorting adapter on particular array - android

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.

Related

How to add value from Model class to ArrayList

I am trying to add into my ArrayList some value of 2 number sum. In Model class i have getters and setters, constructor and Method witch calculates two number sum, set and return the new result. I have no idea how to get the result and add the result into ArrayList
Model class:
public class SumOfTwoNumbers {
private String result;
private Context context;
public SumOfTwoNumbers (String result) {
this.result = result;
}
public SumOfTwoNumbers (int x, int y){
int res = x + y;
result = String.valueOf(res);
setResult(result);
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
In Activity I do something like this and i know that, it is wrong:
SumOfTwoNumbers sum = new SumOfTwoNumbers();
ArrayList<SumOfTwoNumbers> arrayList = new ArrayList<>();
arrayList.add(sum.getResult());
I would like to get result and add it to ArrayList.
Can someone tell me in what i have to think?
Hope i explaned well my problem.
Thanks in advance!
Your implementation seems wrong. As model class should always be plain java text. But here you are storing context also, which possibly cause memory leaks.
And, in arrayList part you add only those objects to arrayList for which you have made array list.
ArrayList<SomeClass> list = new ArrayList<>();
AnotherClass a = new AnotherClass();
list.add(a); // this is completely wrong;
SomeClass b= new SomeClass();
list.add(b); //this is perfectly fine
Hope you got your answer.
I'm having a hard time understanding your question, but I guess you're looking to create a list like this? (If your getResult method returns an Integer)
SumOfTwoNumbers sum = new SumOfTwoNumbers(1,4);
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(sum.getResult());

Displaying [1-3519:3,3518:3,3517:3,3516:3,3520:3] in log using array list in android

I am developing an online examination app,where i have different sections like aptitude, reasoning, verbal reasoning etc.Each section contains questions and radio buttons for answers.I am using Array list for displaying the questions and options to the student.
My code is as follows:
if(count==0)
{
ArrayList param = new ArrayList();
param.add(secid);
param.add(Questionid);
param.add(answer);
}
else
{
ArrayList param = new ArrayList();
param.add(Questionid);
param.add(answer);
}
I am getting the array list in the following format
[1, 3519, 3, 3518, 3, 3517, 3, 3516, 3, 3520, 3]
where 1 is section id should be displayed at a time.
3519 is question id.
3 is answer.
the loop iterates until condition fails.
But the requirement is [1-3519:3,3518:3,3517:3,3516:3,3520:3] .Is it possible to display a list like this.I didn't have idea please suggest me
It will be easier for you, if u create pojo class. Since your question is to display the array in that particular format I guess this will help.
ArrayList<String> param = new ArrayList();
if(count==0)
{
param.add(String.valueOf(secid)+ "-" +String.valueOf(Questionid)+":"+String.valueOf(answer);
}
else
{
param.add(String.valueOf(Questionid)+":"+String.valueOf(answer);
}
You can create a string array and make it into a format of your choice.
For example :
Model(POJO) Class :
public class Notification {
private String msg,date;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Notification(String msg, String date) {
this.msg = msg;
this.date = date;
}
}
Create arryList of that class :
private ArrayList arrayList = new new ArrayList<>();
arrayList.add(new Notification("question","post_date"));

Android Recycler view adapter filter with animation

I am trying to optimize the filter method for RecyclerView Adapter in Android. The list is used as an ArrayList. I have seen this post but they are filtering from the original list every time.
Example: if there are 10 results for String 'a' then user type 'm' , 'am' results are subset of 'a' results(results.size()<=10).
I have three points to ask in this question,
Can I optimize HashMap memory by using ArrayMap? Should I use comma separated positions in String instead of Integer objects array or any way to use int primitive array?
I am not getting any animation in this result, how to get that? (I am using notifyItemInserted still no animation)
How much data should be kept in Hashmap, till 2 characters or it should be according to result list size? I would be glad to know if anything can be done better in this code other than these points.
In below code, mList is used in onBindViewHolder method. copyList always contains all data(no insertion or deletion is done on that).
class MyFilter extends Filter {
/**
* 1. check do we have search results available (check map has this key)
* 2. if available, remove all rows and add only those which are value for that key (string)
* 3. else check do we have any key available starting like this, s=har, already available -ha then it can be reused
*
* #param constraint
*/
#Override
protected FilterResults performFiltering(CharSequence constraint) {
//Here you have to implement filtering way
final FilterResults results = new FilterResults();
if (!mSearchMap.containsKey(constraint.toString())) {
String supersetKey = getSupersetIfAvailable(mSearchMap, constraint.toString());
if (supersetKey == null) {
List<Integer> foundPositions = doFullSearch(copyList, constraint.toString());
mSearchMap.put(constraint.toString(), foundPositions);
} else {
List<Integer> foundPositions = filterFromSuperset(copyList, mSearchMap.get(supersetKey), constraint.toString());
mSearchMap.put(constraint.toString(), foundPositions);
}
}
return results;
}
private String getSupersetIfAvailable(Map<String, List<Integer>> mSearchMap, String s) {
Set<String> set = mSearchMap.keySet();
List<String> list = new ArrayList<>(set);
Collections.sort(list);
Collections.reverse(list);
for (String c : list) {
if (s.startsWith(c)) {
return c;
}
}
return null;
}
private List<Integer> filterFromSuperset(List<WeekWorkBean> list, List<Integer> supersetResults, String s) {
List<Integer> results = new ArrayList<>();
String lowerS = s.toLowerCase();
for (int i = 0; i < supersetResults.size(); i++) {
if (list.get(supersetResults.get(i)).getEmpName().toLowerCase().startsWith(lowerS)) {
results.add(supersetResults.get(i));
}
}
return results;
}
private List<Integer> doFullSearch(List<WeekWorkBean> list, String s) {
List<Integer> results = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getEmpName().toLowerCase().startsWith(s.toLowerCase())) {
results.add(i);
}
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// here you can use result - (f.e. set in in adapter list)
mList.clear();
notifyDataSetChanged();
List<Integer> res = mSearchMap.get(constraint.toString());
int j = 0;
for (Integer i : res) {
mList.add(copyList.get(i));
notifyItemInserted(j++);
}
}
}
Check this out
https://medium.com/#iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00#.ehc0gaijt
DiffUtils is what are you looking for. You can use it in Rx chain to move it out of mainThread for a large data.
here is a example
https://medium.com/#nullthemall/diffutil-is-a-must-797502bc1149#.yg35y9q9b
To give an answer for your 2nd point you can try this:
notifyItemRangeChanged(pos, ItemList.size());
HashMap is a Map, there are also TreeMap, LinkedHashMap and Hashtable. each of them has own features and interface is Map, not Collection. You can also use other data structures, like Treeset, HashSet, ArrayList, LinkedList and etc. These structures comes from Set and List interface, which extends to Collection interface. You can use each of them.
If you insert any object to your collection, use notifyItemInserted(int position), if you delete any object use notifyItemRemoved(int position), if you update any object use notifyDataSetChanged(). Be careful about equality of your collection length and adapter view count.
You can store parameter in maps how much you want. There is not any limitation. But you should choose best Collection for you, set, list or map.

Android : Compare two ArrayList of objects and find unmatching ids from the second ArrayList

I want to compare two ArrayList of objects and find the unmatching values from the second ArrayList based on the ids in the object.
For Example:
Person.java
private int id;
private String name;
private String place;
MainActivity.java:
ArrayList<Person> arrayList1 = new ArrayList<Person>();
arrayList1.add(new Person(1,"name","place"));
arrayList1.add(new Person(2,"name","place"));
arrayList1.add(new Person(3,"name","place"));
ArrayList<Person> arrayList2 = new ArrayList<Person>();
arrayList2.add(new Person(1,"name","place"));
arrayList2.add(new Person(3,"name","place"));
arrayList2.add(new Person(5,"name","place"));
arrayList2.add(new Person(6,"name","place"));
I want to compare the arrayList1, arrayList2 and need to find the unmatching values from the arrayList2.
I need the id values 5,6.
How can I do this?
You can use an inner loop, to check if the Person's id from arrayList2 corresponds to any Person id in the arrayList1. You'll need a flag to mark if some Person was found.
ArrayList<Integer> results = new ArrayList<>();
// Loop arrayList2 items
for (Person person2 : arrayList2) {
// Loop arrayList1 items
boolean found = false;
for (Person person1 : arrayList1) {
if (person2.id == person1.id) {
found = true;
}
}
if (!found) {
results.add(person2.id);
}
}
Look at the modifications to person class
public static class Person{
//setters and getters
#Override
public boolean equals(Object other) {
if (!(other instanceof Person)) {
return false;
}
Person that = (Person) other;
// Custom equality check here.
return this.getId() == that.getId();
}
}
Have overridden equals(Object other)
then simply do this
for (Person person : arrayList1) {
arrayList2.remove(person);
}
your answer is array list 2, it will only contain odd objects
You should iterate through the shortest ArrayList you have, so check which list is shorter and then iterate through all the indexes in that list against every index in the other list.
(This is assuming you don't have any duplicates in either list. If you do, you might want to return a list of all indexes found.)
arrayListChars=new ArrayList<>(); //[M,A,R,V,E,L]
arrayListAddChars=new ArrayList<>(); //[M,A,....coming values]
int count = 0;
for(int i=0;i
if(arrayListAddChars.get(i).equals(arrayListChars.get(i))){
count++;
}
else
{
break;
}
}

Randomize different ArrayList to get a value

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.

Categories

Resources