So I have 2 edittext fields which to me look the same in my android project.
They are both for decimals.
However the KM one keeps bringing up a keyboard with the option of entering letters and doesn't let me close the keyboard.
The Miles one opens up a number only keyboard and has a checkmark which lets me close the keyboard.
Wondering if something in the code is making this happen
I have added images below
package a00891437.set3s.comp3975.convertunits;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioGroup;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onRadioButtonClicked(final View view){
EditText mText = (EditText) findViewById(R.id.MilesText);
EditText kmText = (EditText) findViewById(R.id.KilometersText);
mText.setText("");
kmText.setText("");
if(view.getId()== R.id.KmToMButton) {
mText.setEnabled(false);
kmText.setEnabled(true);
}
if(view.getId() == R.id.MToKmButton){
kmText.setEnabled(false);
mText.setEnabled(true);
}
}
public void onClickedText (final View view){
EditText kilometers = (EditText) findViewById(R.id.KilometersText);
EditText miles = (EditText) findViewById(R.id.MilesText);
double km= 0;
double m = 0;
if(kilometers.isEnabled() == true){
km = Double.parseDouble(kilometers.getText().toString());
m = km * 0.621371;
miles.setText(Double.toString(m));
}
if(miles.isEnabled() == true){
m = Double.parseDouble(miles.getText().toString());
km = m * 1.60934;
kilometers.setText(Double.toString(km));
}
}
}
XML :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:id="#+id/screen">
TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="110dp"
android:onClick="onClickedText"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/KilometersText"
android:layout_above="#+id/button"
android:layout_marginBottom="134dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:enabled="false"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/MilesText"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/KilometersText"
android:layout_alignStart="#+id/KilometersText"
android:enabled="false"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Km"
android:id="#+id/Kilometers"
android:layout_alignTop="#+id/KilometersText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="43dp"
android:layout_marginStart="43dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="M"
android:id="#+id/Miles"
android:layout_alignTop="#+id/MilesText"
android:layout_alignRight="#+id/Kilometers"
android:layout_alignEnd="#+id/Kilometers" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/radio_group">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kilometers to Miles"
android:id="#+id/KmToMButton"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/MToKmButton"
android:layout_alignStart="#+id/MToKmButton"
android:checked="false"
android:onClick="onRadioButtonClicked"/>/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Miles to Kilometers"
android:id="#+id/MToKmButton"
android:layout_below="#+id/KmToMButton"
android:layout_alignLeft="#+id/Kilometers"
android:layout_alignStart="#+id/Kilometers"
android:checked="false"
android:onClick="onRadioButtonClicked"/>/>
</RadioGroup>
</RelativeLayout>
Also had this problem once where the EditTexts didn't seem to listen to the XML. this fixed it for me:
kmText.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
Related
So I am making an app for an assignment.
Basically convert Miles to KM or KM to Miles.
I've now got the radio buttons working but when I add the onclick event, upon clicking the edittext fields I get an exception. :
java.lang.IllegalArgumentException:
Expected receiver of type a00891437.set3s.comp3975.convertunits.MainActivity,
but got android.support.v7.internal.widget.TintContextWrapper
Here is the code
package a00891437.set3s.comp3975.convertunits;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onRadioButtonClicked(final View view) {
View mText = findViewById(R.id.MilesText);
View kmText = findViewById(R.id.KilometersText);
if (view.getId() == R.id.KmToMButton) {
mText.setEnabled(false);
kmText.setEnabled(true);
}
if (view.getId() == R.id.MToKmButton) {
kmText.setEnabled(false);
mText.setEnabled(true);
}
}
public void onClickedText(final View view) {
Log.d("MainActivity", "Clicked");
}
}
The layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:id="#+id/screen">
TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="110dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/KilometersText"
android:layout_above="#+id/button"
android:layout_marginBottom="134dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:enabled="false"
android:onClick="onClickedText"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/MilesText"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/KilometersText"
android:layout_alignStart="#+id/KilometersText"
android:enabled="false"
android:onClick="onClickedText"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Km"
android:id="#+id/Kilometers"
android:layout_alignTop="#+id/KilometersText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="43dp"
android:layout_marginStart="43dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="M"
android:id="#+id/Miles"
android:layout_alignTop="#+id/MilesText"
android:layout_alignRight="#+id/Kilometers"
android:layout_alignEnd="#+id/Kilometers" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kilometers to Miles"
android:id="#+id/KmToMButton"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/MToKmButton"
android:layout_alignStart="#+id/MToKmButton"
android:checked="false"
android:onClick="onRadioButtonClicked"/>/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Miles to Kilometers"
android:id="#+id/MToKmButton"
android:layout_below="#+id/KmToMButton"
android:layout_alignLeft="#+id/Kilometers"
android:layout_alignStart="#+id/Kilometers"
android:checked="false"
android:onClick="onRadioButtonClicked"/>/>
</RadioGroup>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="59dp"
android:layout_marginStart="59dp" />
</RelativeLayout>
You are specifying the onClick event method through XML, and it looks like this does not work with support library AppCompatActivity.
You should just get the reference to the EditText and call setOnClickListener().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText kilometers = (EditText) findViewById(R.id.KilometersText);
kilometers.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onClickedText(v);
}
});
// repeat this for the miles EditText
// you'll need to add an id for the radio group for this to work:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangedListener(new RadioGroup.OnCheckedChangedListener() {
// I leave the code inside here for you to do as an exercise
});
}
I have this activity with EditViews and button. When the button is pressed I move on to a new activity. the problem is when the back button is pressed. The EditViews are not visible. What is expected is that the views and the text that was entered are visible. Also The buttons that appear are from the second activity and not the first.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.ammar.android.dailyjobsiteinspection2.MainActivity1Activity">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="350dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/scrollView">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/linearLayout">
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:visibility="invisible" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText"
android:layout_gravity="center"
android:hint="Inspector ID"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:visibility="invisible" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText2"
android:layout_gravity="center"
android:hint="Site Name" />
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal"
android:visibility="invisible"
android:layout_weight="1" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText3"
android:layout_gravity="center"
android:hint="Site Address" />
<Button
android:layout_width="160dp"
android:layout_height="60dp"
android:text="Start"
android:id="#+id/button3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:onClick="start"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Here is the Java code:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity1Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
}
#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_activity1, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void start(View view){
EditText editText1 = (EditText) findViewById(R.id.editText);
EditText editText2 = (EditText) findViewById(R.id.editText2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
if(!allFieldsEntered(editText1, editText2, editText3)){
com.ammar.android.dailyjobsiteinspection2.Message.message(this, "All fields must be filled before starting an Audit ");
}else{
Intent intent = new Intent(this, MainActivity11Activity.class);
Bundle bundle = getDataBundle(editText1, editText2, editText3);
intent.putExtras(bundle);
setContentView(R.layout.activity_main_activity11);
startActivity(intent);
}
}
private Bundle getDataBundle(EditText editText1, EditText editText2, EditText editText3) {
Bundle bundle = new Bundle();
bundle.putString(MainActivity.INSPECTORID, editText1.getText().toString());
bundle.putString(MainActivity.SITENAME, editText2.getText().toString());
bundle.putString(MainActivity.SITEADDRESS, editText3.getText().toString());
return bundle;
}
private boolean allFieldsEntered(EditText editText1, EditText editText2, EditText editText3) {
return !(editText1.getText().toString().matches("")
|| editText2.getText().toString().matches("")
|| editText3.getText().toString().matches(""));
}
}
Here is the second activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.ammar.android.dailyjobsiteinspection2.MainActivity11Activity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/scrollView"
android:layout_gravity="center_horizontal"
android:layout_weight="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layout"></LinearLayout>
</ScrollView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="#+id/layout2">
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:text="New Text"
android:id="#+id/textView4"
android:layout_weight="1"
android:visibility="invisible" />
<Button
android:layout_width="160dp"
android:layout_height="fill_parent"
android:text="Save"
android:id="#+id/button4"
android:onClick="save" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView5"
android:layout_weight="1"
android:visibility="invisible"/>
<Button
android:layout_width="160dp"
android:layout_height="fill_parent"
android:text="Submit"
android:id="#+id/button5"
android:onClick="submit" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView6"
android:layout_weight="1"
android:visibility="invisible"/>
</LinearLayout>
</LinearLayout>
and the Java code:
import android.app.ActionBar;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity11Activity extends ActionBarActivity {
private ArrayList<RadioGroup> radioGroupArrayList;
private String inspectorId;
private String siteName;
private String siteAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity11);
setFields();
setUI();
}
#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_activity11, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setFields() {
Intent intentBundle = getIntent(); // get intent
Bundle bundle = intentBundle.getExtras(); // get bundle from intent
inspectorId = bundle.getString(MainActivity.INSPECTORID);
siteName = bundle.getString(MainActivity.SITENAME);
siteAddress = bundle.getString(MainActivity.SITEADDRESS);
}
private void setUI() {
TextView textView;
radioGroupArrayList = new ArrayList<RadioGroup>();
LinearLayout ll = (LinearLayout) this.findViewById(R.id.layout);
int count = 0;
for(int i = 0; i<6; i++){
int id = getResources().getIdentifier("PreStart"+ i, "array" , getPackageName());
String [] questions = getResources().getStringArray(id);
textView = new TextView(this);
textView.setText(questions[0]);
textView.setTextSize(24);
textView.setTypeface(null, Typeface.BOLD);
ll.addView(textView);
TextView textView1;
TextView textView2;
RadioGroup radioGroup;
RadioButton radioButton1;
RadioButton radioButton2;
RadioButton radioButton3;
for (int j = 1; j< questions.length; j++){
textView1 = new TextView(this);
textView1.setText(questions[j]);
textView1.setTextSize(18);
radioGroup = new RadioGroup(this);
radioGroupArrayList.add(radioGroup);
radioButton1 = new RadioButton(this);
radioButton2 = new RadioButton(this);
radioButton3 = new RadioButton(this);
radioButton1.setText("Yes");
radioButton2.setText("No");
radioButton3.setText("NA");
radioButton1.setId(count);
radioButton2.setId(count+1);
radioButton3.setId(count+2);
count = count + 3;
radioGroup.addView(radioButton1);
radioGroup.addView(radioButton2);
radioGroup.addView(radioButton3);
radioButton1.setPadding(20, 20, 100, 20);
radioButton2.setPadding(20, 20, 100, 20);
radioButton3.setPadding(20, 20, 100, 20);
radioGroup.setOrientation(LinearLayout.HORIZONTAL);
textView2 = new TextView(this);
textView2.setVisibility(View.INVISIBLE);
ll.addView(textView1);
ll.addView(radioGroup);
ll.addView(textView2);
}
}
EditText editText = new EditText(this);
editText.setId(R.id.editText11);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Enter Comments Here");
ll.addView(editText);
}
public void save(View view){
AnswerListCreator answerCreator = new AnswerListCreator(radioGroupArrayList);
String[] answerList = answerCreator.getAnswerList();
String commentLog = ((EditText) findViewById(R.id.editText11)).getText().toString();
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Site site = new Site(inspectorId, siteName, siteAddress, answerList, commentLog, 0);
dbHelper.insertSite(db, site);
// go back to main
Intent intent = new Intent(this, MainActivity.class);
setContentView(R.layout.activity_main);
startActivity(intent);
db.close();
finish();
}
public void submit(View view) {
AnswerListCreator answerCreator = new AnswerListCreator(radioGroupArrayList);
if (!answerCreator.isComplete()) {
com.ammar.android.dailyjobsiteinspection2.Message.message(this, "All fields must be checked");
} else {
answerCreator = new AnswerListCreator(radioGroupArrayList);
String[] answerList = answerCreator.getAnswerList();
String commentLog = ((EditText) findViewById(R.id.editText11)).getText().toString();
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Site site = new Site(inspectorId, siteName, siteAddress, answerList, commentLog, 1);
dbHelper.insertSite(db, site);
// go back to main
Intent intent = new Intent(this, MainActivity.class);
setContentView(R.layout.activity_main);
startActivity(intent);
db.close();
finish();
}
}
}
You are changing first Activity's View before calling StartActivity.
Remove this in MainActivity1Activity:
setContentView(R.layout.activity_main_activity11);
Furthermore, if you want to keep view state in MainActivity1Activity don't start it again. Just call finish() in second activity.
My method that is called (calculate BMI) inside of my activity is supposed to compute and display BMI (based on the formula inside the code), and display its value inside of a textview. The application runs correctly, however the value displayed is always zero. I am struggling to figure out if the problem lies in my formula (unlikely) or if the way that I am passing the value is incorrect. Any help would be appreciated. Code below
.Java file
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.widget.Toast;
public class Health extends ActionBarActivity {
EditText bloodPressure;
EditText cholesterol;
int weight;
int height;
EditText heightString;
EditText age;
TextView bmiText;
EditText weightString;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health);
weightString = (EditText) findViewById(R.id.weightTextBox);
heightString =(EditText) findViewById(R.id.heightTextBox);
bmiText = (TextView) findViewById(R.id.bmiTextView);
bloodPressure = (EditText) findViewById(R.id.bloodPressureTextBox);
cholesterol = (EditText) findViewById(R.id.cholesterolTextBox);
age = (EditText) findViewById(R.id.ageTextBox);
dbHandler = new MyDBHandler(this, null, null, 1);
}
public void calculateBMI(View view)
{
weight = Integer.parseInt(weightString.getText().toString());
height = Integer.parseInt(heightString.getText().toString());
int BMI = 703 * (weight/(height*height));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Toast.makeText(Health.this, " Info Saved ", Toast.LENGTH_SHORT).show();
HealthInfo healthInfo = new HealthInfo(bloodPressure.getText().toString(),cholesterol.getText().toString(),heightString.getText().toString(),weightString.getText().toString(),age.getText().toString());
dbHandler.addHealth(healthInfo);
}
public void calorieClick(View view){
Intent i = new Intent(this, CalorieTracker.class);
startActivity(i);
}
public void openTips(View view){
Intent i = new Intent(this, HealthTipsActivity.class);
startActivity(i);
}
public void openPlans(View view){
Intent i = new Intent(this, DietPlansActivity.class);
startActivity(i);
}
#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_health, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
.XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="seniorproject.broncos.broncowellnessapp.Health"
android:background="#006699">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/blood_pressure_text"
android:id="#+id/bloodPressureTextView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/cholesterol_text"
android:id="#+id/cholesterolTextView"
android:layout_below="#+id/bloodPressureTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/weight_text"
android:id="#+id/weightTextView"
android:layout_below="#+id/cholesterolTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/height_text"
android:id="#+id/heightTextView"
android:layout_below="#+id/weightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/age_text"
android:id="#+id/ageTextView"
android:layout_below="#+id/heightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:width="150dp"
android:id="#+id/bloodPressureTextBox"
android:layout_below="#+id/bloodPressureTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/cholesterolTextBox"
android:layout_below="#+id/cholesterolTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/weightTextBox"
android:layout_below="#+id/weightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/heightTextBox"
android:layout_below="#+id/heightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/ageTextBox"
android:layout_below="#+id/ageTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/diet_plans_button_text"
android:onClick="openPlans"
android:id="#+id/dietPlansButton"
android:layout_below="#+id/ageTextBox"
android:layout_marginTop="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/calorie_tracker_button"
android:id="#+id/calorieAccessButton"
android:layout_below="#+id/dietPlansButton"
android:onClick ="calorieClick"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/tips_button_text"
android:id="#+id/tipsButton"
android:onClick="openTips"
android:layout_below="#+id/calorieAccessButton"
android:layout_alignRight="#+id/calorieAccessButton"
android:layout_alignEnd="#+id/calorieAccessButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/BMI_button_text"
android:id="#+id/bmiButton"
android:onClick="calculateBMI"
android:layout_alignBottom="#+id/cholesterolTextBox"
android:layout_alignRight="#+id/dietPlansButton"
android:layout_alignEnd="#+id/dietPlansButton"
android:layout_marginRight="36dp"
android:layout_marginEnd="36dp"
android:background="#ff00b812" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Push Button to Compute BMI"
android:id="#+id/bmiTextView"
android:layout_alignBottom="#+id/weightTextBox"
android:layout_alignLeft="#+id/bmiButton"
android:layout_alignStart="#+id/bmiButton" />
</RelativeLayout>
Your weight and height variables are int. That is your problem. Change them to float or double
Currently, you are doing integer division which is causing the result to be truncated as follows: 1 / 2 gives 0
You are doing a division for integer which results mostly to zero.
That is why the result is always zero.
Change your weight and height variables to double like this
and just cast the result back to int.
double weight = 0.0;
double height = 0.0;
int BMI = (int)(703 * (weight/(height*height)));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Place this on the end of the onCreate() method:
findViewById(R.id.bmiButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
weight = Integer.parseInt(weightString.getText().toString());
height = Integer.parseInt(heightString.getText().toString());
int BMI = 703 * (weight/(height*height));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Toast.makeText(Health.this, " Info Saved ", Toast.LENGTH_SHORT).show();
HealthInfo healthInfo = new HealthInfo(bloodPressure.getText().toString(),cholesterol.getText().toString(),heightString.getText().toString(),weightString.getText().toString(),age.getText().toString());
dbHandler.addHealth(healthInfo);
}
});
Some android version does not support onClick attribute for Button tag in XAML.
im tired to try this thing,can help me find out my solution.
I try to validate Edittext if edittext filed empty when i push a button will show a toast message.
this my layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MyActivity"
android:id="#+id/relativeLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Panjang"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="right|left" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextPanjang"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:maxLength="10"
android:hint="Panjang"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lebar"
android:id="#+id/textView2"
android:layout_below="#+id/editTextPanjang"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="right|left"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextLebar"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:maxLength="10"
android:hint="Lebar"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hitung Luas"
android:id="#+id/buttonHitungLuas"
android:layout_below="#+id/editTextLebar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="hitugLuas"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Luas"
android:id="#+id/textView3"
android:layout_below="#id/buttonHitungLuas"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextLuas"
android:layout_below="#id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextLuas"
android:id="#+id/buttonClear"
android:text="#string/btn_clear"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/buttonClear"
android:layout_below="#+id/editTextLuas"
android:id="#+id/buttonExit"
android:text="Exit"
/>
</RelativeLayout>
this my java
package com.example.aan.myfirstapp;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MyActivity extends ActionBarActivity {
private EditText edtPanjang;
private EditText edtLebar;
private EditText edtLuas;
private Button btnHitungLuas;
private Button btnClear;
private Button btnExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
initUI();
initEvent();
}
private void initUI(){
edtPanjang = (EditText) findViewById(R.id.editTextPanjang);
edtLebar = (EditText) findViewById(R.id.editTextLebar);
edtLuas = (EditText) findViewById(R.id.editTextLuas);
btnHitungLuas = (Button) findViewById(R.id.buttonHitungLuas);
btnClear = (Button) findViewById(R.id.buttonClear);
btnExit = (Button) findViewById(R.id.buttonExit);
}
private void initEvent() {
btnHitungLuas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hitungLuas();
}
}
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clearData();
}
});
btnExit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View paramView) {
MyActivity.this.finish();
}
});
}
private void hitungLuas(){
int panjang = Integer.parseInt(edtPanjang.getText().toString());
int lebar = Integer.parseInt(edtLebar.getText().toString());
int luas = panjang*lebar;
edtLuas.setText(luas+"");
}
private void clearData(){
edtLuas.setText("");
edtLebar.setText("");
edtPanjang.setText("");
}
#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_my, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Sory for my bad english
log chat when i run the emulator
03-12 09:29:21.784 1710-2323/com.google.process.gapps E/Backup﹕ [LegacyBackupAccountManager] Fail to get legacy transport context.
android.content.pm.PackageManager$NameNotFoundException: Application package com.google.android.backup not found
at android.app.ContextImpl.createPackageContextAsUser(ContextImpl.java:2139)
at android.app.ContextImpl.createPackageContext(ContextImpl.java:2115)
at android.content.ContextWrapper.createPackageContext(ContextWrapper.java:658)
at com.google.android.gms.backup.am.<init>(SourceFile:47)
at com.google.android.gms.backup.a.a(SourceFile:65)
at com.google.android.gms.backup.c.a(SourceFile:39)
at com.google.android.gms.backup.b.a(SourceFile:67)
at com.google.android.gms.backup.b.a(SourceFile:39)
at com.google.android.gms.backup.BackupAccountNotifierService.onHandleIntent(SourceFile:76)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
You need to handle onClick of the button in this manner and show a toast if the edittext is empty
if(editText.getText().toString().trim().length()==0){
Toast.makeText(getApplicationContext(), "field is empty",
Toast.LENGTH_LONG).show();
}else{
//your code here
}
If you want to check for empty EditText.. try TextUtils for it.
Example
if (TextUtils.isEmpty(edtText.getText().toString().trim())) {
Toast.makeText(getBaseContext(),
"Empty", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getBaseContext(),
"Not Empty", Toast.LENGTH_SHORT)
.show();
}
I have a problem with creating things using LayoutInflater:
package com.tip.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity implements View.OnClickListener {
EditText billamount, percent, people;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
billamount = (EditText)findViewById(R.id.billtext);
percent = (EditText)findViewById(R.id.percenttext);
people = (EditText)findViewById(R.id.numberpeople);
Button unevensplitbutton = (Button)findViewById(R.id.unevensplit);
Button calculates = (Button)findViewById(R.id.calculate);
unevensplitbutton.setOnClickListener(this);
calculates.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.calculate:
TableLayout calculatenumberinflated = (TableLayout)findViewById(R.id.numbertable2);
View view = getLayoutInflater().inflate(R.layout.calculatenumbertable,calculatenumberinflated,false);
calculatenumberinflated.addView(view);
break;
case R.id.unevensplit:
break;
}
}
#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;
}
#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);
}
}
And the XML of calculatenumbertable:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="25dp"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/numbertable2">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Each Person Pays"
android:id="#+id/numberpeople"
android:layout_column="3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/eachpersonedit"
android:layout_column="6" />
</TableRow></TableLayout>
And the XML of fragment_main:
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="25dp">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bill amount"
android:id="#+id/bill"
android:layout_column="3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/billtext"
android:layout_column="6" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Percentage %"
android:id="#+id/percentage"
android:layout_column="3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/percenttext"
android:layout_column="6" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number of people"
android:id="#+id/textView"
android:layout_column="3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/numberpeople"
android:layout_column="6" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Split Unevenly"
android:id="#+id/unevensplit"
android:layout_column="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:id="#+id/calculate"
android:layout_column="6" />
</TableRow>
</TableLayout>
</ScrollView>
It returns an error where:
12-16 21:22:56.825 28459-28459/com.tip.calculator E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.tip.calculator.MainActivity.onClick(MainActivity.java:35)
Where line 35 is the calculatenumberinflated.addView(view); line of code.
I feel lost right now, can someone please clarify what I am doing wrong? Thanks.
You are getting Nullpointer error at this line TableLayout calculatenumberinflated = (TableLayout)findViewById(R.id.numbertable2); which is not at all available in your fragment_main layout. It in the layout calculatenumbertable file and as you are inflating fragment_main layout so its not getting the correct id of your TableLayout.
Try to add your layout in TableRow besides TableLayout. Create separate row in your calculatenumbertable layout and then try add the layout in that row. You can not add layout directly in TableLayout.
Try as below:
In your calculatenumbertable add row in last as below:
<TableRow
android:id="#+id/tablerow"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TableRow>
In your onClick add the layout as below:
public void onClick(View v) {
switch(v.getId()){
case R.id.calculate:
TableRowcalculatenumberinflated = (TableRow)findViewById(R.id.tablerow);
View view = getLayoutInflater().inflate(R.layout.calculatenumbertable,calculatenumberinflated,false);
calculatenumberinflated.addView(view);
break;
case R.id.unevensplit:
break;
}
}
Just move android:id="#+id/numbertable2" from calculatenumbertable.xml to fragment_main.xml in the tableLayouts.
Try this
LayoutInflater inflater=getLayoutInflater();
View view= inflater.inflate(R.layout.calculatenumbertable, null);
calculatenumberinflated.addView(view);