I have these two methods:
one of which creates RadioButtons, gets their names from an arraylist and adds them to a togglegroup and Vbox
second that's supposed to get the name of the selected radiobutton and returns it as a string.
I keep getting nullpointerexception, even though the names print out normally...
private void radioButtons() {
for (int i = 0; i < kaudet.size() - 1; i++) {
RadioButton btn = new RadioButton();
String btnText = kaudet.get(i).getKausiID();
btn.setText(btnText);
System.out.println(btnText);
btn.setToggleGroup(contSeason);
vBoxSeasons.getChildren().add(btn);
}
}
private String kilpKausiget() {
String kausiID = "";
try{
RadioButton chk = (RadioButton)contSeason.getSelectedToggle();
kausiID = chk.getText();
System.out.println(kausiID);
}catch(Error e){
e.printStackTrace();
}
return kausiID;
}
The latter method worked fine, when I had hardcoded the names, but that doesn't really work with what I need.
Thank you in advance!
Related
I was trying to build a simple app that takes the plain text and no of lines as input and convert the plain text into cipher text using the rail fence ciphering technique. I was taking no of lines input from user and convert that string input into integer by casting. As i was doing it, it shows NumberFormatException. I wrote the casting line inside the try block and there after the scope of that variable is limited such that my encryption() method is not able to access it. What can i do as my onClick function is not producing the correct desired cipher text?
The button behaves like it was never clicked.
I have tried creating that variable outside the try block and then typecasting it inside the block, i also made that lines variable final as it was accessed within the class. Then it asked me to initialize the variable, I have done that also but it does not seems helping me.
Button decryptBtn, encryptBtn;
TextView hlWrld, encryptedText;
EditText noOfLines, plainText;
int lines;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
decryptBtn = findViewById(R.id.decryptBtn);
encryptBtn = findViewById(R.id.encrptBtn);
hlWrld = findViewById(R.id.hlwWorld);
encryptedText = findViewById(R.id.encryptedText);
noOfLines = findViewById(R.id.lineNo);
plainText = findViewById(R.id.plntxt);
final String plntxt = plainText.getText().toString();
final String noOflines = noOfLines.getText().toString();
int lines = 0;
try {
lines = Integer.parseInt(noOflines);
} catch (NumberFormatException e) {
}
final int finalLines = lines;
encryptBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
encryption(plntxt, finalLines);
}
});
}
public void encryption(String plntxt, int lines) {
boolean checkdown = false; // check whether it is moving downward or upward
int j = 0;
int row = lines; // no of row is the no of rails entered by user
int col = plntxt.length(); //column length is the size of string
char[][] a = new char[row][col];
// we create a matrix of a of row *col size
for (int i = 0; i < col; i++) { // matrix visiting in rails order and putting the character of plaintext
if (j == 0 || j == row - 1)
checkdown = !checkdown;
a[j][i] = plntxt.charAt(i);
if (checkdown) {
j++;
} else {
j--;
}
}
// visiting the matrix in usual order to get ciphertext
for (int i = 0; i < row; i++) {
for (int k = 0; k < col; k++) {
System.out.print(a[i][k] + " ");
}
System.out.println();
}
String en = "";
System.out.println("----------------------");
for (int i = 0; i < row; i++) {
for (int k = 0; k < col; k++) {
if (a[i][k] != 0)
en = en + a[i][k];
}
}
System.out.println(en); // printing the ciphertext
encryptedText.setText(en);
}
I expect the output to be a cipher text come to me as a result of setText() method that I have applied on my textView. But, nothing is happening at all.
I was taking no of lines input from user and convert that string input into integer by casting. As i was doing it ,it shows NumberFormatException.
That is because you're trying to read a string from an EditText with no input yet as integer which is not a valid number with the following code (see the comment):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// your view binding code with findViewById
// ...
// here you're trying to read the EditText value,
// but no user input yet because you've only inflate it before.
final String plntxt= plainText.getText().toString();
final String noOflines= noOfLines.getText().toString();
// the noOfLines is "", an empty string.
int lines = 0;
try {
// this raise an exception because empty string is not number.
lines = Integer.parseInt(noOflines);
}
catch (NumberFormatException e){
}
...
}
I have tried creating that variable outside the try block and then typecasting it inside the block, i also made that "lines" variable final as it was accessed within the class. then it ask me to initialize the variable, i have done that also but it does not seems helping me.
What you done is make more damage to your code because your making the variable value constant. Both the value of plntxt and noOflines will always be an "", empty string. So, your following code won't work:
final String plntxt= plainText.getText().toString();
final String noOflines= noOfLines.getText().toString();
...
final int finalLines = lines;
encryptBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// this won't work because plntxt is always empty string
// and finalLines is always invalid number.
encryption(plntxt, finalLines);
}
});
A simple fix can be done by moving all the text getter to the inside of your onClick method:
encryptBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String plntxt= plainText.getText().toString();
String noOflines= noOfLines.getText().toString();
int lines = 0;
try {
lines = Integer.parseInt(noOflines);
}
catch (NumberFormatException e){
}
encryption(plntxt, finalLines);
}
});
I am trying add an item listener to a checkbox to see if its been checked, and if it is, to be added to a list of SQL table names to be selected. Inversely, if it is not selected then remove it from the list. I cannot add a listener though to any checkbox because "they are not effitively final". What can I do/is there a better way to attack it?
My method:
public JPanel drawChecks(){
ArrayList<String> list = MainFrame.grabSQLTableNames();
int index = list.size();
int rows = 1;
while(index > 1){
rows++;
index = index - 3;
}
GridLayout c = new GridLayout(rows, 3);
JPanel panel = new JPanel(c);
JCheckBox check[] = new JCheckBox[list.size()];
for(int x = 0; x < list.size(); x++){
check[x] = new JCheckBox(list.get(x));
check[x].setVisible(true);
check[x].addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (check[x].getState == true){
//do something
}
}
});
panel.add(check[x]);
}
Get the source of the event using the getSource method of the ItemEvent
public void itemStateChanged(ItemEvent e) {
JCheckBox checkBox = (JCheckBox)e.getSource();
if ( checkBox.isSelected() ){
//do something
}
}
For future reference, please read the following for tips on posting code examples for asking questions on stack overflow: https://stackoverflow.com/help/mcve
I want to make a Hint button, so when I click on it, I want to delete two buttons from the list (answers list). Now I don't know how to do it,ho w to make the for loop on the button array, so I can make this buttons invisible.
public class ClassicMode extends Activity {//מהמשחק עצמו
String pic;//תמונה של הדגל
Button answer1;//תשובות
Button answer2;
Button answer3;
Button answer4;
Button hint;
TextView guess;
TextView numOfGuess;
TextView score;
TextView scorenum;
DatabaseHandler db = new DatabaseHandler(this);
String fn;
Guesses G;
Bitmap bm;
Score s;
Button [] b = new Button[4];
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
score =(TextView)findViewById(R.id.score);
scorenum =(TextView)findViewById(R.id.scorenum);
scorenum.setText(String.valueOf(s.score));
guess =(TextView)findViewById(R.id.guesses);
numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
hint =(Button)findViewById(R.id.hint);
Flags f = new Flags();
Random r = new Random();//הדגל שיבחר לשאלה
int num = r.nextInt(160);//Up
f = db.getFlag(num);//הצגת הדגל הרנדומלי שיצא
fn = f.getName().toString();
pic = f.getImage().toString();
pic_view(pic);//מעבר לפונקציה להשמת התמונה של הדגל במשחק
//מערך ארבע כפתורים כנגד ארבע תשובות
b[0] = (Button)findViewById(R.id.button1);
b[1] = (Button)findViewById(R.id.button2);
b[2] = (Button)findViewById(R.id.button3);
b[3] = (Button)findViewById(R.id.button4);
List<String>Answers=new ArrayList<String>();//מערך תשובות
Answers.add(f.getName().toString());//הוספת התשובה הנכונה
for(int i=1;i<4;i++)
{
num = r.nextInt(200);
String valToAdd1 = db.getFlag(num).getName().toString();
if(!Answers.contains(valToAdd1)){
Answers.add(valToAdd1);
}
}
/*num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());//הוספת 3 תשובות רנדומליות
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());*/
Collections.shuffle(Answers);//ערבוב התשובות
for(int i=0;i<Answers.size();i++)
{
b[i].setText(Answers.get(i));//השמת התשובות מהמהערך למערך הכפתורים
}
}//end of OnCreat
Now what I've done (there is the function check, which check if you answered correctly and the hint which I don't know how to make):
public void check(View v)
{
Log.d("yes", fn);
Button b = (Button)v;
String text = b.getText().toString();
if(text.equals(fn))
{
s.score+=5;
resetQuiz();
}
else
{
s.score-=5;
if(Guesses.numOfGuesses==1)
{
G.setNumOfGuesses(3);
finish();//כאשר מספר הניחושים
return;
}
Guesses.numOfGuesses--;
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
}
}
public void hint(View v)
{
G.numOfGuesses--;
for(int i=0;i<2;i++)
for(int j=0;j<4;j++)
{
if()
}
}
Note: this is {mostly} pseudocode
I suggest keeping two separate lists of your answers. Your Flag object already holds the correct answer. You need a list to keep track of the wrong answers (so we don't have to loop and check against each item every time). You also need a list of all of them together that you can shuffle and display.
I took a little bit of liberty making your variable names longer so they are more clear.
onCreate() {
...
btnHint.setOnClickListener(hintOnClickListener);
...
Flag f = db.getFlag(randomNum); // This is the real question & answer
List<String> wrongAnswers = new ArrayList<String>(3);
List<String> allAnswers = new ArrayList<String>(4);
// Loop 3 times for 3 random wrong answers
for (int i=0; i<=3; i++) {
randNum = r.nextInt(200);
String randWrongAnswer = db.getFlag(randNum).getName().toString();
if (! wrongAnswers.contains(randWrongAnswer)) {
wrongAnswers.add(randWrongAnswer);
}
}
allAnswers.add(f.getName().toString());
allAnswers.addAll(wrongAnswers);
Collection.shuffle(allAnswers);
...
}
I like to declare all my listeners separately further down in the code, to keep the OnCreate method clean and legible.
private OnClickListener hintOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
G.numOfGuesses--;
// Since you shuffled the 'allAnswers' before displaying to the screen,
// we can just pick the first 2 answers from wrongAnswers list
// and it will appear to be random to the user.
for (int i=0; i < buttons.length; i++) {
String buttonText = buttons[i].getText().toString();
if (buttonText.equals(wrongAnswers.get(0))
|| buttonText.equals(wrongAnswers.get(1))) {
buttons[i].setVisibility(View.INVISIBLE);
}
}
}
};
Edit: to add hint logic based on OP's comment.
I got an ArrayList:
ArrayList<CheckBox> swmsInfo = new ArrayList<CheckBox>();
and some checkboxes:
checkBoxCompany = createCheckBox(R.id.checkBoxCompany);
checkBoxName = createCheckBox(R.id.checkBoxName);
checkBoxPhone = createCheckBox(R.id.checkBoxPhone);
checkBoxAdress = createCheckBox(R.id.checkBoxAdress);
I want to get their values 0 or 1 if some of the checkboxes are checked or not , and when i got their values i want to put them into a array. My checkboxes are inside a array
ArrayList<CheckBox> boxes = new ArrayList<CheckBox>();
You can loop through the arraylist and get the value. Something like
for (int i = 0; i<boxes.size(); i++){
CheckBox cb = boxes.get(i);
if (cb.isChecked()){
System.out.println("checked");
//from here you can populate you array
}else{
System.out.println("not checked");
//from here you can populate you array
}
}
======= Edit after the comment =======
public class CheckBoxStatus{
CheckBox cb;
boolean blnIsChecked;
public CheckBoxStatus(CheckBox cb, boolean blnIsChecked){
this.cb = cb;
this.blnIsChecked = blnIsChecked;
}
public CheckBox getCheckbox(){
return this.cb;
}
public boolean getStatus(){
return this.blnIsChecked;
}
public boolean setStatus(boolean blnIsChecked){
this.blnIsChecked = blnIsChecked;
}
}
//Now in your code instead of ArrayList<CheckBox>, use ArrayList<CheckBoxStatus>
ArrayList<CheckBoxStatus> alCBS = new ArrayList<CheckBoxStatus>();
CheckBoxStatus cbs = new CheckBoxStatus(<checkbox instance>, false); //pass false as default value;
alCBS.add(cbs);
//Modified loop
for (int i = 0; i<boxes.size(); i++){
CheckBox cb = boxes.get(i);
CheckBoxStatus cbs = new CheckBoxStatus(cb, cb.isChecked());
boxes.set(i, cbs);
}
I have a program that takes an input file, pulls a color word + hexadecimal value from it (for exaple Red 0xFF0000). I had my code working perfectly except I tried to replace my 2 arrayLists with a HashMap... That is where things took a wrong turn. I have my code back to what I believe it was before except now it is NOT changing colors when the radio buttons are pushed. Anyone want to take a peek?
public HashMapTests() {
JPanel p1 = new JPanel();
this.getContentPane().setLayout(new GridLayout(5,4));
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < colorCollection.size(); i++) {
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
}
for(int i = 0; i < colorCollection.size(); i++){
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
for (int j = 0; j < colorCollection.size(); j++){
String hexColor = hexCollection.get(j);
if(hexCollection.get(j).equals(((JRadioButton)e.getSource()).getText())){
getContentPane().setBackground(Color.decode(hexColor));
repaint();
}
}
}
});
}
add(p1);
}
First investigation:
while (colorCollection.size() < 10)
shall be replaced with
if (colorCollection.size() < 10)
Second observation:
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
The second line is useless, see constructor's javadoc.
Third:
The second loop where you attach the listener is useless, you can put this code to the first loop where you create a button.
Finally:
if (hexCollection.get(j).equals(((JRadioButton) e.getSource()).getText())) {
You compare here content of hexCollection with radio button text, but the button has label from colorCollection. I cannot look to your file but I think that this will be the problem.
Map Solution:
Initialization
String name = fileInput.next();
String hexValue = fileInput.next();
colors.put(name, hexValue);
Buttons
int i = 0;
for (String s : colors.keySet()) {
jrbColor[i] = new JRadioButton(s);
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String hexColor = colors.get(((JRadioButton) e.getSource()).getText());
getContentPane().setBackground(Color.decode(hexColor));
}
});
}