How to randomize(or shuffle) order of Radio Buttons - java

I want to randomize my radio buttons whenever I reopen my app.
For example my layout is like below:
RBtn1
Rbtn2
Rbtn3
Rbtn4
Now I want to shuffle them whenever I open that particular activity. How can I do this?

As far I know, Layouts in resources are immutable. That means you've to make Views in the dynamic or Java way.
What you can do is use the SecureRandom class (accurate than Random for picking random numbers) to pick a random number and take one RadioButton object from the RadioButton array what you will create.
PoC: I'm explaining first by a now written and tested code →
import java.util.*;
public class HelloWorld{
static String los1 = "taotao1";
static String los2 = "taotao2";
static String los3 = "taotao3";
static String los4 = "taotao4";
static String[] X = {los1,los2,los3,los4};
public static void main(String []args){
Collections.shuffle(Arrays.asList(X));
System.out.println(Arrays.toString(X));
}
/*
Test 1 : [taotao4, taotao3, taotao2, taotao1]
Test 2 : [taotao2, taotao3, taotao4, taotao1]
Test 3 : [taotao3, taotao4, taotao1, taotao2]
Test 4 : [taotao2, taotao4, taotao1, taotao3]
*/
}
Explanation: Collections.shuffle shuffles objects in an Array as you will be able to see by running code.
Conceptual Code: I'm saying it conceptual because writing directly in Stack Answer Box without testing, Test to be done by you.
public class NoNotHelloWorld extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
RadioButton r1,r2,r3,r4; //please declare to avoid NullPtr and also declare their functionalities
LinearLayout xyz = (LinearLayout)findViewById(R.id.xyzwhatisthis);
//though unnesseary cast, but I did it.
ArrayList<RadioButton> dydx = new ArrayList<RadioButton>();
dydx.add(r1);
dydx.add(r2);
dydx.add(r3);
dydx.add(r4);
Collections.shuffle(Arrays.asList(arr));
for(RadioButton dxdy : dydx){
xyz.addView(dxdy)
}
}
}
I think it should work otherwise comment box is there.

Related

make a variable available to all fragments?

I'm making a quiz app, there is main activity and it contains fragments which are questions like (Radio Button, Checkbox, Drag and drop questions) . How to collect the Score from all the fragments.
Hold the score variable in the Main Activity
private int score=0;
write public functions to get and set the score in the activity
public void setScore(int score){
this.score=score;
}
public int getScore(){
return this.score
}
Now in the fragments you can get and set score using
score=((MainActivity)getContext()).getScore()
((MainActivity)getContext()).setScore(score)
There are multiple ways to do that.
You can add Set/Get method in Your activity and fetch that from
fragment when you need them.
Create static variable in Activity class and you can access with 'ActivityClassName'.
Use Shared Preference and get access of that data anywhere. You can reset when you need and update from any class.
You can use as your app requires.
Just keep the variable static in which your are storing your score .
for eg : public static int score=0
by writing static it will have reference in memory and will be available until the
activity is running .
Create a Java class and name it as DataHolder. Define score variable as a global variable. Create getter & setter method as static. When you get score, set the values using set method. when you want to get score, use get method. Its simple java. Best thing is you can get and set score from any activity or any fragment using this method. Try below code.
DataHolder.java
public class DataHolder {
private static String Score="";
public static void set_Score(String s){
DataHolder.Score = s;
}
public static String get_Score(){
return DataHolder.Score;
}
}
To set score in DataHolder class, use below code from any fragment or activity.
String Score = ""; //get Score to this variable
DataHolder.set_Score(Score);
try using public static final key word if your value is not going to be changed through out the app else use public static before the var type that will remain accessible in all files with out instantiation and value could be initialized at any instance .
Example:
public static int score;
public static final int score=5;
Second way is by using sharedprefrences , you can get help from here .

Using methods across all activities in android

