I am new to programming and started android few week back.
public class MainActivity extends AppCompatActivity {
int a,i,j,k;
/*char [][] s1= new char[][]
{
{'A','B','C','D'},
{'E','F','G','H'},
{'I','J','K','L'},
{'M','N','O','P'},
{'Q','R','S','T'},
{'U','V','W','X'},
{' ','Y','Z',' '}};*/
char [][] s2=new char[8][8];
char[][] s3=new char[8][8];
int[] getlist= new int[10];;
char choice,choice1;
int x,b,c,d;
String[] messageText = new String[10];
String[] messageEdit = new String[10];
public void letterNo(View view) { // Method to show screen for getting number of letters
setContentView(R.layout.displaylettersno);
}
public void getNumber(View view) { // Method to get Numbers of Letter
EditText et = (EditText) findViewById(R.id.editText);
String s = et.getText().toString();
x = Integer.parseInt(s);
if (x > 0 && x < 9) {
et.setText("");
} else {
Toast.makeText(getApplicationContext(), "Wrong Entery... Enter again", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.gettingcolumnno);
// Toast.makeText(getApplicationContext(),"Click on Column No in Which 1st Letter Appear",Toast.LENGTH_LONG).show();
TextView textView = (TextView) findViewById(R.id.textView8);
for (i = 0; i < x; i++){
textView.setText("Enter Column No. in which Your letters of name is
present:" );
}
}
public void buttondone(View view) {
EditText op = (EditText) findViewById(R.id.operator2);
String num = op.getText().toString();
for (i = 0; i < x; i++)
{
getlist[i] = Integer.parseInt(String.valueOf(op.getText()));
}
Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I want to develop a Name guess game
1- it will ask user to enter the no. of letters he thought
2- it will ask user to enter the column no in which his letter present ( i want this to run according to user enter the no of letter .
suppose user enter 4 digits and it will ask to enter the column no 4 times.
and similarly it has a edit box where user enter column no .
i am using for loop for this purpose but it only show 1 time i am stuck here for 1 week . help me if you understand what i am trying to do . following is my code
Done button has to be pressed number of letters time to get columns.
TextView textView = (TextView) findViewById(R.id.textView8);
int numberOfColumnsEntered = 0;
public void getNumber(View view) {
// get number logic then
textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
}
public void buttondone(View view) {
EditText op = (EditText) findViewById(R.id.operator2);
String num = op.getText().toString();
getlist[numberofColumnsEntered] = Integer.parseInt(num);
numberofColumnsEntered++;
textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
if(numberofColumnsEntered == x) {
Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
}
}
Related
First of all, I'm new to Android Studio. I'm currently trying to make a BMI calculator app where the user has to enter their weight and height and select the unit of measurement used for both. A Toast message (R.string.toastError) should pop up upon clicking a button if: (1-2) the EditText fields for weight and height are empty and (3) if the value of HeightInput is less than or equal to zero; else, the calculation should proceed.
The whole math part worked fine when I tested it, but when I left the fields blank, the app just crashes. The Toast pops up though when HeightInput = 0, but not when the EditText field for Weight is left empty at the same time. I think it's the way I wrote the 'if' statement that's giving me a problem.
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
Here's the whole code for reference:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// weight units spinner
final Spinner spinWeightUnit = (Spinner) findViewById(R.id.spinnerWeightUnit);
spinWeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> WeightList = ArrayAdapter.createFromResource(this, R.array.WeightUnits, android.R.layout.simple_spinner_item);
WeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinWeightUnit.setAdapter(WeightList);
// height units spinner
final Spinner spinHeightUnit = (Spinner) findViewById(R.id.spinnerHeightUnit);
spinHeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> HeightList = ArrayAdapter.createFromResource(this, R.array.HeightUnits, android.R.layout.simple_spinner_item);
HeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinHeightUnit.setAdapter(HeightList);
// calculate button
Button buttonCalculate = (Button) findViewById(R.id.buttonCalculate);
buttonCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
// weight conversion constant
if (finalWeightUnit.equals("kilograms")) {
constantWeight = 1.00;
} else {
constantWeight = 1 / 2.204623;
}
// height conversion constant
switch (finalHeightUnit) {
case "inches":
constantHeight = 0.0254;
break;
case "centimeters":
constantHeight = 0.01;
break;
case "feet":
constantHeight = 1 / 3.2808;
break;
default:
constantHeight = 1.00;
break;
}
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
I'd appreciate any help! Thanks!
Try below in if statement
if (editTextWeightInput.getText().toString().trim().isEmpty() || editTextHeightInput.getText().toString().trim().isEmpty() || HeightInput <= 0)
When you leave an EditText Empty the getString() function returns a null value. First you need to check for null in the if condition.
if (editTextWeightInput.getText() == null || editTextWeightInput.getText().toString().length() == 0 || HeightInput <= 0)
You need to validate your declaration code also.
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
if(TextUtil.isEmpty(editTextWeightInput.getText().toString())||TextUtil.isEmpty(editTextHeightInput.getText().toString())){
Toast.makeText(getApplicationContext(), R.string.toastError,
Toast.LENGTH_SHORT).show();
}else{
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
}
I want to take the depth input by the user and mathematically operate on it to obtain cost and then display it to the user. How do I go about doing that?(If didn't notice already, I don't know Java). Thanks.
private void estimateCost(View view){
EditText depth = findViewById(R.id.depth);
TextView cost = findViewById(R.id.cost);
String x = depth.getText().toString().trim();
cost.setText(x);
}
You need to parse your String obtained from EditText, then perform some operations.
private void estimateCost(View view){
EditText depth = findViewById(R.id.depth);
TextView cost = findViewById(R.id.cost);
String x = depth.getText().toString().trim();
// parse to a number, i.e. int
int depthValue = Integer.parseInt(x);
// calculate total cost
int totalCost = ...
cost.setText(String.valueOf(totalCost));
}
You can create a button to obtain the value. For example:
<Button
android:id="#+id/bt_calc"
android:text="calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Then you can catch the click event (put it inside onCreate method):
EditText depth = (EditText) findViewById(R.id.depth);
TextView cost = (TextView) findViewById(R.id.cost);
Button btCalc = (Button) findViewById(R.id.bt_calc);
int costValue;
btCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//in here you can
//get the depth from the EditText:
int depthValue = Integer.valueOf(depth.getText().toString());
//do the operations (example):
costValue = depthValue + 1;
//and display the cost in the TextView:
cost.setText(String.valueOf(costValue));
}
});
Good luck!
If your input contains letters as well you won't get int from it with Integer.parseInt()
Use this
int x = 0;
for (int i=0; i < str.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') continue;
x = x * 10 + c - '0';
}
private TextView info;
private EditText input;
private Button getInfo;
long answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInfo = (Button) findViewById(R.id.button1);
getInfo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
input = (EditText) findViewById(R.id.editText1);
String s2 = input.getText().toString();
long inputNumber = Integer.parseInt(s2);
for (int i = 0; i <= inputNumber; i++) {
answer = fibonacci(i);
}
input.setText(answer + "");
}
});
}
public static long fibonacci(long n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
I made a program which generates fibonacci series for the number I give input through edit text and display the output value in edittext .Issue is when I enter 30 it generates fibonacci series but when I enter 50 or 100 app does not respond and stops .
I think it is because you have a lot of calculation on UI thread.
Try calculate it in AssyncTask, for example.
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 made a program that computes the geometric mean and my program is already working but i have some sort of errors. Whenever i click the btnCalculate with an empty input in my inputValues my program stops working. how am I going to deal with this error? Thanks:)
final AutoCompleteTextView inputValues = (AutoCompleteTextView) findViewById(R.id.txt_input);
final TextView txtTotalNum = (TextView) findViewById(R.id.txt_totalNumber);
final TextView GeoMean= (TextView) findViewById(R.id.txt_GeoMean);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
});
Button btnclear = (Button)findViewById(R.id.btnclear);
btnclear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
inputValues.setText("");
txtTotalNum.setText("");
GeoMean.setText("");
}
You are getting errors because your code is trying to split on empty strings or null and then accessing values[] that really have no index at all. Just check if the string fetched by the EditText has a length>0.
#Override
public void onClick(View agr0) {
String fetchedValues = ( inputValues.getText().toString());
if(fetchedValues.length>0)
{
String []values = fetchedValues.split(",");
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
else
{
//alert the user that the field is empty
}
}
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
if(values !=NULL){
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
// try this
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
if(inputValues.getText().toString().length()>0){
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
});
Your program stops at
convertedValues[a] =Integer.parseInt(values[a]);
because for an empty input the split array has no values, so its length is 0. And when you try to access values[0]you get an ArrayIndexOutOfBoundsException.
Just check if the input is emty, before splitting it.
if(!inputValues.getText().toString().equals("")){
... // do your stuff
} else {
// show a message
}