I have a problem concerning setting a listener that would execute different action based on the clicked button.
The compiler doesn't detect any error on the syntax, but the problem is that when I simulate my app on the emulator, it pops up the window asking for "Force Close".
Here is my Java file :
package tp.imc.namespace;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class IMCCalculatorActivity extends Activity {
EditText poids,taille;
Button boutton1,boutton2;
TextView text1;
Boolean k=true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
poids=(EditText) findViewById(R.id.poids);
taille=(EditText) findViewById(R.id.taille);
boutton1 =(Button) findViewById(R.id.boutton1);
text1=(TextView) findViewById(R.id.text1);
boutton1.setOnClickListener(clicker);
boutton2.setOnClickListener(clicker);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener clicker = new View.OnClickListener(){
public void onClick (View v){
if( v == boutton1 )
{
String a,b;
Double r;
a=poids.getText().toString();
b=taille.getText().toString();
Double zero=Double.parseDouble(b);
a=poids.getText().toString();
b=taille.getText().toString();
if (zero==0)
{
text1.setText("Erreur ! Division par 0.");
}
else {
r=(Double.parseDouble(a))/(Double.parseDouble(b)*Double.parseDouble(b));
if (r<16.5) text1.setText("Famine.");
else if (r>16.5 && r<18.5) text1.setText("Maigreur.");
else if (r>=18.5 && r<25) text1.setText("Coplulence nomrale.");
else if (r>=25 && r<30) text1.setText("Surpoids.");
else if (r>=30 && r<35) text1.setText("Obésité modérée.");
else if (r>=35 && r<40) text1.setText("Obésité sévère.");
else if (r>=40) text1.setText("Obésité morbide ou massive.");
}
}
else if( v == boutton2 )
{
poids.setText("");
taille.setText("");
text1.setText("");
}
}
};
}
And here is my XML file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/poids"
android:textColor="#FF0000"
android:gravity="center"
/>
<EditText
android:id="#+id/poids"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/poids"
android:lines="1"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/taille"
android:textColor="#FF0000"
android:gravity="center"
/>
<EditText
android:id="#+id/taille"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/taille"
android:lines="1"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/metre"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/centimetre"
/>
</RadioGroup>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/mega"
android:checked="false"
/>
<Button
android:id="#+id/boutton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/compute" />
<Button
android:id="#+id/boutton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/raz" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/resultat"
/>
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/text"
/>
</LinearLayout>
You don't define boutton2, it is null. Add this:
boutton2 = (Button) findViewById(R.id.boutton2);
boutton2.setOnClickListener(clicker);
Since boutton1 and boutton2 don't have common code between them you could simply create two different listeners.
Lastly, this line doesn't look right.
if( v == boutton1 )
You are trying to compare a View to a Button which may not work. Try this:
if( v.getId() == boutton1.getId() )
Related
I'm currently making a very simple math game. In this math game I want the player to solve easy equations. It looks like this: 9 * __ = 45, the player then fill in the correct number to solve the equation and then presses a Correct-button. If correct scores are added to the player.
The empty space is an EditText and the others are TextViews. Because I use a mix of TextView & EditText I need somehow to make a convertion for the program to be able to read and calculate. I've been reading like crazy and tried all kinds of different methods without success. How should I do to get around this?
This is how my data looks like:
activity_play.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_play"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.android.laboration2.PlayActivity">
<TextView
android:id="#+id/textPlayMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textPlayNumber1"
android:layout_centerHorizontal="true"
android:text="#string/multiply"
android:textAlignment="textStart"
android:layout_gravity = "start"
android:textColor="#android:color/black"
android:textSize="40sp" />
<TextView
android:id="#+id/textPlayNumber1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textPlayScore"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textPlayScore"
android:layout_marginTop="48dp"
android:text="#string/number_1"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textPlayEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/equal"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp"
android:layout_below="#+id/editTextPlayNumber2"
android:layout_alignLeft="#+id/textPlayMultiply"
android:layout_alignStart="#+id/textPlayMultiply" />
<TextView
android:id="#+id/textPlayResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:text="#string/result_number3"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp"
android:layout_below="#+id/textPlayEqual"
android:layout_alignLeft="#+id/textPlayEqual"
android:layout_alignStart="#+id/textPlayEqual" />
<TextView
android:id="#+id/textPlayScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="31dp"
android:layout_toStartOf="#+id/answerButton"
android:text="#string/score_0"
android:textAlignment="textStart"
android:layout_gravity="start"
android:textColor="#android:color/black"
android:textSize="24sp"
android:layout_toLeftOf="#+id/answerButton" />
<Button
android:id="#+id/answerButton"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:background="#android:color/holo_orange_dark"
android:text="#string/button_result"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold"
android:layout_below="#+id/textPlayResult"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/editTextPlayNumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textPlayMultiply"
android:layout_alignBottom="#+id/textPlayMultiply"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:hint=" "
android:inputType="number"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textPlayLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textPlayScore"
android:layout_alignBottom="#+id/textPlayScore"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:text="#string/level_0"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="24sp" />
</RelativeLayout>
.
PlayActivity.java
package com.example.android.laboration2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PlayActivity extends AppCompatActivity implements View.OnClickListener {
TextView textPlayNumber1;
EditText editTextPlayNumber2;
TextView textPlayResult;
TextView textPlayScore;
TextView textPlayLevel;
Button answerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
textPlayNumber1 = (TextView) findViewById(R.id.textPlayNumber1);
editTextPlayNumber2 = (EditText) findViewById(R.id.editTextPlayNumber2);
textPlayResult = (TextView) findViewById(R.id.textPlayResult);
textPlayScore = (TextView) findViewById(R.id.textPlayScore);
textPlayLevel = (TextView) findViewById(R.id.textPlayLevel);
answerButton = (Button) findViewById(R.id.answerButton);
answerButton.setOnClickListener(this);
}//onCreate ends here
#Override
public void onClick(View v) {
}//onClick ends here
}//PlayActivity ends here
You can do
int playNumberValue = Integer.getInteger(textPlayNumber1.getText().toString());
int userInputValue = Integer.getInteger(editTextPlayNumber2.getText().toString());
int result = Integer.getInteger(textPlayResult.getText().toString());
if(result == userInputValue+playNumberValue)
//win game
Your TextView and EditText all have String type values. You have to parse those value to Integer then calculate and show the result.
Here is the action onClick answer button-
int score = 0;
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.answerButton:
int playNum1 = Integer.parseInt(textPlayNumber1.getText().toString());
int playNum2 = Integer.parseInt(editTextPlayNumber2.getText().toString());
int playResult = Integer.parseInt(textPlayResult.getText().toString());
if(playNum1*playNum2 == playResult){
score++;
textPlayScore.setText(""+score);
}
break;
}
}
Hope this helps.
I'm having a set of 9 radio Buttons(a group of 3 each),user has to select 3 (1 of each group)
on right selection a increment in score while on wrong selection decrement in score,but problem is that if all 3 correct ans are selected score is coming right else not ,also it is not responding to re selecting of another radio button of the group.On submit button i have written the code, I am new in development so kindly guide
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.qa:cb.setChecked(false);
cc.setChecked(false);
cd.setChecked(false);
s[0] = false;
break;
case R.id.qb:
ca.setChecked(false);
cc.setChecked(false);
cd.setChecked(false);
s[0] = false;
break;
case R.id.qc:
cb.setChecked(false);
ca.setChecked(false);
cd.setChecked(false);
s[0] = true;
break;
}
public void onClick(View v) {
score = 0;
for (int i = 0; i < 3; i++) {
if (s[i] == true)
score++;
else
score--;
}
where s is boolean s[] = new boolean[];
I am new in development so not able to sort out problem
The code sample below will add the radiobuttons dynamically to a group so that you can arrange the buttons in any way you like using any layouts.
Layout : main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1" >
<RadioButton
android:id="#+id/rbtn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="A" />
<RadioButton
android:id="#+id/rbtn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="B" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1" >
<RadioButton
android:id="#+id/rbtn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="C" />
<RadioButton
android:id="#+id/rbtn4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="D" />
</LinearLayout>
</LinearLayout>
Code : MainActivity.xml
public class MainActivity extends Activity {
private static final String GROUP_A = "GroupA";
private static final String GROUP_B = "GroupB";
private List<RadioButton> radioButtons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RadioButton rbtn1 = (RadioButton) findViewById(R.id.rbtn1);
RadioButton rbtn2 = (RadioButton) findViewById(R.id.rbtn2);
RadioButton rbtn3 = (RadioButton) findViewById(R.id.rbtn3);
RadioButton rbtn4 = (RadioButton) findViewById(R.id.rbtn4);
addRadioButtonToGroup(rbtn1, GROUP_A);
addRadioButtonToGroup(rbtn2, GROUP_A);
addRadioButtonToGroup(rbtn3, GROUP_A);
addRadioButtonToGroup(rbtn4, GROUP_B);
}
private void addRadioButtonToGroup(RadioButton rbtn, String group) {
rbtn.setTag(group);
if (radioButtons == null) {
radioButtons = new ArrayList<RadioButton>();
}
radioButtons.add(rbtn);
rbtn.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
for (int i = 0; i < radioButtons.size(); i++) {
RadioButton radioButton = radioButtons.get(i);
if (radioButton
.getTag()
.toString()
.equalsIgnoreCase(
buttonView.getTag().toString())) {
if (!radioButton.equals(buttonView)) {
radioButton.setChecked(false);
}
}
}
}
}
});
}
}
Here..First 3 radio buttons will belong to the group A and other to Group B, which makes sure one radio button in a group can be checked at a time. We also dont need the RadioGroup and this code gives the control to arrange Radio Buttons in anyway you like.
Use RadioGroup instead of checking and un checking the RadioButtons manually.
If You put 3 radio buttons in a radio group, you will be able to check a radio button at one time, RadioGroup will manage it.
Check the sample below : On Submit button click it will calculate the score.
layout : main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="First Question" />
<RadioGroup
android:id="#+id/rg1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rbtn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="A" />
<RadioButton
android:id="#+id/rbtn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B" />
<RadioButton
android:id="#+id/rbtn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="C" />
</RadioGroup>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Second Question" />
<RadioGroup
android:id="#+id/rg2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rbtn4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="P" />
<RadioButton
android:id="#+id/rbtn5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Q" />
<RadioButton
android:id="#+id/rbtn6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="R" />
</RadioGroup>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Third Question" />
<RadioGroup
android:id="#+id/rg3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rbtn7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="X" />
<RadioButton
android:id="#+id/rbtn8"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Y" />
<RadioButton
android:id="#+id/rbtn9"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Z" />
</RadioGroup>
<Button
android:id="#+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
</ScrollView>
Activity :
package com.example.demo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
private RadioGroup rg1;
private RadioGroup rg2;
private RadioGroup rg3;
private OnClickListener btnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
int answerCount = 0;
if (rg1.getCheckedRadioButtonId() == R.id.rbtn1)
answerCount++;
if (rg2.getCheckedRadioButtonId() == R.id.rbtn5)
answerCount++;
if (rg3.getCheckedRadioButtonId() == R.id.rbtn9)
answerCount++;
Toast.makeText(MainActivity.this, String.valueOf(answerCount),
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rg1 = (RadioGroup) findViewById(R.id.rg1);
rg2 = (RadioGroup) findViewById(R.id.rg2);
rg3 = (RadioGroup) findViewById(R.id.rg3);
Button btnSumbit = (Button) findViewById(R.id.btnSubmit);
btnSumbit.setOnClickListener(btnClickListener);
}
}
I am using two buttons, one for next news and one for previous news. In my activity when I am on the first news my button should set the image with the grey image and when I move forward my previous news button should change from the grey image to the colored one. Similarly when I reach at the last news my next button should change to grey image.
This is my xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFFFF"
>
<TextView
android:id="#+id/tv_submitDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Medium Text"
android:textColor="#000000"
android:padding="5dp"/>
<TextView
android:id="#+id/tv_headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_submitDate"
android:text="Medium Text"
android:textColor="#000000"
android:textStyle="bold"
android:padding="5dp"/>
<View
android:id="#+id/viewSeperator"
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_below="#+id/tv_headline"
android:background="#FF909090" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/btn_relative_layout"
android:layout_below="#+id/viewSeperator" android:padding="10dp">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_detailNews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textColor="#000000" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:id="#+id/btn_relative_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#DCDCDC"
android:padding="10sp" >
<Button
android:id="#+id/btn_prevNews"
android:layout_width="120sp"
android:layout_height="40sp"
android:layout_weight="0.5"
android:layout_marginRight="5sp"
android:background="#drawable/arrow_left"
android:clickable="true" />
<Button
android:id="#+id/btn_nextNews"
android:layout_width="120sp"
android:layout_height="40sp"
android:layout_marginLeft="5sp"
android:layout_weight="0.5"
android:background="#drawable/arrow_right"
android:clickable="true" />
</LinearLayout>
</RelativeLayout>
This is where I am trying to change the image of my button:
public void onClick(View v) {
if (v == btnPrevNews && newsId > 0) {
if (newsId > 0) {
newsId--;
putDetailNewsinView(newsId);
} else if (newsId == 0) {
btnPrevNews
.setBackgroundResource(R.drawable.disable_arrow_left);
btnPrevNews.setEnabled(false);
}
// btnPrevNews.setVisibility(View.INVISIBLE);
} else if (v == btnNextNews && newsId < newsListDetail.size() - 1) {
if (newsId < newsListDetail.size() - 1) {
newsId++;
putDetailNewsinView(newsId);
if(newsId == 0)
btnNextNews.setBackgroundDrawable(getResources().getDrawable(
R.drawable.disable_arrow_right));
} else if (newsId == newsListDetail.size()) {
// btnNextNews.setVisibility(View.INVISIBLE);
btnNextNews.setBackgroundDrawable(getResources().getDrawable(
R.drawable.disable_arrow_right));
// btnNextNews.setBackgroundResource(R.drawable.disable_arrow_right);
btnNextNews.setEnabled(false);
}
}
}
Please help me out in this.
Thanks in advance.
I assume you have Methods which will be executed if the Button is pressed. Just use these and add Logic to change the Background of these Buttons to grey:
Give both Buttons an ID, you can access these Buttons with:
Button mybutton = (Button) findViewById(R.id.yourid);
Now you can do all kinds of things with your button, like changing the background.
edit:
The Problem could lay in the Pictures, but if i were you, i would set some breakpoints and debug step-by-step.
I hacked some code of mine to test this functionality, it works fine for me. Here is it:
package my.namespac;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SomeTestProjectActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.btn_prevNews);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button)v;
v.setBackgroundDrawable(getResources().getDrawable(R.drawable.koala));
}
});
}
}
And the Layout-Xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn_prevNews"
android:layout_width="120sp"
android:layout_height="40sp"
android:layout_weight="0.5"
android:layout_marginRight="5sp"
android:background="#drawable/ic_launcher"
android:clickable="true" />
</LinearLayout>
I am trying to build a calculator for android, i am trying to multiply two numbers.
If i give number 1 and leave number 2 open, i want to get zero as an answer.
I first thought it could be the problem of not having a value for the double.
So i tried: if (Double.isNaN(number1)) { number1=0; }
But it did not work.
How do i make this happen?
R.layout.main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- 1 -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="number:" />
<EditText
android:id="#+id/number1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="number"
android:layout_marginLeft="20dp" />
</LinearLayout>
<!-- 2 -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="number:" />
<EditText
android:id="#+id/number2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="number"
android:layout_marginLeft="20dp" />
</LinearLayout>
<!-- multiply -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="multiply:" />
<TextView
android:id="#+id/multiplydisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="20dp" />
</LinearLayout>
<Button
android:id="#+id/btncalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"/>
<Button
android:id="#+id/btnreset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset" />
</LinearLayout>
TipcalcActivity.java
package com.tip.calc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class TipcalcActivity extends Activity {
private EditText number1;
private EditText number2;
private TextView multiplydisplay;
private Button btncalculate;
private Button btnreset;
private double number1calc = 0;
private double number2calc = 0;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
number1 = (EditText)findViewById(R.id.number1);
number2 = (EditText)findViewById(R.id.number2);
multiplydisplay = (TextView)findViewById(R.id.multiplydisplay);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ reset(); }});
}
private void calculate() {
number1calc=Double.parseDouble(number1.getText().toString());
number2calc=Double.parseDouble(number2.getText().toString());
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
}
private void reset() {
multiplydisplay.setText("");
number1.setText("");
number2.setText("");
}
}
you should just check that the content of the textfield of the value is different than "". If not, just assign the value 0.
In calculate :
private void calculate() {
number1calc=(number1.getText().toString() != "" ) ? Double.parseDouble(number1.getText().toString()) : 0;
number2calc=(number2.getText().toString() != "" ) ? Double.parseDouble(number2.getText().toString()) : 0;
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
}
if(numberOne.getText().toString().trim().length() < 1 || numberTwo.getText().toString().length() < 1){
multiplyDisplay.setText("0");
}
else{
//default handling
}
If the edittext is left blank, this is obviously not a number(NaN). Doing any operation with NaN in Java will cause the result of this operation to be NaN.
I searched net to find the answer for my following problem. But no answer found. I myself tried several ways, but I am still a novice at Android. What I found on net related to scrolling is official documentation and examples of scrolling on http://developer.android.com, Mr. Senthilkumar's How to scroll the screen, Kakka47's ScrollView only part of the screen, darrinps A scroll view with only part of the screen scrolling, etc.
This is very common requirement as is clear from above titles. I have following screen layout as shown in figure.
The screen from top to column titles is stable. The table records, below column titles needs to scroll. I have AbsoluteLayout (I know it is deprecated but that is the only one I can use for by specific need), inside it a scrollview and inside scrollview a TableLayout.
User clicks "Add" button to add the orders received. One order in one row. As rows increase, they go beyond visible area. Therefore, I want it to scroll so user can access it. But this part is not scrolling. I have given the listing of my code. Please tell me what to do.
Code:
package com.BookOrders;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//import android.widget.TableRow.LayoutParams;
#SuppressWarnings("deprecation")
public class BookOrders extends Activity implements ScrollViewListener{
/** Called when the activity is first created. */
private TextView BookingDateDisplay;
private Button ChangeDate, AddRec, DeleteRec, SaveAll;
private CheckBox SelectedAll, SelectedRec;
private ObservableScrollView CustomScroller = null;
private ObservableScrollView CustomScrolled = null;
private int ChangedYear;
private int ChangedMonth;
private int ChangedDay;
public Context CurrentContext, UsedContext;
static final int DATE_DIALOG_ID = 0;
int IdGenerator = 100000;
int Number_of_Records = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
#SuppressWarnings("deprecation")
final AbsoluteLayout main = (AbsoluteLayout)findViewById(R.id.widget0);
CurrentContext = main.getContext();
//final ScrollView ScrollControl = (ScrollView)findViewById(R.id.scroller);
//final AbsoluteLayout LayerControl = (AbsoluteLayout)findViewById(R.id.FinalLayer);
// UsedContext = LayerControl.getContext();
// capture our View elements
CustomScroller = (ObservableScrollView) findViewById(R.id.scrollContainer);
BookingDateDisplay = (TextView) findViewById(R.id.BookedDate);
ChangeDate = (Button) findViewById(R.id.pickDate);
AddRec = (Button) findViewById(R.id.AddRecord);
DeleteRec = (Button) findViewById(R.id.DeleteRecord);
SaveAll = (Button) findViewById(R.id.SaveRecord);
SelectedAll = (CheckBox) findViewById(R.id.SelectAll);
// add a click listener to the button
ChangeDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
AddRec.setOnClickListener(new View.OnClickListener() {
public void onClick(View AddRecView) {
IdGenerator = IdGenerator+10;
UsedContext = AddRecView.getContext();
TableRow Tr = new TableRow(UsedContext);
for (int controls=0; controls<6; controls++) {
if (controls==0){
CheckBox RecordCheck = new CheckBox(UsedContext);
RecordCheck.setId(IdGenerator+controls);
RecordCheck.setTag("CheckBoxTag");
RecordCheck.setHeight(20);
RecordCheck.setWidth(25);
Tr.addView(RecordCheck);
}
if ((0 < controls ) && (controls<5)){
Spinner Record = new Spinner(UsedContext);
Record.setId(IdGenerator+controls);
//Record.setMinimumHeight(20);
//Record.setMinimumWidth(90);
Tr.addView(Record);
}
if (controls==5){
EditText OrderQuantity = new EditText(UsedContext);
OrderQuantity.setId(IdGenerator+controls);
//OrderQuantity.setHeight(20);
//OrderQuantity.setWidth(90);
Tr.addView(OrderQuantity);
}
}
TableLayout Orders = (TableLayout)findViewById(R.id.OrderData);
Orders.addView(Tr);
// Scrolls to line before last - why?
final ScrollView ScrollAttempt = (ScrollView) findViewById(R.id.scrollContainer);
ScrollAttempt.post(new Runnable() {
public void run() {
ScrollAttempt.fullScroll(View.FOCUS_DOWN);
}
});
Number_of_Records = Number_of_Records + 1;
}
});
// updates the date in the TextView
private void updateDisplay() {
BookingDateDisplay.setText(
new StringBuilder()
.append(ChangedDay).append("-")
.append(ChangedMonth + 1).append("-") // Month is 0 based so add 1
.append(ChangedYear).append(" "));
}
// the call back received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener DateSetListener =
new DatePickerDialog.OnDateSetListener(){
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
ChangedYear = year;
ChangedMonth = monthOfYear;
ChangedDay = dayOfMonth;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, DateSetListener, ChangedYear, ChangedMonth, ChangedDay);
}
return null;
}
public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
if(scrollView == CustomScroller) {
CustomScrolled.scrollTo(x, y);
} else if(scrollView == CustomScrolled) {
CustomScroller.scrollTo(x, y);
}
}
}
My main.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget0"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<!-- <ImageButton android:text="Date" android:layout_height="20px" android:layout_width="32px" android:id="#+id/BDate" android:layout_x="274dip" android:layout_y="51dip"></ImageButton> -->
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="81dip"
android:layout_y="10dip"
android:background="#0ff0ff"
android:gravity="center"
android:text="Order Booking"
android:textColor="#330000"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" >
</TextView>
<TextView
android:id="#+id/BDate_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="277dip"
android:layout_y="52dip"
android:gravity="right"
android:text="Booked on:"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/BookedDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="350dip"
android:layout_y="52dip"
android:text=""
android:textSize="12sp" >
</TextView>
<Button
android:id="#+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="400dip"
android:layout_y="15dip"
android:text="Change Date"
android:textSize="10sp" >
</Button>
<View
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_y="68dp"
android:background="#drawable/gradient" >
</View>
<Button
android:id="#+id/AddRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="10dip"
android:layout_y="71dip"
android:text="Add"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/DeleteRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="140dp"
android:layout_y="71dp"
android:text="Delete"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/ClearRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="270dp"
android:layout_y="71dp"
android:text="Clear"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/SaveRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="400dp"
android:layout_y="71dp"
android:text="Save"
android:textSize="10sp" >
</Button>
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_y="110dp"
android:background="#drawable/gradient" >
</View>
<CheckBox
android:id="#+id/SelectAll"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_x="10dip"
android:layout_y="115dip"
android:text="Select All"
android:textSize="10sp" >
</CheckBox>
<TextView
android:id="#+id/Company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="95dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Company"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="200dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Product"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="300dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Code"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Model"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="380dp"
android:layout_y="115dp"
android:background="#666666"
android:text="Model"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="470dp"
android:layout_y="115dp"
android:background="#666666"
android:text="Quantity"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<View
android:id="#+id/view1"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_x="0dip"
android:layout_y="134dip"
android:background="#drawable/gradient" >
</View>
<com.BookOrders.ObservableScrollView
android:id="#+id/scrollContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_x="1dp"
android:layout_y="140dp"
android:clickable="true"
android:fadeScrollbars="false"
android:fillViewport="true" >
<TableLayout
android:id="#+id/OrderData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="0,1,2,3,4" />
</com.BookOrders.ObservableScrollView>
</AbsoluteLayout>
Have you tried a ScrollView? You can find more about ScrollView here
Here is an example of how to use ScrollView:
<ScrollView
android:id="#+id/coupons_details_scroll_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!--You can nest any other views here, and they will be scrollable, but take care of views that have their own scrolling capabilities like ListView -->
</ScrollView>
Good luck with it :)
I worked out the solution for this. For those who would like to know can first go through the following link
http://blog.stylingandroid.com/archives/447
I used this logic. However, I create rows dynamically when user clicks "Add" button. The only problem is, if you use spinner you won't be able to set its height zero.
Nitin