I know there are already some questions on global methods and variables in android but I'm running into problems with static methods probably due to my less experience with objectoriented programming. So here is what I want to have:
I am writing an app which counts points which the user can earn for certain things he does. Because of that I want to call the method addPoints from different activities and services. This method should also set the points textview in the main activity and some other things.
I realized it by adding a static variable
static int sPoints;
in the MainActivity, that I use as a "global" variable in each activity.
However, with the addPoints method I have some problems. If I use a non-static method, I have to create an instance of MainActivity in the other activities, which is not very nice and changing the values of that instance does not have an effect on the actual MainActivity.
If I use a static function it works fine as long as I don't want to use non-static methods like in this example:
public static void addPoints(Context context, int points){
int levelBefore, levelAfter;
levelBefore = getLevelFromPoints(sPoints);
sPoints = sPoints + points;
levelAfter = getLevelFromPoints(sPoints);
if(levelBefore!=levelAfter){
String rank = getRankFromLevel(levelAfter);
levelTextView.setText("Lvl. " + String.valueOf(levelAfter));
Toast.makeText(context, "Congrats! You reached the next level!", Toast.LENGTH_LONG).show();
}
}
Here I can't easily use levelTextView.setText and I run into this problem in many other cases. Moreover, I've read that using static methods is not good, anyway.
So would the correct way be creating an instance of MainActivity each time and then call addPoints on it which has to return the new number of points? Or is there another way (I hope so, because both above ways seem to be not very satisfying).
a. Static methods can safely be used in case your work can not be accomplished by ShardPreferences and requires the use of same code at multiple classes like in your case.
b. First create an interface that will pass the updated rank to respective activities or classes
public interface ScoreUpdater {
void updateScore (String rank);
}
c. then implement it in all activities where required to use, MainActivity in this case
public class MainActivity extends AppCompatActivity implements ScoreUpdater{
//
//other methods and codes
//
#Override
public void updateScore(String rank) {
runOnUiThread(new Runnable() {
#Override
public void run() {
levelTextView.setText("Lvl. " + String.valueOf(levelAfter));
Toast.makeText(MainActivity.this.getApplicationContext(), "Congrats! You reached the next level!", Toast.LENGTH_LONG).show();
}
});
}
}
d. then implement your static methods. not sure where you have declared few variables. so my method below is on guess work.
public static void addPoints(Context context, int points){
//not sure where you are declaring sPoints
int levelBefore, levelAfter;
levelBefore = getLevelFromPoints(sPoints);
sPoints = sPoints + points;
levelAfter = getLevelFromPoints(sPoints);
if(levelBefore!=levelAfter){
String rank = getRankFromLevel(levelAfter);
if(context instanceof ScoreUpdater){
((ScoreUpdater)context).updateScore(rank);
}
}
}
private static int getLevelFromPoints(int points){
//your operations
return points;
}

Public Variables in a Stand-Alone Program

