I need random number in recyclerView adapter but I am unable to get any. I am trying to generate the number in the Activity.java and pass it in the constructor but I am getting same number on every item. I have tried this :
Random random = new Random();
randInt = random.nextInt(6);
adapterPost = new AdapterPost(QuestionsActivity.this, postList, randInt);
//Adapter
public class AdapterPost extends RecyclerView.Adapter<AdapterPost.ViewHolder> {
Context context;
ArrayList<ModelPost> postList;
String myUid;
DatabaseReference likesRef;
DatabaseReference postRef;
boolean hasLiked = false;
int randInt;
public AdapterPost(Context context, ArrayList<ModelPost> postList, int randInt) {
this.context = context;
this.postList = postList;
this.randInt = randInt;
myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
likesRef = FirebaseDatabase.getInstance().getReference("Likes");
postRef = FirebaseDatabase.getInstance().getReference("Posts");
}
Please let me know how can I get a different random number on evey item. Thanks!
You need to create list of unique random numbers having same size which your postList have.
public void generateRandom(){
Random random = new Random();
int randInt = random.nextInt(postList.size());
while(list_rand.size()!=postList.size()) {
if (list_rand.contains(randInt)) {
generateRandom();
} else {
list_rand.add(randInt);
}
}
}
Now call generateRandom method and pass populated list to adapter like this:
ArrayList<Integer> list_rand = new ArrayList(postList.size);
generateRandom()
adapterPost = new AdapterPost(QuestionsActivity.this, postList,list_rand);
Now you have unique random numbers according to your listview size. Now you can set items on your listview item freely because every item in list_rand is unique random number.
I am trying to generate the number in the Activity.java and pass it in the constructor but I am getting same number on every item.
Emphasis mine. Of course you're getting the same number on every item since - based on your code - you are generating one random number and using it for the one adapter which creates all of your items.
If you want a different number for each item, generate a new number for each item. For example, you could set a random value on each model item before passing it to the adapter.
Random random = new Random();
for (item in postList) {
item.setRandomNumber(random.nextInt(6));
}
adapterPost = new AdapterPost(QuestionsActivity.this, postList);
Try with the following code and generate random number in specific range.
int minVal = 50;
int maxVal = 200;
Random r = new Random();
int randomVal = r.nextInt(maxVal - minVal + 1) + minVal;
Related
I want to assign the numbers of my array at random to the keys key0, key1 etc ..
I'm using this code where in the first two lines I have my array, and with setText I assign the number. but i can't get it to work ..
String[] shuffledKeys = {"0","1","2","3","4","5","6","7","8","9"};
Random random = new Random(); // or create a static random field...
String randString = shuffledKeys[random.nextInt(shuffledKeys.length)];
key0.setText(shuffledKeys.get(0));
key1.setText(shuffledKeys.get(0));
key2.setText(shuffledKeys.get(0));
key3.setText(shuffledKeys.get(0));
key4.setText(shuffledKeys.get(0));
key5.setText(shuffledKeys.get(0));
key6.setText(shuffledKeys.get(0));
key7.setText(shuffledKeys.get(9));
key8.setText(shuffledKeys.get(8));
key9.setText(shuffledKeys.get(9));
String[] keys = {"0","1","2","3","4","5","6","7","8","9"};
Set<String> addedKeys = new HashSet<String>();
List<String> shuffledKeys = new ArrayList<String>();
Random random = new Random();
while (shuffledKeys.size() < keys.length) {
int index = Math.abs(random.nextInt() % keys.length);
if (!addedKeys.contains(keys[index])) {
addedKeys.add(keys[index]);
shuffledKeys.add(keys[index]);
}
}
/// Shuffled keys should now actually be "shuffled"
key0.setText(shuffledKeys.get(0));
key1.setText(shuffledKeys.get(1));
key2.setText(shuffledKeys.get(2));
key3.setText(shuffledKeys.get(3));
key4.setText(shuffledKeys.get(4));
key5.setText(shuffledKeys.get(5));
key6.setText(shuffledKeys.get(6));
key7.setText(shuffledKeys.get(7));
key8.setText(shuffledKeys.get(8));
key9.setText(shuffledKeys.get(9));
I have a list having number of questions in it.
I want to display the total no. of question present in the list.
Loop is used to get particular element at particular index like :
List<?> list = new ArrayList<>();
for(Object obj : list){
//---- do something with obj
}
You do not need loop for size, there are methods to get size of collected data.
Well it not clear which list you are referring to, but here is some example of how you can get size/length of collected data..
if you are referring to ListView,use getCount() :
// --------------ListView
ListView listView = new ListView(context);
int listViewSize = listView.getCount();
And if your referring to any Collection , use size() :
// --------------Collection
ArrayList<?> arrayList = new ArrayList<>();
int arrayListSize = arrayList.size();
List<?> list = new ArrayList<>();
int listSize = list.size();
Set<?> stringSet = new HashSet<>();
int setSize = stringSet.size();
Map<?,?> hashMap = new HashMap<>();
int mapSize = hashMap.size();
LinkedList<?> link = new LinkedList<>();
int linkedListSize = link.size();
Queue<?> queue = new LinkedList<>();
int queueSize = queue.size();
<?> indicate generic, use data-type (<String>,<Integer> etc) for particular return type..
Any other data type array, use length :
// ---------------Data Type
String[] stringsArray = new String[]{};
int stringArraySize = stringsArray.length;
int[] in = new int[]{};
int intSize = in.length;
This is java document for explanation
I believe you are looking for the below. Although the question is not clear.
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
use size() method to get the size of the list
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 want to make a random array and print it over one by one. But I need to print all of it without make any duplicate. I've try to adding it into list but it seems fail.
My Code :
String quest1 = "5x5#5*10#8/4"
String[] quest = quest1.split("#");
ArrayList <String> question = new ArrayList<String>();
question.add(quest[0]);
question.add(quest[1]);
question.add(quest[2]);
Random rand = new Random();
int id = rand.nextInt(question.size());
System.out.println(question.get(id));
question.remove(id);
I want to print 5x5 5*10 8/4 but in random order and I want to print each of it without print it again.
Make a key value 2d object array or a hashmap of integer and boolean. Against all the numbers keep the boolean value false (implying that the number hasn't been printed yet ). Then generate a random number using Random class. Let this be n. Calculate n%array.length. Now see if for this new index whether you have true/false in the 2dArray/hashmap. If false then print the corresponding number and else don't print anything. I hope it's clear to you
Try following code
ArrayList<Integer> questionPrinted = new ArrayList<Integer>();
int i=0;
while (question.size()>0) {
Random rand = new Random();
int id = rand.nextInt(question.size());
if (questionPrinted.size() > 0) {
if (questionPrinted.contains(id)) {
while (!questionPrinted.contains(id))
id = rand.nextInt(question.size());
}
}
questionPrinted.add(i);
System.out.println(question.get(id));
question.remove(id);
i++;
}
I have a question regarding the following code
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(4);
String wordList[] = new String[4];
{
wordList[0] = "Red";
wordList[1] = "Blue";
wordList[2] = "Green";
wordList[3] = "Orange";
}
String wordToDisplay = wordList[randomInt];
This code works fine however I would like to know if it was possible to get it to not pick the same word two times in a row. For example, if it just selected "Red" then it would not pick "Red" again the next consecutive time. I read something about DISTINCT but I'm not sure if that's along the right path.
Here is the code for the button which uses this
final Button button1 = (Button) findViewById(R.id.button1);
final TextView textView = (TextView) findViewById(R.id.text_random_text);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(9);
String wordToDisplay = wordList[randomInt];
textView.setText(wordToDisplay);
Thankyou for your help
go for list and remove color once used:
private static ArrayList<String> arrayList = new ArrayList<String>();
private static Random random = new Random();
public static void fillList(){
arrayList.add("Red");
arrayList.add("Blue");
arrayList.add("Green");
arrayList.add("Orange");
}
public static String getNextRandomColor(){
if(arrayList.isEmpty()){
fillList();
}
return arrayList.remove(random.nextInt(arrayList.size()));
}
You can do this in two way (probably more but two that I can think of right now):
1) Create a function that uses a global variable to store the last generated random number.
It will look something like this:
int myRand(int i) {
int aux;
Random randomGenerator = new Random();
do {
aux = randomGenerator.nextInt(i);
} while (aux != lastRandGenerated);
lastRandGenerated = aux;
return aux;
}
, where lastRandGenerated is a global variable that you initialize to 0.
Then you use this function to generate random numbers.
2) You can create a class that has a function very similar to the one above and then instantiate an object of that class and use that to generate your random numbers. In the class create a static variable that will remember the last generated random number. Use that instead of the global variable.
The specifics are a bit out of my league but as a math problem there are 24 combinations (4 * 3 * 2 * 1). As heavy handed as this might sound, worst case you could work out all the combos and then pick a one out of 24 random.