I am building a Fate Dice roller app for my finishing course in App Development and I am having a problem with changing the ImageView of the dice based on the result. Here is the code(the roller is in a fragment tab):
public class RollDiceFragment extends Fragment {
private Button btnRoll;
private EditText et_rollDice;
private ImageView iv_dice1, iv_dice2, iv_dice3, iv_dice4;
Random random;
public RollDiceFragment() {
}
public static RollDiceFragment newInstance() {
RollDiceFragment fragment = new RollDiceFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_rolldice, container, false);
random = new Random();
btnRoll = rootView.findViewById(R.id.btnRoll);
et_rollDice = rootView.findViewById(R.id.et_rollDice);
iv_dice1 = rootView.findViewById(R.id.iv_dice1);
iv_dice2 = rootView.findViewById(R.id.iv_dice2);
iv_dice3 = rootView.findViewById(R.id.iv_dice3);
iv_dice4 = rootView.findViewById(R.id.iv_dice4);
btnRoll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RollDiceFragment.this.rollDice();
}
});
return rootView;
}
private void rollDice(){
int d1 = this.random.nextInt(3) -1;
int d2 = this.random.nextInt(3) -1;
int d3 = this.random.nextInt(3) -1;
int d4 = this.random.nextInt(3) -1;
String print = (((BuildConfig.FLAVOR + addResult(d1)) + addResult(d2)) + addResult(d3)) + addResult(d4);
int diceSum = ((d1 + d2) + d3) + d4;
if (diceSum > 0){
this.et_rollDice.setText("+" + Integer.toString(diceSum));
}else {
this.et_rollDice.setText(Integer.toString(diceSum));
}
}
public String addResult(int i){
if (i == 1){
return "+";
}
if (i == 0){
return "0";
}
return "-";
}
}
The random roller works fine on the emulator and the result is shown in the editText line. I would just like the images to change based on the result of each dice. If a dice is showing a "-" the image shown should be diceminus.jpg.... Any help would be appreciated =)
The problem is that you are passing an int to setText method.
On the else case change it to using the setText overload with String as parameter:
this.et_rollDice.setText("" + Integer.toString(diceSum));
I found an answers so I will post it here in case somebody else needs the code one day =)
switch (d1){
case -1:
iv_dice1.setImageResource(R.drawable.diceminus);
break;
case 0:
iv_dice1.setImageResource(R.drawable.dicezero);
break;
case +1:
iv_dice1.setImageResource(R.drawable.diceplus);
break;
}
switch (d2){
case -1:
iv_dice2.setImageResource(R.drawable.diceminus);
break;
case 0:
iv_dice2.setImageResource(R.drawable.dicezero);
break;
case +1:
iv_dice2.setImageResource(R.drawable.diceplus);
break;
}
switch (d3){
case -1:
iv_dice3.setImageResource(R.drawable.diceminus);
break;
case 0:
iv_dice3.setImageResource(R.drawable.dicezero);
break;
case +1:
iv_dice3.setImageResource(R.drawable.diceplus);
break;
}
switch (d4){
case -1:
iv_dice4.setImageResource(R.drawable.diceminus);
break;
case 0:
iv_dice4.setImageResource(R.drawable.dicezero);
break;
case +1:
iv_dice4.setImageResource(R.drawable.diceplus);
break;
}
Related
if the first ad block is loaded -> stop checking and execute it -> if the first one is not loaded -> check the second one -> the second one is loaded -> stop checking -> the second one is not loaded -> check the third one .
Tried to execute through Switch case. Only the first block is executed. Please help me figure out what the problem is.
mDatabase = FirebaseDatabase.getInstance().getReference("Reklama");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// Switch between video ads and interstitial ads. if Reklama == 1 -> Interstitial / if Reklama == 2 -> Video.
int Reklama = Math.toIntExact((Long) snapshot.getValue());
//ad matching cycle
if (Reklama == 1) {
final int adUnit1 = 1;
final int adUnit2 = 2;
final int adUnit3 = 3;
int ReklamaInt = 1;
switch (ReklamaInt) {
case adUnit1:
mInterstitialAd.loadAd(adRequest);
break;
case adUnit2:
mInterstitialAdMid.loadAd(adRequest);
break;
case adUnit3:
mInterstitialAdLow.loadAd(adRequest);
break;
default:
throw new IllegalStateException("Unexpected value: " + ReklamaInt);
}
}
//ad matching cycle
else if (Reklama == 2) {
final int adUnit1 = 1;
final int adUnit2 = 2;
final int adUnit3 = 3;
int ReklamaReward = 1;
switch (ReklamaReward){
case adUnit1:
mRewardedAd.loadAd(adRequest);
break;
case adUnit2:
mRewardedAdMid.loadAd(adRequest);
break;
case adUnit3:
mRewardedAdLow.loadAd(adRequest);
break;
default:
throw new IllegalStateException("Unexpected value: " + ReklamaReward);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
I've only been writing code for a couple months and I'm still fairly newbie to a lot of techniques, but I'm working on a math training quiz for my 5 year old son. I've been trying to a few different "games" to play and challenge himself. I finished a time-trial yesterday, and a pattern match last week but now I'm stuck on the current game, which is a levels challenge. The player must answer 10 questions correctly to move to the next level (where the questions get harder).
I'm using a RecyclerView to create the questions. Each question is populated with random integers, and possible answers are selectable as RadioButtons.
So far I've been able to figure out how to add the formatting and update the ViewHolder, but now I'm stuck with trying to create a method in my Fragment to check for all questions answered. I believe that has to be done in the Fragment, since the Fragment is where I define how many questions to create and where the random numbers are generated and passed into the ArrayList that the Recycler Adapter uses to update the View Holder.
I hope that I'm explaining myself well enough, so my question is how can I check that all radiogroups meet the following parameters:
Has a selected radioButton
Is answered correctly (if they're answered incorrectly, they won't move to the next level, but instead will be given a new set of the same difficulty questions.
Here is my Fragment Class:
public class FragmentLevelChallenge extends Fragment{
public static final String TAG = "LevelChallengeFragment";
RecyclerView recyclerView;
RVAdapterMulti adapterMulti;
private List<multiquestion> QuestionsMulti;
int firstDig;
int secondDig;
int correctAnswer;
int incorrectOne;
int incorrectTwo;
int incorrectThree;
int thisPosition;
int selectedAnswers;
int questionsAnswered;
//levelChallenge defines the current challenge level
int levelChallenge;
int maxBound = 10;
int minBound = 1;
int adjustBound = 1;
RadioGroup radioGroupRecycler;
public static FragmentLevelChallenge newInstance() {
FragmentLevelChallenge fragment = new FragmentLevelChallenge();
return fragment;
}
#Override
public void onCreate (Bundle savedInstanceState) {super.onCreate(savedInstanceState);}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_level_challenge, container, false);
levelChallenge = 1;
QuestionsMulti = new ArrayList<>();
recyclerView = view.findViewById(R.id.recycler_view_display_multi);
radioGroupRecycler = view.findViewById(R.id.radio_group_multi);
LinearLayoutManager layoutManager = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(layoutManager);
TextView levelsText = view.findViewById(R.id.level_challenge);
levelsText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
initializeRecyclerAdapter();
createQuestionBatch();
return view;
}
private void createQuestionBatch() {
//Integer values to define the minimum, maximum and adjustment for random integers
if (selectedAnswers == 5) {
levelChallenge++;
}
//Checks the current level to determine the boundaries for difficulty of random integers
switch (levelChallenge) {
case 1: //If level 1 (bounds 10,1,1)
maxBound = 10;
minBound = 1;
adjustBound = 1;
break;
case 2: //If level 2 (bounds 20,1,4)
maxBound = 20;
minBound = 1;
adjustBound = 4;
break;
case 3: //If level 3 (bounds 25,10,5)
maxBound = 25;
minBound = 10;
adjustBound = 5;
break;
case 4: //If level 4 (bounds 30,10,7)
maxBound = 30;
minBound = 10;
adjustBound = 7;
break;
case 5: //If level 5 (bounds 50,10,9)
maxBound = 50;
minBound = 10;
adjustBound = 9;
break;
case 6: //If level 6 (bounds 75,10,15)
maxBound = 75;
minBound = 10;
adjustBound = 15;
break;
case 7: //If level 7 (bounds 100,10,18)
maxBound = 100;
minBound = 10;
adjustBound = 18;
break;
//If level 8 (bounds random integers?)
}
//Creates the random integers for math functions
int questionsToFillRecycler = 5;
for (int i = 0; i < questionsToFillRecycler; i++) {
final Random r = new Random();
Random position = new Random();
thisPosition = position.nextInt(4 - 1) + 1;
//Creates the array list for incorrect answers
firstDig = r.nextInt(maxBound - minBound) + adjustBound;
secondDig = r.nextInt(maxBound - minBound) + adjustBound;
if (firstDig < secondDig) {
correctAnswer = secondDig - firstDig;
incorrectOne = secondDig - firstDig - 1;
incorrectTwo = secondDig - firstDig + 2;
incorrectThree = (secondDig + firstDig) - 2;
} else {
correctAnswer = firstDig + secondDig;
incorrectOne = secondDig + firstDig - 2;
incorrectTwo = secondDig + firstDig + 1;
incorrectThree = (firstDig - secondDig) + 3;
}
//Convert integer to string values
String firstNumber = String.valueOf(firstDig);
String secondNumber = String.valueOf(secondDig);
String firstIncorrect = String.valueOf(incorrectOne);
String secondIncorrect = String.valueOf(incorrectTwo);
String thirdIncorrect = String.valueOf(incorrectThree);
String correct = String.valueOf(correctAnswer);
List<String> answers = new Vector<>();
answers.add(correct);
answers.add(firstIncorrect);
answers.add(secondIncorrect);
answers.add(thirdIncorrect);
Collections.shuffle(answers);
if (firstDig < secondDig) {
//Checks if 1st integer is less than 2nd integer
QuestionsMulti.add(new multiquestion(secondNumber, firstNumber, answers.get(0), "-", answers.get(1), answers.get(2), answers.get(3)));
} else if (firstDig > secondDig) {
//Checks if 1st integer is greater than 2nd integer
QuestionsMulti.add(new multiquestion(secondNumber, firstNumber, answers.get(0), "+", answers.get(1), answers.get(2), answers.get(3)));
} else {
//Checks if 1st integer is greater than 2nd integer
QuestionsMulti.add(new multiquestion(secondNumber, firstNumber, answers.get(0), "+", answers.get(1), answers.get(2), answers.get(3)));
}
//Updates the RecyclerView Adapter
adapterMulti.notifyDataSetChanged();
}
}
private void initializeRecyclerAdapter() {
adapterMulti = new RVAdapterMulti(QuestionsMulti);
recyclerView.setAdapter(adapterMulti);
}
}
And here is my RecyclerAdapter:
public class RVAdapterMulti extends RecyclerView.Adapter<RVAdapterMulti.ViewHolder> {
private static String TAG = "RadioMultiAdapter";
private LayoutInflater inflater;
private List<multiquestion> QuestionsMulti;
private int questionsAnswered;
private AdapterView.OnItemSelectedListener onSelect;
public RVAdapterMulti(List<multiquestion> QuestionMulti) {
this.QuestionsMulti = QuestionMulti;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_multi, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
multiquestion currentQuestion = QuestionsMulti.get(position);
holder.setFirstDigit(currentQuestion.firstNumber);
holder.setSecondDigit(currentQuestion.secondNumber);
holder.setMathFunction(currentQuestion.mathFunc);
holder.setOptions(currentQuestion, position);
}
#Override
public int getItemCount() {
if (QuestionsMulti == null) {
return 0;
} else {
return QuestionsMulti.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayoutContainer;
private TextView firstDigitView;
private TextView secondDigitView;
private TextView mathFunctionView;
private TextView mathAnswerView;
private RadioGroup radioGroupOptions;
private RadioButton radioButtonOne, radioButtonTwo;
private RadioButton radioButtonThree, radioButtonFour;
public ViewHolder(View itemView) {
super(itemView);
firstDigitView = itemView.findViewById(R.id.first_digit);
secondDigitView = itemView.findViewById(R.id.second_digit);
mathFunctionView = itemView.findViewById(R.id.math_function);
mathAnswerView = itemView.findViewById(R.id.math_answer);
radioGroupOptions = itemView.findViewById(R.id.radio_group_multi);
radioButtonOne = itemView.findViewById(R.id.radio_button_one);
radioButtonTwo = itemView.findViewById(R.id.radio_button_two);
radioButtonThree = itemView.findViewById(R.id.radio_button_three);
radioButtonFour = itemView.findViewById(R.id.radio_button_four);
}
public void setFirstDigit(String firstDigit) {
firstDigitView.setText(firstDigit);
}
public void setSecondDigit(String secondDigit) {
secondDigitView.setText(secondDigit);
}
public void setMathFunction(String mathFunction) {
mathFunctionView.setText(mathFunction);
}
public void setOptions(final multiquestion question, int position) {
radioGroupOptions.setTag(position);
radioButtonOne.setText(question.correct);
radioButtonTwo.setText(question.incorrectOne);
radioButtonThree.setText(question.incorrectTwo);
radioButtonFour.setText(question.incorrectThree);
if (question.mathFunc.equals("+")) {
question.correctSolution = Integer.parseInt(question.firstNumber) + Integer.parseInt(question.secondNumber);
} else {
question.correctSolution = Integer.parseInt(question.firstNumber) - Integer.parseInt(question.secondNumber);
}
if(question.isAnswered) {
radioGroupOptions.check(question.checkedId);
} else {
radioGroupOptions.check(-1);
}
radioGroupOptions.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int pos = (int) group.getTag();
multiquestion que = QuestionsMulti.get(pos);
que.isAnswered = true;
que.checkedId = checkedId;
radioGroupOptions.setClickable(false);
radioButtonOne.setClickable(false);
radioButtonTwo.setClickable(false);
radioButtonThree.setClickable(false);
radioButtonFour.setClickable(false);
questionsAnswered = questionsAnswered + 1;
mathAnswerView.setText(String.valueOf(question.correctSolution));
String radioOneText = String.valueOf(radioButtonOne.getText());
String radioTwoText = String.valueOf(radioButtonTwo.getText());
String radioThreeText = String.valueOf(radioButtonThree.getText());
String radioFourText = String.valueOf(radioButtonFour.getText());
switch (que.checkedId) {
case R.id.radio_button_one:
if(radioOneText.equals(String.valueOf(question.correctSolution))) {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorCorrect));
} else {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorIncorrect));
}
break;
case R.id.radio_button_two:
if(radioTwoText.equals(String.valueOf(question.correctSolution))) {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorCorrect));
} else {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorIncorrect));
}
break;
case R.id.radio_button_three:
if(radioThreeText.equals(String.valueOf(question.correctSolution))) {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorCorrect));
} else {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorIncorrect));
}
break;
case R.id.radio_button_four:
if(radioFourText.equals(String.valueOf(question.correctSolution))) {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorCorrect));
} else {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorIncorrect));
}
break;
}
}
});
}
}
}
Any help would be greatly appreciated.
The easiest way will be to keep track of correct answers in your QuestionMulti list (you should refactor that to camel case by convention). Add an attribute to your multiquestion (should be MultiQuestion) class called answeredCorrectly with a default value of false.
Then every time onCheckChanged is called, set the value at that position in the list and also loop through the list to check if every answer is correct.
I have just started to use android studio recently and currently I am working on a Roman Numeral Translator app. The app's interface looks like this: Application interface
The user will use the keypad to input a integer which will show up on the TextView shown above. When they hit the convert button it will take the integer they have entered and convert it (the program will be able to catch the input if contains a string or character). Then the app will reset the TextView to the result after the user hits the "convert" button.
Currently, my main activity contains the onClickListeners for the buttons and a separate translator method for the translations. My problem is with the "convert" button I'm not sure how to get the input from the translator method and set it as TextView when it finishes converting. Here is the sample of my code:
"Convert" button listener- `
convert.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
TextView numeralInput = (TextView) findViewById(R.id.textView);
String intValue = numeralInput.getText().toString();
try{
int integer = Integer.parseInt(intValue);
if (integer > 0 && integer <= 4999){
translator(integer);
}else{
numeralInput.setText("Please enter an integer between 0 and 4,999.");
}
}catch(NumberFormatException e){
numeralInput.setText("Invalid input try again.");
}
}
}
);
`
Translator Method- `
public static void translator(int integer) {
LinkedList<String> stack = new LinkedList<String>();
// if (integer > 0 && integer <= 4999) {
//ArrayList<Integer> placement = new ArrayList<Integer>();
int place = (int) Math.log10(integer);
for (int i = 0; i <= place; i++) {
//while(integer > 0){
//System.out.println(integer);
int placeOfValue = integer % 10;
//stack.push(placeOfValue);
//System.out.print(stack);
//System.out.print(placeOfValue +":" + i);
String placement = "";
switch (i) {
case 0:
placement = ones(placeOfValue);
break;
case 1:
placement = tens(placeOfValue);
break;
case 2:
placement = hundreds(placeOfValue);
break;
case 3:
placement = thousands(placeOfValue);
break;
default:
break;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
stack.push(placement);
}
integer = integer / 10;
//System.out.print(placement);
// System.out.println(placement.size());
//}
// for(int j = 0; j < placement.size(); j++){
// double tenthPower = Math.floor(Math.log10(placement.get(j)));
// double place = Math.pow(10, tenthPower);
// System.out.println(place);
//
// }
// }
while (!stack.isEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
System.out.print(stack.pop());
}
}
// } else {
// System.out.println("Please enter an integer between 0 and 4,999.");
// }
}
}
`
The other methods inside translator is like a library for the roman numerals each containing a numeral for each of the place values as shown below.
Thousands method- `
public static String thousands(int integer) {
String thouValue = "";
switch (integer) {
case 1:
thouValue = "M";
//System.out.print("M");
break;
case 2:
thouValue = "MM";
//System.out.print("MM");
break;
case 3:
thouValue = "MMM";
//System.out.print("MMM");
break;
case 4:
thouValue = "MMMM";
//System.out.print("MMMM");
break;
default:
thouValue = "";
break;
}
return thouValue;
}
`
Make your translator() method return a string which contains the final output.
So before the while statement in that method, declare a string such as
String result = null; and in the loop append the popped values to this variable like, result += stack.pop().
Now, the place where you call the translator(integer) method, do numeralInput.setText(translator(integer)) instead of translator(integer)
You need to make your TextView a class member and initialise it in your oncreate bundle, so that you can access the textview elsewhere in the activity.
TextView numeralInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
numeralInput = (TextView) findViewById(R.id.textView);
convert.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
String intValue = numeralInput.getText().toString();
try{
int integer = Integer.parseInt(intValue);
if (integer > 0 && integer <= 4999){
translator(integer);
}else{
numeralInput.setText("Please enter an integer between 0 and 4,999.");
}
}catch(NumberFormatException e){
numeralInput.setText("Invalid input try again.");
}
}
}
);
I have been scouring the internet for answers to my problem. I have found some good advice and have changed my original code, but I am yet to discover the answer to my initial problem.
I am trying to take string data from a series of Jtextfields and writing them to an arraylist, and then in turn taking the written data from the arraylist and transfering it to the same text fields.
public class Form extends javax.swing.JFrame {
public ArrayList<Personal> personalList;
public ArrayList<Business> businessList;
public ArrayList<Personal> displayPersonalList;
public ArrayList<Business> displayBusinessList;
public Form() {
initArrayLists();
}
private void initArrayLists(){
personalList = new ArrayList<Personal>();
businessList = new ArrayList<Business>();
displayPersonalList = new ArrayList<Personal>();
displayBusinessList = new ArrayList<Business>();
}
this is my submit button that writes to the arraylists.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if (contactTypeLabel.getText().equals("Personal Contact")){
Personal p = new Personal();
p.first = firstNameTF.getText();
p.last = lastNameTF.getText();
p.address = addressTF.getText();
p.s = stateTF.getText();
p.zip = zipTF.getText();
p.phone = phoneTF.getText();
p.email = emailTF.getText();
personalList.add(p);
Personal d = new Personal();
d.first = firstNameTF.getText();
displayPersonalList.add(p);
resetTextFields();
}else if (contactTypeLabel.getText().equals("Business Contact")){
Business b = new Business();
b.first = firstNameTF.getText();
b.last = lastNameTF.getText();
b.address = addressTF.getText();
b.s = stateTF.getText();
b.zip = zipTF.getText();
b.phone = phoneTF.getText();
b.email = emailTF.getText();
businessList.add(b);
Business d = new Business();
d.first = firstNameTF.getText();
displayBusinessList.add(d);
resetTextFields();
}
}
here is the code to change to display mode, with a combobox that should populate for accessing the arraylist to fill the textfields with selected data
private void displayPersonalButtonActionPerformed(java.awt.event.ActionEvent evt)
{
personalFieldViewer();
submitButton.setVisible(false);
displayComboBox.setVisible(true);
clearTextFields();
for (Object item : displayPersonalList) {
displayComboBox.addItem(item);
}
}
this is the code for the combobox action and code to fill the text fields
private void displayComboBoxActionPerformed(java.awt.event.ActionEvent evt)
{
int x;
switch (displayComboBox.getSelectedIndex()){
case 0:
for (x = 0; x < x + 8; x ++) {
switch (x){
case 0 :firstNameTF.setText(personalList.get(x).toString());
break;
case 1 :lastNameTF.setText(personalList.get(x).toString());
break;
case 2 :addressTF.setText(personalList.get(x).toString());
break;
case 3 :stateTF.setText(personalList.get(x).toString());
break;
case 4 :zipTF.setText(personalList.get(x).toString());
break;
case 5 :phoneTF.setText(personalList.get(x).toString());
break;
case 6 :dobTF.setText(personalList.get(x).toString());
break;
case 7 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
case 1:
for (x = 8; x < x + 8; x ++) {
switch (x){
case 8 :firstNameTF.setText(personalList.get(x).toString());
break;
case 9 :lastNameTF.setText(personalList.get(x).toString());
break;
case 10 :addressTF.setText(personalList.get(x).toString());
break;
case 11 :stateTF.setText(personalList.get(x).toString());
break;
case 12 :zipTF.setText(personalList.get(x).toString());
break;
case 13 :phoneTF.setText(personalList.get(x).toString());
break;
case 14 :dobTF.setText(personalList.get(x).toString());
break;
case 15 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
case 2:
for (x = 16; x < x + 8; x ++) {
switch (x){
case 16 :firstNameTF.setText(personalList.get(x).toString());
break;
case 17 :lastNameTF.setText(personalList.get(x).toString());
break;
case 18 :addressTF.setText(personalList.get(x).toString());
break;
case 19 :stateTF.setText(personalList.get(x).toString());
break;
case 20 :zipTF.setText(personalList.get(x).toString());
break;
case 21 :phoneTF.setText(personalList.get(x).toString());
break;
case 22 :dobTF.setText(personalList.get(x).toString());
break;
case 23 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
}
}
here are the classes that hold the variables for the arraylists.
public class Contacts {
public String first, last, address, s, zip, phone, email;
}
public class Personal extends Contacts{
public String dob;
}
public class Business extends Contacts{
public String title, organization;
}
when I alternately try to fill the arraylists with *.add(textfield.getText()); Java will not allow this as well as using variables first=firstNameTF.getText(); then *.add(first); I get the same error message...
Please try to refrain from being negative, and I have read the API regarding arraylists. Thank you.
Your arraylist declarations has type either Personal or Business. So these list cant add a string value. So when you say personalList.add(textfield.getText()); its actually trying to add String object to a list that can contain only Personal object.
Secondly the for loop inside displayComboBoxActionPerformed() method results in an infinite loop. for (x = 0; x < x + 8; x ++). Insted of having different for loops and switch statements you could do something like
private void displayComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
if(displayComboBox.getSelectedIndex() > -1){
int start = displayComboBox.getSelectedIndex() * 8;
for (int x = start; x < start + 8; x ++) {
firstNameTF.setText(personalList.get(x).toString());
}
}
}
I have made an android calculator, and I have added the +/- button to it recently. The problems I am facing is, firstly when I use it, and press the equal button, the app crashes. Moreover as soon as I click +/- button, the digits turn into a float value, and when I type any number the number value continues after the decimal. Example: I have 200 and I press +/- the number becomes 200.0 and when I type any number it becomes 200.01. How do I overcome this problem? Can someone please let me know what are the changes required in my code? Here it is.
Thank you. :)
public class MainActivity extends Activity {
Typeface font1, font2;
TextView tv1;
private EditText Scr; //textbox screen
private float NumberBf; //Save screen before pressing button operation;
private String Operation;
private ButtonClickListener btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
font1=Typeface.createFromAsset(getAssets(), "digits.ttf");
Scr=(EditText)findViewById(R.id.editText);
Scr.setTypeface(font1);
font2=Typeface.createFromAsset(getAssets(), "alexbrush.TTF");
tv1=(TextView)findViewById(R.id.textView1);
tv1.setTypeface(font2);
Scr = (EditText) findViewById(R.id.editText);
Scr.setEnabled(false);
btnClick = new ButtonClickListener();
int idList[] = {R.id.button0,R.id.button7, R.id.button1, R.id.button8,R.id.button9,R.id.button4,
R.id.button5,R.id.button6,R.id.button,R.id.button2,R.id.button3,R.id.buttonDot,
R.id.buttonMul,R.id.buttonDiv,R.id.buttonAdd,R.id.buttonSub,R.id.buttonC,
R.id.buttonEq, R.id.buttonSqrt, R.id.buttonsquare, R.id.buttonNp
};
for(int id:idList){
View v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void mMath(String str){
NumberBf = Float.parseFloat(Scr.getText().toString()); //save the screen
Operation = str; //save operation
Scr.setText("0"); //Clear screen
}
public void getKeyboard(String str){
String ScrCurrent = Scr.getText().toString();
if(ScrCurrent.equals("0"))
ScrCurrent = "";
ScrCurrent += str;
Scr.setText(ScrCurrent);
}
public void mResult(){
float NumAf = Float.parseFloat(Scr.getText().toString());
float result = 0;
if(Operation.equals("+")){
result = NumAf + NumberBf;
}
if(Operation.equals("-")){
result = NumberBf - NumAf;
}
if(Operation.equals("*")){
result = NumAf * NumberBf;
}
if(Operation.equals("/")){
result = NumberBf / NumAf;
}
Scr.setText(String.format("%10d", result));
}
public void fnSqrt(){
double Number = Double.parseDouble(Scr.getText().toString());
Number = Math.sqrt(Number);
Scr.setText(String.valueOf(Number));
}
public void fnSquare(){
float Number1 = Float.parseFloat(Scr.getText().toString());
Number1 = pow(Number1, 2);
Scr.setText(String.valueOf(Number1));
}
public void fnNp(){
float Number = Float.parseFloat(Scr.getText().toString());
Number = Number*(-1);
Scr.setText(String.valueOf(Number));
}
private float pow(float number1, int i) {
return number1*number1;
}
private class ButtonClickListener implements OnClickListener{
public void onClick(View v){
switch (v.getId()){
case R.id.buttonC: //Clear screen
Scr.setText("0");
NumberBf = 0;
Operation = "";
break;
case R.id.buttonAdd: //function Add
mMath("+");
break;
case R.id.buttonSub:
mMath("-");
break;
case R.id.buttonMul:
mMath("*");
break;
case R.id.buttonDiv:
mMath("/");
break;
case R.id.buttonEq:
mResult();
break;
case R.id.buttonSqrt:
fnSqrt();
break;
case R.id.buttonNp:
fnNp();
break;
case R.id.buttonsquare:
fnSquare();
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
}
Concerning your first problem: Do you get a nullpointer exception?
public void mResult(){
float NumAf = Float.parseFloat(Scr.getText().toString());
does not prevents your statement to try to turn a null String into a float which obviously will let your app crash. So include a mechanism to catch the null value before.
case R.id.buttonEq:
if (Scr.getText() != null)
mResult();
break;
I think this is the easiest way to prevent your mResult() from getting a null value.
For your second problem: It becomes a float because you do
float Number = Float.parseFloat(Scr.getText().toString());`
When you cast your 200 into a float it becomes 200.00 which will be returned as a string.
EDIT: I realized that you also have a dotButton (your code is really messy). The suggested alternative of course does not work with decimal numbers because it always casts your numbervalue. To prevent this behaviour maybe you can implement a simple if/else statement.
public void fnNp() {
if (Scr.getText().toString().contains(".")) {
float Number = Float.parseFloat(Scr.getText().toString());
Number = Number*(-1);
Scr.setText(String.valueOf(Number));
} else {
int number = Integer.parseInt(Scr.getText().toString());
Number = Number*(-1);
Scr.setText(String.valueOf(Number));
}
}
You need to do a if statement in mResult that checks whether the float has a absolute difference to a float of the int of the float , less than , say Float.MIN_VALUE , and then get the toString of the int of the float instead if it is.
Wrap the call Scr.setText( Float f) , in a function setScreenTextWithNumber(Number n)
and do the checking there.
If you just check for the decimal point, then 2.0000 / 2 = 1.000 if that is what you want.
Otherwise checking for significant differences makes a call that a number that is not significantly different from the nearest integer is an integer.