I'm writing a small Java program that randomly deals out playing cards, then displays them on screen in a window.
Since I'm using NetBeans, the GUI was started for me, and I've been writing my methods for randomly choosing cards, setting up an array to store whether or not a card has already been dealt, etc., all in the same class NetBeans set up for me when it built the JFrame.
I'd like to move all my non-GUI code into its own Class, and then just pass data back to the GUI class as needed to display the cards, but I'm not sure of the best way to share data between the two classes.
I know about set/get methods and I know I could make public class-level variables, but everything I've been reading tells me to avoid both as much as possible.
Right now I have a method that generates an int between 1 and 52 for each card dealt. 1 = Ace of spades, 2= 2 of spades, etc. Once the GUI has that number, it can display the appropriate card in the appropriate place on the screen (or at least it will be able to once I've coded the GUI side of things). If I'm looking to pass that integer value to the GUI class, then display a specific card on the screen based on that value, how should I do it?
Seems to me a public variable would make this easy, as would a simple get method...but in the interest of avoiding those options is there another way?
I can provide code snippets if that helps.
Here's one way you could start to implement this idea using OO concepts.
Make a Card class to represent a card.
public class Card {
// FIELDS
// card name
private final String name;
// card value (number)
private final int value;
// another arbitrary value to demonstrate setter
private Object arbitraryValue;
public Card(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public Object getArbitraryValue() {
return this.arbitraryValue;
}
public void setArbitraryValue(Object arbitraryValue) {
this.arbitraryValue = arbitraryValue;
}
}
Create a CardManager class to hold methods that pertain to handling cards (e.g. utility methods and card data storage)
public class CardManager() {
private List<Card> cards = new ArrayList<Card>();
public void addCard(Card card) {
this.cards.add(card);
}
// and so on...your methods here.
}
Finally, create a class for your GUI (CardGUI) management and make use of the other classes to manage it.
You can do so like this:
public class CardGUI() {
public static void main(String[] args) {
// create your GUI and put your logic here...
// also use your other classes, perhaps like so.
Card card = new Card("One", 1);
CardManager cardManager = new CardManager();
cardManager.addCard(card);
// From there you can manage your cards through other classes.
}
Hope this helps / demonstrates how to share data between classes following standards.
Edit:
To answer your question on exactly how you would get the value, then see the above Card class. You would simple create a new card (Card card = new Card("name", intval);), then you would use the method Card#getValue() to get that value and display it in the GUI.

global variables between different classes java

i am on the creation of an app in android. its a calculator app. the main activity is where the user could input the equation, and the second activity is where the user can add/edit/delete variables. so i made a new class in another file named Global.java. then i extended it to application, imported everything i need, made s private string, made some public functions, edited the manifest, and initialized it right on my main activity. everything works fine while im only using a string to be passed by the functions but when i started adding what i need, an ArrayList, and made some functions so i could access the list then run it, the app closes. i think its because the arraylist is not allowed to be passed to different classes? am i right or am i just missing something?
please dont downvote my post if i didn't post something needed. i am using aide so there is no log output. code:
Global.java
...
import android.app.*;
import java.util.*;
public class Global extends Application
{
private String s;
public static ArrayList<String> sList;
public String getS() {
return s;
}
public void setS(String ss) {
s=ss;
}
public void add() {
sList.add(s);
}
}
MainActivity.java
...
String s;
...
global=(Global)getApplicationContext();
...
global.setS("jian"); //this one works
global.sList.add("jian"); // this one dont
...
Are you sure you initialized sList, like this:
sList = new ArrayList<String>();
If you didn't, you might want to change its declaration to include this initialization.
public static ArrayList<String> sList = new ArrayList<String>();
Just do
global.add("jian");
since you have an add function to take care of the addition of item to arraylist.
Also, try with this:
public void add(String ss) {
sList.add(ss);
}
You are not instantiating your arraylist.
public static ArrayList<String> sList = new Arraylist<String>();
Also you should read beginner tutorials on Java and android, using a public extension of application like this is a bad idea and you can get log outputs from different apps if Aide doesn't provide that, search play store

Passing a String Array Between Java Classes Android App

I am writing an Android app where I need to pass a string array between two classes. The string initializes fine and I can output the contents of the string fine in the one class but as I try to pass it to another class I get a Null Pointer Exception error. The following is the stripped down version of my code:
accelerometer.java:
public class accelerometer extends Service {
public String movement[];
public void onCreate() {
movement = new String[1000000];
}
public void updatearray() {
movement[arraypos]=getCurrentTimeString();
//Toast.makeText(this, movement[arraypos] , Toast.LENGTH_SHORT).show(); //this correctly displays each position in the array every time it updates so I know the array is working correctly in this file
arraypos+=1;
}
public String[] getmovement(){
return movement;
}
}
wakeupalarm.java:
public class wakeupalarm extends Activity {
private TextView herestext_;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wakeup);
herestext_ = (TextView) findViewById(R.id.TextView01);
accelerometer accelerometercall = new accelerometer();
String movearray[] = accelerometercall.getmovement();
herestext_.setText(movearray[2]);
}
}
I have a feeling I'm missing something very simple but any help would be greatly appreciated!
Thanks,
Scott
You're creating a new accelerometer class, which is completely uninitialized since there is no constructor, then you access its member. Of course it'll be null.
Not sure how your two classes are related, but if the activity is called by the service, then you need to pass the string through the intent (through an extra, for example).
Side note: Class names should always start with a capital letter. Method/variable names should have camel case, i.e. "updateArray". Also, you can format your code here by selecting it and pressing CTRL+K.
Your first problem, I think, is that you are creating an array with a million slots in it. Do you really mean to be doing that? It's going to take a lot of memory---quite possibly more than is available. You should instead look to having a Vector of Strings that you extend as necessary.

Categories