package com.example.rami.androidstudio_312332604_guessgame;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
private String changeCharInPosition(int position, char ch, String str) {
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
private void start() {
TextView errortext = (TextView) findViewById(R.id.statustext);
Button button = (Button) findViewById(R.id.guessbt);
TextView tv = (TextView) findViewById(R.id.guessingtext);//get the textview from the activity
TextView testtext = (TextView) findViewById(R.id.testtext);//get the testview from the activity
EditText edittext = (EditText) findViewById(R.id.editText);
String[] world = getResources().getStringArray(R.array.words);// get the array from string xml
Random rand = new Random();
errortext.setText("");
int randomNum = rand.nextInt(world.length);
String country = world[randomNum];
String s = "";
for (int i = 0; i < country.length(); i++) {
if (country.charAt(i) != ' ')
s += '?';
else
s += ' ';
}
tv.setText(s);
testtext.setText(world[randomNum]);
button.setEnabled(true);
//Toast toast = Toast.makeText(getApplicationContext(), points, Toast.LENGTH_LONG);
//toast.show();
}
// Remove the below line after defining your own ad unit ID.
private static final String TOAST_TEXT = "Test ads are being shown. "
+ "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start();
Button button = (Button) findViewById(R.id.guessbt);
button.setOnClickListener(new View.OnClickListener() {
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
private void clear() {
ImageView img = (ImageView) findViewById(R.id.errorimg);
TextView errortext = (TextView) findViewById(R.id.statustext);
img.setImageResource(R.mipmap.error_num0);
counter = 6;
lettersguessed.clear();
errortext.setText("");
}
public void onClick(View v) {
EditText guessedtext = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.guessbt);
TextView questionstext = (TextView) findViewById(R.id.guessingtext);
TextView errortext = (TextView) findViewById(R.id.statustext);
if (guessedtext.getText().length() != 1) {//to make sure it's one char
Toast toast = Toast.makeText(getApplicationContext(), "Please Enter One Char", Toast.LENGTH_SHORT);
toast.show();
guessedtext.setText("");
return;
}
String country = ((TextView) findViewById(R.id.testtext)).getText().toString();
char uc = Character.toUpperCase(guessedtext.getText().charAt(0));
char lc = Character.toLowerCase(guessedtext.getText().charAt(0));
guessedtext.setText("");
if (lettersguessed.contains(uc)) {
Toast toast = Toast.makeText(getApplicationContext(), "You tried that before", Toast.LENGTH_SHORT);
toast.show();
return;
}
lettersguessed.add(uc);
boolean right = false;
for (int i = 0; i < country.length(); i++) {
char cc = country.charAt(i);
if (cc == uc || cc == lc) {
right = true;
questionstext.setText(changeCharInPosition(i, cc, questionstext.getText().toString()));
errortext.setText("You have guessed: " + lettersguessed.toString() + " (" + counter + " tries left)");
}
}
if (!right) {
if (counter == 1) {
Toast toast = Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_SHORT);
toast.show();
clear();
//points=-20;
return;
}
ImageView img = (ImageView) findViewById(R.id.errorimg);
counter--;
img.setImageResource(R.mipmap.error_num1);
errortext.setText("You have guessed: " + lettersguessed.toString() + " (" + counter + " tries left)");
}
if (questionstext.getText().toString().indexOf('?') < 0) {
Toast toast = Toast.makeText(getApplicationContext(), "Done it!", Toast.LENGTH_SHORT);
toast.show();
button.setEnabled(false);
clear();
//points += 20;
return;
}
}
});
Button newtb = (Button) findViewById(R.id.newbt);
newtb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
start();
}
});
Button giveupbt = (Button) findViewById(R.id.giveupbt);
giveupbt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Button button = (Button) findViewById(R.id.guessbt);
String country = ((TextView) findViewById(R.id.testtext)).getText().toString();
TextView guessedtext = (TextView) findViewById(R.id.guessingtext);
guessedtext.setText(country);
button.setEnabled(false);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
**These two variables, I want to reach or to make this class vars and reach them from the anonymous class. Because I want to read this and change their value
More info: the button is the guessing button for guessing countries names game and after entering the char into edittext you click this button to make your guess.
Any Ideas?
Just make these two variables as final and then access them in your inner class.
So it then becomes,
final ArrayList<Character> lettersguessed = new ArrayList<Character>();
final int[] counter = new int[1];
counter[0] = 6;
just replace counter by counter[0].
Related
Hello i have an android project ongoing at the moment. The user must answer a maths question then point should be awarded/taken away for the answer then the code should display a second different question until 10 questions have been completed. The problem is that the code skips the loop and instantly finishes the game. I have attempted using a while loop but the same problem happened. I thought about an if but couldn't work out how to re run the if. Below is the whole code of the project but the main problem is the for loop.
package com.example.mixmathsv3;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class SimpleModeActivity extends AppCompatActivity {
Button checkButt, nextQuestionButt;
TextView resultText, simpleQuestionText, scoreText, questionNumberText;
EditText userAnswer;
public volatile int completedTimes = 0;
public int scoreValue = 0;
public int intUserAnswer = 0;
public String questionAnswer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_mode);
resultText = (TextView) findViewById(R.id.result);
checkButt = (Button) findViewById(R.id.checkButt);
simpleQuestionText = (TextView) findViewById(R.id.simpleQuestionText);
scoreText = (TextView) findViewById(R.id.scoreText);
userAnswer = (EditText) findViewById(R.id.userAnswer);
//nextQuestionButt = (Button) findViewById(R.id.nextQuestion/Butt);
//questionNumberText = (TextView) findViewById(R.id.questionNumberText);
final String[] questionArray = {"5+2", "10+3", "7+1", "9+0", "1+6"};
final String[] answerArray = {"7", "13", "8", "9", "7"};
final Random r = new Random();
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
for (int i = 1; i < 11; i++) {
//System.out.println(i);
//Toast.makeText(getApplicationContext(), ("loop successful"), Toast.LENGTH_SHORT).show();
checkButt.setEnabled(true);
checkButt.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View v) {
checkButt.setEnabled(false);
intUserAnswer = Integer.parseInt(userAnswer.getText().toString());
int intQuestionAnswer = Integer.parseInt(questionAnswer);
if (intUserAnswer == intQuestionAnswer) {
resultText.setText("Correct");
scoreValue = scoreValue + 10;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes);
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
if (intUserAnswer != intQuestionAnswer) {
resultText.setText("Incorrect");
scoreValue = scoreValue - 5;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes)
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
}
});
}
Toast.makeText(getApplicationContext(), ("Game Over"), Toast.LENGTH_SHORT).show();
setOnClickListener does not do what you think :
setOnClickListener is used to register a method that will be called only if the user click on the button.
In your example, the for-loop register 10 times a new onClickListener which is not what we want.
In your case, you must not use the for-loop which is executed instantly. Change the question and the text when the user clicked on the button.
final String[] questionArray = {"5+2", "10+3", "7+1", "9+0", "1+6"};
final String[] answerArray = {"7", "13", "8", "9", "7"};
final Random r = new Random();
int answered = 0;
// Initial question
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
checkButt.setEnabled(true);
checkButt.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View v) {
checkButt.setEnabled(false);
intUserAnswer = Integer.parseInt(userAnswer.getText().toString());
int intQuestionAnswer = Integer.parseInt(questionAnswer);
if (intUserAnswer == intQuestionAnswer) {
resultText.setText("Correct");
scoreValue = scoreValue + 10;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes);
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
if (intUserAnswer != intQuestionAnswer) {
resultText.setText("Incorrect");
scoreValue = scoreValue - 5;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes)
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
answered++;// We update the count of answered question
if(answered == 10) {
// Finish
Toast.makeText(getApplicationContext(), ("Game Over"), Toast.LENGTH_SHORT).show();
} else {
// Change question
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
}
}
});
I suggest you to learn more about how Android is working and callback methods.
You don't need to put everything in the loop. Move all logic outside the loop and it should work.
Iam getting runtime error at Dialog fragment. At the Runtime of program works smoothly but when it comes to dialog appearence imes the program crashes........... Somebody show me where did the mistake I can't resolve my problem.
I am posting a LogCat Image because of body limit is crossed
MainActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
public static final String GUESSES = "settings_numberOfGuesses";
public static final String ANIMALS_TYPE = "settings_animalType";
public static final String QUIZ_BACKGROUND_COLOR = "settings_quiz_background_color";
public static final String QUIZ_FONT = "settings_quiz_font";
private boolean isSettingsChanged = false;
static Typeface azkiaDemo;
static Typeface chunkFive;
static Typeface fontleroyBrown;
static Typeface hauntedEyes;
static Typeface knightBrushDemo;
static Typeface wonderbarDemo;
MainActivityFragment myAnimalQuizFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
azkiaDemo = Typeface.createFromAsset(getAssets(),"fonts/Azkia demo.otf");
chunkFive = Typeface.createFromAsset(getAssets(),"fonts/Chunkfive.otf");
fontleroyBrown = Typeface.createFromAsset(getAssets(),"fonts/FontleroyBrown.ttf");
hauntedEyes = Typeface.createFromAsset(getAssets(),"fonts/Haunted Eyes.otf");
knightBrushDemo = Typeface.createFromAsset(getAssets(),"fonts/Knight Brush Demo.otf");
wonderbarDemo = Typeface.createFromAsset(getAssets(),"fonts/Wonderbar Demo.otf");
PreferenceManager.setDefaultValues(this, R.xml.quiz_preferences, false);
PreferenceManager.getDefaultSharedPreferences(this).
registerOnSharedPreferenceChangeListener(settingsChangedListener);
myAnimalQuizFragment = (MainActivityFragment) getSupportFragmentManager().findFragmentById(R.id.animalQuizFragment);
myAnimalQuizFragment.modifyAnimalGuessRows(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyTypeofAnimals(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyQuizFont(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyBackgroundColor(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.resetAnimalQuiz();
isSettingsChanged = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent preferencesIntent = new Intent(this,SettingsActivity.class);
startActivity(preferencesIntent);
return super.onOptionsItemSelected(item);
}
private SharedPreferences.OnSharedPreferenceChangeListener settingsChangedListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
isSettingsChanged = true;
if (key.equals(GUESSES)){
myAnimalQuizFragment.modifyAnimalGuessRows(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else if (key.equals(ANIMALS_TYPE)){
Set<String> animalTypes = sharedPreferences.getStringSet(ANIMALS_TYPE,null);
if (animalTypes != null && animalTypes.size() > 0){
myAnimalQuizFragment.modifyTypeofAnimals(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else {
SharedPreferences.Editor editor = sharedPreferences.edit();
animalTypes.add(getString(R.string.default_animal_type));
editor.putStringSet(ANIMALS_TYPE, animalTypes); // here we provided default value also.......
editor.apply();
Toast.makeText(MainActivity.this, R.string.default_animalType_message, Toast.LENGTH_SHORT).show();
}
}else if (key.equals(QUIZ_FONT)){
myAnimalQuizFragment.modifyQuizFont(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else if (key.equals(QUIZ_BACKGROUND_COLOR)){
myAnimalQuizFragment.modifyBackgroundColor(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}
Toast.makeText(MainActivity.this, R.string.toast_message , Toast.LENGTH_SHORT).show();
}
};
public void showDialog(){
ExampleDialog exampleDialog = new ExampleDialog();
exampleDialog.setCancelable(false);
exampleDialog.show(getFragmentManager(),"Animal_Quiz_Result");
}
}
Here is the MainActivityFragment.java class
import android.animation.Animator;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class MainActivityFragment extends Fragment {
public static final int NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ = 10;
private List<String> allAnimalsNameList;
private List<String> animalNamesQuizList;
private Set<String> animalTypesInQuiz;
private String correctAnimalsAnswer;
public static int numberOfAllGuesses;
private int numberOfAnimalGuessRows;
private int numberOfRightAnswers;
private SecureRandom secureRandomNumber;
private Handler handler;
private Animation wrongAnswerAnimation;
private LinearLayout animalQuizLinearLayout;
private TextView txtQuestionNumber;
private ImageView imgAnimal;
private LinearLayout[] rowsOfGuessButtonsInAnimalQuiz;
private TextView txtAnswer;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
allAnimalsNameList = new ArrayList<>();
animalNamesQuizList = new ArrayList<>();
secureRandomNumber = new SecureRandom();
handler = new Handler();
wrongAnswerAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.wrong_animation);
wrongAnswerAnimation.setRepeatCount(1);
animalQuizLinearLayout = view.findViewById(R.id.animalQuizLinearLayout);
txtQuestionNumber = view.findViewById(R.id.txtQuestionNumber);
imgAnimal = view.findViewById(R.id.imgAnimal);
rowsOfGuessButtonsInAnimalQuiz = new LinearLayout[3];
rowsOfGuessButtonsInAnimalQuiz[0] = view.findViewById(R.id.firstRowLinearLayout);
rowsOfGuessButtonsInAnimalQuiz[1] = view.findViewById(R.id.secondRowLinearLayout);
rowsOfGuessButtonsInAnimalQuiz[2] = view.findViewById(R.id.thirdRowLinearLayout);
txtAnswer = view.findViewById(R.id.txtAnswer);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz) {
for (int column = 0; column < row.getChildCount(); column++) {
Button btnGuess = (Button) row.getChildAt(column);
btnGuess.setOnClickListener(btnGuessListener);
btnGuess.setTextSize(24);
}
}
txtQuestionNumber.setText(getString(R.string.question_text, 1, NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ));
// getString is extends fragment...........
return view;
}
private View.OnClickListener btnGuessListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Button btnGuess = ((Button) view);
String guessValue = btnGuess.getText().toString();
String answerValue = getTheExactAnimalName(correctAnimalsAnswer);
++numberOfAllGuesses;
if (guessValue.equals(answerValue)) {
++numberOfRightAnswers;
txtAnswer.setText(answerValue + " ! " + " RIGHT");
disableQuizGuessButton();
if (numberOfRightAnswers == NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ) {
MainActivity mainActivity = new MainActivity();
mainActivity.showDialog();
} else {
handler.postDelayed(new Runnable() {
#Override
public void run() {
animateAnimalQuiz(true);
}
}, 1000); //1000 milliseconds for 1 second delay.......
}
} else {
imgAnimal.startAnimation(wrongAnswerAnimation);
txtAnswer.setText(R.string.wrong_answer_message);
btnGuess.setEnabled(false);
}
}
};
public static String getTheExactAnimalName(String animalName) {
return animalName.substring(animalName.indexOf('-') + 1).replace('_', ' ');
}// this method changes the actual name of image for example removes or starts after tame_animal- through index of method
// and after that removes _ between the names of animals...........
private void disableQuizGuessButton() {
for (int row = 0; row < numberOfAnimalGuessRows; row++) {
LinearLayout guessRowLinearLayout = rowsOfGuessButtonsInAnimalQuiz[row];
for (int buttonIndex = 0; buttonIndex < guessRowLinearLayout.getChildCount(); buttonIndex++) {
guessRowLinearLayout.getChildAt(buttonIndex).setEnabled(false);
}
}
}
public void resetAnimalQuiz() {
AssetManager assets = getActivity().getAssets();
allAnimalsNameList.clear();
try {
for (String animalType : animalTypesInQuiz) {
String[] animalImagePathsInQuiz = assets.list(animalType);
for (String animalImagePathInQuiz : animalImagePathsInQuiz) {
allAnimalsNameList.add(animalImagePathInQuiz.replace(".png", ""));
}
}
} catch (IOException e) {
Log.e("AnimalQuiz", "Error", e);
}
numberOfRightAnswers = 0; // this variable holds the right guesses must be 0 because we reset the game.
numberOfAllGuesses = 0; // this variable holds no. of all guesses whether it is right or wrong have to be 0.
animalNamesQuizList.clear(); // this variable holds randomly generated quiz paths must be 0 to generate new paths......
int counter = 1;
int numberOfAvailableAnimal = allAnimalsNameList.size();// this variable holds number of available animals or the size or length of paths
while (counter <= NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ) {
int randomIndex = secureRandomNumber.nextInt(numberOfAvailableAnimal);
String animalImageName = allAnimalsNameList.get(randomIndex);
if (!animalNamesQuizList.contains(animalImageName)) {
animalNamesQuizList.add(animalImageName);
++counter;
}
}
showNextAnimal();
}
private void animateAnimalQuiz(boolean animateOutAnimalImage) {
if (numberOfRightAnswers == 0) {
return;
}
int xTopLeft = 0;
int yTopLeft = 0;
int xBottomRight = animalQuizLinearLayout.getLeft() + animalQuizLinearLayout.getRight();
int yBottomRight = animalQuizLinearLayout.getTop() + animalQuizLinearLayout.getBottom();
//Here is max value for radius
int radius = Math.max(animalQuizLinearLayout.getWidth(), animalQuizLinearLayout.getHeight());
Animator animator;
if (animateOutAnimalImage) {
animator = ViewAnimationUtils.createCircularReveal(animalQuizLinearLayout, xBottomRight, yBottomRight, radius, 0);
animator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
showNextAnimal();
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
} else {
animator = ViewAnimationUtils.createCircularReveal(animalQuizLinearLayout, xTopLeft, yTopLeft, 0, radius);
}
animator.setDuration(700);
animator.start();
}
private void showNextAnimal() {
String nextAnimalImageName = animalNamesQuizList.remove(0);
correctAnimalsAnswer = nextAnimalImageName;
txtAnswer.setText("");
txtQuestionNumber.setText(getString(R.string.question_text, (numberOfRightAnswers + 1), NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ));
String animalType = nextAnimalImageName.substring(0, nextAnimalImageName.indexOf("-")); // it holds the animal type whether it is
// Tame animal or Wild Animal
AssetManager assets = getActivity().getAssets();
try (InputStream stream = assets.open(animalType + "/" + nextAnimalImageName + ".png")) {
Drawable animalImage = Drawable.createFromStream(stream, nextAnimalImageName);
imgAnimal.setImageDrawable(animalImage);
animateAnimalQuiz(false);
} catch (IOException e) {
Log.e("AnimalQuiz", "There is an Error Getting" + nextAnimalImageName, e);
}
Collections.shuffle(allAnimalsNameList); // this method is a predefined method in java which helps to shuffle the list of data
int correctAnimalNameIndex = allAnimalsNameList.indexOf(correctAnimalsAnswer);
String correctAnimalName = allAnimalsNameList.remove(correctAnimalNameIndex);
allAnimalsNameList.add(correctAnimalName);
for (int row = 0; row < numberOfAnimalGuessRows; row++) {
for (int column = 0; column < rowsOfGuessButtonsInAnimalQuiz[row].getChildCount(); column++) {
Button btnGuess = (Button) rowsOfGuessButtonsInAnimalQuiz[row].getChildAt(column);
btnGuess.setEnabled(true);
String animalImageName = allAnimalsNameList.get((row * 2) + column);
btnGuess.setText(getTheExactAnimalName(animalImageName));
}
}
int row = secureRandomNumber.nextInt(numberOfAnimalGuessRows);
int column = secureRandomNumber.nextInt(2);
LinearLayout randomRow = rowsOfGuessButtonsInAnimalQuiz[row];
String correctAnimalImageName = getTheExactAnimalName(correctAnimalsAnswer);
((Button) randomRow.getChildAt(column)).setText(correctAnimalImageName);
}
public void modifyAnimalGuessRows(SharedPreferences sharedPreferences){
final String NUMBER_OF_GUESS_OPTION = sharedPreferences.getString(GUESSES,null);
numberOfAnimalGuessRows = Integer.parseInt(NUMBER_OF_GUESS_OPTION)/2;
for (LinearLayout horizontalLinearLayout : rowsOfGuessButtonsInAnimalQuiz){
horizontalLinearLayout.setVisibility(View.GONE);
}
for (int row = 0; row < numberOfAnimalGuessRows; row++){
rowsOfGuessButtonsInAnimalQuiz[row].setVisibility(View.VISIBLE);
}
}
public void modifyTypeofAnimals(SharedPreferences sharedPreferences){
animalTypesInQuiz = sharedPreferences.getStringSet(ANIMALS_TYPE,null);
}
public void modifyQuizFont(SharedPreferences sharedPreferences){
String fontStringValue = sharedPreferences.getString(QUIZ_FONT,null);
switch (fontStringValue){
case "Chunkfive.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(chunkFive);
}
}
break;
case "Azkia demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(azkiaDemo);
}
}
break;
case "FontleroyBrown.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(fontleroyBrown);
}
}
break;
case "Haunted Eyes.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(hauntedEyes);
}
}
break;
case "Knight Brush Demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(knightBrushDemo);
}
}
break;
case "Wonderbar Demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(wonderbarDemo);
}
}
break;
}
}
public void modifyBackgroundColor(SharedPreferences sharedPreferences){
String backgroundColor = sharedPreferences.getString(QUIZ_BACKGROUND_COLOR,null);
switch (backgroundColor){
case "White":
animalQuizLinearLayout.setBackgroundColor(Color.WHITE);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.BLACK);
txtAnswer.setTextColor(Color.rgb(34,167,240));
break;
case "Black":
animalQuizLinearLayout.setBackgroundColor(Color.BLACK);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(247,202,24));
button.setTextColor(Color.BLACK);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
case "Green":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(38,166,91));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.rgb(247,202,24));
txtAnswer.setTextColor(Color.WHITE);
break;
case "Yellow":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(247,202,24));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.BLACK);
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.BLACK);
txtAnswer.setTextColor(Color.BLACK);
break;
case "Red":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(240,52,52));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
case "Blue":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(34,167,240));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(240,52,52));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
}
}
}
Here is the ExampleDialog.java class
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import static com.example.narayanmaity.app61animal_quiz.MainActivityFragment.numberOfAllGuesses;
/**
* Created by Narayan Maity on 12/14/2017.
*/
public class ExampleDialog extends DialogFragment {
MainActivityFragment myAnimalQuizFragment;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.results_string_value, numberOfAllGuesses,
(1000 / (double) numberOfAllGuesses)));
builder.setPositiveButton(R.string.result_animal_quiz, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myAnimalQuizFragment.resetAnimalQuiz();
}
});
return builder.create();
}
}
The problem is in this line.Remove the line below from your code
MainActivity mainActivity = new MainActivity();
mainActivity.showDialog();
You never ever create an Activity's instance with new operator. Its android Component class it initializes automatically with Intent . All Activities in android must go through a lifecycle so that they have a valid context attached to them. Read Activity.
The solution for this problem.
if(getActivity()!=null){
((MainActivity)getActivity()).showDialog()
}
For your new problem which you mentioned in comments.
You never assign myAnimalQuizFragment so it will give you NullPointerException anyway . Access it from your MainActivity.
((MainActivity)getActivity()).myAnimalQuizFragment.resetAnimalQuiz();
Make myAnimalQuizFragment as public in MainActivity.
Hi there i've been constructing this code for a week but i still cant get it to work. It has no errors but when i run it on the AVD it terminates suddenly.
package com.tryout.sample;
import java.util.Random;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements View.OnClickListener{
Random number = new Random();
int Low = 1;
int High = 13;
int RandomNumber = number.nextInt(High-Low) + Low;
int current = 0;
int points=0;
final Integer[] cardid = { R.drawable.card1,
R.drawable.card10,
R.drawable.card11,
R.drawable.card12,
R.drawable.card13,
R.drawable.card2,
R.drawable.card3,
R.drawable.card4,
R.drawable.card5,
R.drawable.card6,
R.drawable.card7,
R.drawable.card8,
R.drawable.card9,
};
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView score = (TextView) findViewById(R.id.textView2);
Button high = (Button) findViewById(R.id.button1);
Button low = (Button) findViewById(R.id.button2);
final ImageView pic = (ImageView) findViewById(R.id.imageView1);
low.setOnClickListener(new view.OnClickListener() {
public void onClick(View v) {
int resource = cardid[RandomNumber];
if(current < RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
high.setOnClickListener(new View.OnClickListener() {
public void higher(View v) {
int resource = cardid[RandomNumber];
if(current > RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
int resource = cardid[RandomNumber];
pic.setImageResource(resource);
current = RandomNumber;
}
}
I cant figure out where my problem is, kindly check out my code. THanks for any help
put this:
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
in you onCreate method after the call setContentView(R.layout.activity_main);.
How should R.id.imageView1 assigned if the content is not specified like in your case?
ImageView pic2;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic2 = (ImageView) findViewById(R.id.imageView1);
score = (TextView) findViewById(R.id.textView2);
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class minigame_cardpairing extends Activity implements View.OnClickListener {
private static final int TOTAL_CARD_NUM = 16;
private int[] cardId = {R.id.card01, R.id.card02, R.id.card03, R.id.card04, R.id.card05, R.id.card06, R.id.card07, R.id.card08,
R.id.card09, R.id.card10, R.id.card11, R.id.card12, R.id.card13, R.id.card14, R.id.card15, R.id.card16};
private Card[] cardArray = new Card[TOTAL_CARD_NUM];
private int CLICK_CNT = 0;
private Card first, second;
private int SUCCESS_CNT = 0;
private boolean INPLAY = false;
//----------- Activity widget -----------//
private Button start;
//-----------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.minigame_cardpairing);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for(int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i] = new Card(i/2);
findViewById(cardId[i]).setOnClickListener(this);
cardArray[i].card = (ImageButton) findViewById(cardId[i]); // Card assignment
cardArray[i].onBack();
}
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startGame();
//start.setBackgroundDrawable(background);
}
});
findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
} // end of onCreate
protected void startDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("The match-card game. Please remember to flip the cards two by two card hand is a pair Hit. Hit all pairs are completed.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Game Description");
alt2.show();
}
protected void clearDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("It fits all the cards in pairs. Congratulations.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Match-complete");
alt2.show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
startDialog();
}
public void onClick(View v) {
if (INPLAY) {
switch (CLICK_CNT) {
case 0:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
first = cardArray[i];
break;
}
}
if (first.isBack) {
first.onFront();
CLICK_CNT = 1;
}
break;
case 1:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
second = cardArray[i];
break;
}
}
if (second.isBack) {
second.onFront();
if (first.value == second.value) {
SUCCESS_CNT++;
Log.v("SUCCESS_CNT", "" + SUCCESS_CNT);
if (SUCCESS_CNT == TOTAL_CARD_NUM/2) {
clearDialog();
}
}
else {
Timer t = new Timer(0);
t.start();
}
CLICK_CNT = 0;
}
break;
}
}
}
void startGame() {
int[] random = new int[TOTAL_CARD_NUM];
int x;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (!cardArray[i].isBack)
cardArray[i].onBack();
}
boolean dup;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
while(true) {
dup = false;
x = (int) (Math.random() * TOTAL_CARD_NUM);
for (int j=0; j<i; j++) {
if (random[j] == x) {
dup = true;
break;
}
}
if (!dup) break;
}
random[i] = x;
}
start.setClickable(false);
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].card = (ImageButton) findViewById(cardId[random[i]]);
cardArray[i].onFront();
}
Log.v("timer", "start");
Timer t = new Timer(1);
//flag = false;
t.start();
/*
while(true) {
if (flag) break;
//Log.v("flag", "" + flag);
}
Log.v("timer", "end");
*/
SUCCESS_CNT = 0;
CLICK_CNT = 0;
INPLAY = true;
}
class Timer extends Thread {
int kind;
Timer (int kind) {
super();
this.kind = kind;
}
#Override
public void run() {
INPLAY = false;
// TODO Auto-generated method stub
try {
if (kind == 0) {
Thread.sleep(1000);
mHandler.sendEmptyMessage(0);
}
else if (kind == 1) {
Thread.sleep(3000);
mHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
INPLAY = true;
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0) {
first.onBack();
second.onBack();
first.isBack = true;
second.isBack = true;
}
else if (msg.what == 1) {
//flag = true;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].onBack();
}
start.setClickable(true);
}
}
};
}
class Card { // start of Card class
private final static int backImageID = R.drawable.cardback;
private final static int[] frontImageID = {R.drawable.card1, R.drawable.card2,
R.drawable.card3, R.drawable.card4,
R.drawable.card5, R.drawable.card6,
R.drawable.card7, R.drawable.card8};
int value;
boolean isBack;
ImageButton card;
Card(int value) {
this.value = value;
}
public void onBack() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
}
public void flip() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
else {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
public void onFront() {
if (isBack) {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
} // end of Card class
i have two arrays.
double number[] = new double[5];
char oper[] = new char[4];
in my program when user press any operator sign like +,-,*,/ the number array is taking user input for example if he is entering 345 it is taking and saving it in number[0] and [0] become [1] and also save the current operation input from user and save it in oper[0] and so on.
but i dont know how can i get the result using both arrays.
i am pasting whole code here.
package com.example.calculatortesting;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements OnClickListener {
TextView textdisplay;
EditText currentcalc;
EditText et1;
double number[] = new double[5]; //for saving numbers in array
char oper[] = new char[4]; //for saving operation in array
int numposition = 0; //for position of number array
int operposition = 0; //for position of operation array
double currentnum; //saving current number before operation
int last_button = 0; //checking last button pressed
char operator; //saving pressed operation value
String newnum = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
et1 = (EditText) findViewById(R.id.editText1);
textdisplay = (TextView) findViewById(R.id.editText1);
currentcalc = (EditText) findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
Button b3 = (Button) findViewById(R.id.b3);
Button b4 = (Button) findViewById(R.id.b4);
Button b5 = (Button) findViewById(R.id.b5);
Button b6 = (Button) findViewById(R.id.b6);
Button b7 = (Button) findViewById(R.id.b7);
Button b8 = (Button) findViewById(R.id.b8);
Button b9 = (Button) findViewById(R.id.b9);
Button b0 = (Button) findViewById(R.id.b0);
Button multiply1 = (Button) findViewById(R.id.multiply);
Button divide1 = (Button) findViewById(R.id.divide);
Button plus1 = (Button) findViewById(R.id.plus);
Button minus1 = (Button) findViewById(R.id.minus);
Button equal1 = (Button) findViewById(R.id.equal);
Button clear1 = (Button) findViewById(R.id.clear);
Button back1 = (Button) findViewById(R.id.backspace);
Button dot1 = (Button) findViewById(R.id.decimal);
Button plusminus1 = (Button) findViewById(R.id.plusminus);
Button percent = (Button) findViewById(R.id.percent);
Button shift = (Button) findViewById(R.id.shift);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
b7.setOnClickListener(this);
b8.setOnClickListener(this);
b9.setOnClickListener(this);
b0.setOnClickListener(this);
multiply1.setOnClickListener(this);
divide1.setOnClickListener(this);
plus1.setOnClickListener(this);
minus1.setOnClickListener(this);
equal1.setOnClickListener(this);
clear1.setOnClickListener(this);
back1.setOnClickListener(this);
dot1.setOnClickListener(this);
plusminus1.setOnClickListener(this);
percent.setOnClickListener(this);
shift.setOnClickListener(this);
}
public void currentcalcmethod(String currentcalcoper) {
currentcalc.setText(currentcalc.getText() + currentcalcoper);
currentcalc.setSelection(currentcalc.getText().length());
}
void number() {
}
void oper() {
number[numposition] = currentnum;
oper[operposition] = operator;
numposition ++;
operposition++;
currentnum= 0;
}
void result (){
double total;
StringBuilder builder = new StringBuilder();
for (double num : number) {
for (char op : oper){
builder.append(num + op);
total = num+op;
et1.setText(Double.toString(total));
}}
}
public void shownum(String number) {
newnum = newnum + number ;
currentnum = Double.parseDouble(newnum);
et1.setText(Double.toString(currentnum));
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.b0) {
currentcalcmethod("0");
shownum("0");
} else if (v.getId() == R.id.b1) {
currentcalcmethod("1");
shownum("1");
} else if (v.getId() == R.id.b2) {
currentcalcmethod("2");
shownum("2");
} else if (v.getId() == R.id.b3) {
currentcalcmethod("3");
shownum("3");
} else if (v.getId() == R.id.b4) {
currentcalcmethod("4");
shownum("4");
} else if (v.getId() == R.id.b5) {
currentcalcmethod("5");
shownum("5");
} else if (v.getId() == R.id.b6) {
currentcalcmethod("6");
shownum("6");
} else if (v.getId() == R.id.b7) {
currentcalcmethod("7");
shownum("7");
} else if (v.getId() == R.id.b8) {
currentcalcmethod("8");
shownum("8");
} else if (v.getId() == R.id.b9) {
currentcalcmethod("9");
shownum("9");
} else if (v.getId() == R.id.plus) {
currentcalcmethod("+");
operator = '+';
oper();
} else if (v.getId() == R.id.minus) {
currentcalcmethod("-");
operator = '-';
oper();
} else if (v.getId() == R.id.percent) {
currentcalcmethod("%");
operator = '%';
oper();
} else if (v.getId() == R.id.divide) {
currentcalcmethod("/");
operator = '/';
oper();
} else if (v.getId() == R.id.multiply) {
currentcalcmethod("*");
operator = '*';
oper();
} else if (v.getId() == R.id.decimal) {
currentcalcmethod(".");
} else if (v.getId() == R.id.equal) {
result ();
currentcalcmethod("=");
} else if (v.getId() == R.id.backspace) {
if (currentcalc.getText().toString().length() > 0) {
int start =0;
int end2 = currentcalc.getText().toString().length() - 1;
String newText2 = currentcalc.getText().toString()
.substring(start, end2);
currentcalc.setText(newText2);
}
} else if (v.getId() == R.id.clear) {
textdisplay.setText("");
currentcalc.setText("");
number = null;
oper = null;
numposition = 0;
operposition = 0;
} else if (v.getId() == R.id.plusminus) {
}
last_button = v.getId();
}
}
Take the user input as a String and parse it. Something like:
String userInput = "3+5";
List<Character> numbers = new ArrayList<>();
List<Character> operators = new ArrayList<>();
for (char c : userInput.toCharArray()) {
if(Character.isDigit(c)){
numbers.add(c);
}
else{
operators.add(c);
}
}
// Now loop through lists and perform the desired arthimetic operation based on operator
You could put all of the inputs into a String and convert the string to a double to get an actual equation.
String ans = Double.toString(number[0]) +
Char.toString(oper[0]) + Double.toString(number[1]); //could use a loop to enter all values != null
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript"); // build-in javascript engine allows for string equations.
try {
System.out.println(engine.eval(ans));
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Something like that.
My MainActivity.java file looks like this:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v)
{
EditText e1 = (EditText)findViewById(R.id.editText1);
String s = e1.toString();
double temp = Double.parseDouble(s);
double finalTemp = 0.0;
boolean checked = ((RadioButton) v).isChecked();
switch(v.getId())
{
case R.id.radio0 :
if(checked)
{
finalTemp = (temp * (9/5)) + 32;
}
case R.id.radio1 :
if(checked)
{
finalTemp = (temp - 32) * (5/9);
}
}
Toast.makeText(this, "The Converted Temperature is: " + finalTemp,Toast.LENGTH_LONG).show();
}
}
There are two radio buttons, and one is C to F another is F to C. The user will enter a double number and will check either of the boxes and will hit "convert" button and a toast message will appear with the converted temperature. But as soon as I am entering a value and hitting the convert button, the application is crashing.
I am new to android. Please help me. If possible give me some basic concepts of radio buttons and normal buttons. I am not new to java though.
Thanks...
You got your onClick() method all wrong. And also when getting string from EditText use edittext.getText().toString(). The way you took it will make your application crashes at this line double temp = Double.parseDouble(s);Try something like this.
public void onClick(View v)
{
EditText e1 = (EditText)findViewById(R.id.editText1);
String s = e1.getText().toString();
double temp = Double.parseDouble(s);
double finalTemp = 0.0;
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroupId);
int selectedId = radioGroup.getCheckedRadioButtonId();
switch(selectedId )
{
case R.id.radio0 :
finalTemp = (temp * (9/5)) + 32;
break;
case R.id.radio1 :
finalTemp = (temp - 32) * (5/9);
break;
}
Toast.makeText(this, "The Converted Temperature is: " + finalTemp,Toast.LENGTH_LONG).show();
}
And dont forget your break; in switch statements.
Or you can try this way:
public void onClick(View v)
{
EditText e1 = (EditText)findViewById(R.id.editText1);
String s = e1.getText().toString();
double temp = Double.parseDouble(s);
double finalTemp = 0.0;
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
if (celsiusButton.isChecked()) {
finalTemp = (temp * (9/5)) + 32;
} else {
finalTemp = (temp - 32) * (5/9);
}
}
Inside onClick method replace String s = e1.toString() with String s = e1.getText().toString() statement.
Move e1 inside on create method
EditText e1 = (EditText)findViewById(R.id.editText1);
In the onClick method for the button do
String s = e1.getText().toString();
Hope it helps.
use this code, may help you:
String s1=e1.getText().toString();
and check the s1.len>0
hit the button convert the answer otherwise the don't do anything....