New to Android - Exception - cannot be cast to android.widget.EditText - java

I'm new to android and am running into an error on a basic app. I am getting the following error,
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout
cannot be cast to android.widget.EditText at
com.example.chris.mytestv1.MainActivity.onCreate(MainActivity.java:39)
Below is the line causing it
numberTxt = (EditText) findViewById(R.id.numberTxt);
In my MainActivity.java i have
package com.example.chris.mytestv1;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
TextView totalTextView = null;
EditText percentageTxt = null;
EditText numberTxt = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
totalTextView = (TextView) findViewById(R.id.TotalTextView);
percentageTxt = (EditText) findViewById(R.id.percentageTxt);
numberTxt = (EditText) findViewById(R.id.numberTxt);
Button calcBtn = (Button) findViewById(R.id.calcBtn);
calcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float percentage = Float.parseFloat(percentageTxt.getText().toString());
float dec = percentage / 100;
float total = dec * Float.parseFloat(numberTxt.getText().toString());
totalTextView.setText(Float.toString(total));
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#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);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.example.chris.mytestv1/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.example.chris.mytestv1/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
In my content_main.xml i have -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.chris.mytestv1.MainActivity"
tools:showIn="#layout/activity_main"
android:id="#+id/numberTxt">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="0"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:textAlignment="center"
android:textSize="50dp"
android:id="#+id/TotalTextView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="What is"
android:id="#+id/textView"
android:layout_below="#+id/TotalTextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:layout_marginBottom="10dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/percentageTxt"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:hint="Enter Percentage"
android:textAlignment="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/numberTxt"
android:hint="Enter Number"
android:textAlignment="center"
android:layout_marginTop="48dp"
android:layout_below="#+id/textView3"
android:layout_alignStart="#+id/percentageTxt" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="%"
android:id="#+id/textView2"
android:layout_marginRight="50dp"
android:layout_alignTop="#+id/percentageTxt"
android:layout_toEndOf="#+id/calcBtn"
android:paddingTop="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Of"
android:id="#+id/textView3"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CALCULATE"
android:id="#+id/calcBtn"
android:layout_marginTop="70dp"
android:textSize="30dp"
android:background="#b91313"
android:textColor="#ffffff"
android:layout_below="#+id/numberTxt"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I've searched for why this error could be occurring however i was unable to find out why.

You have duplication in ids, your RelativeLayout and EditText use the same id:
<RelativeLayout
android:id="#+id/numberTxt">
<EditText
android:id="#+id/numberTxt">
so when android try to findViewById he try to use first which is RelativeLayout not EditText.

I found the error, stupid mistake. I wasn't sure where i should be looking.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.chris.mytestv1.MainActivity"
tools:showIn="#layout/activity_main"
android:id="#+id/numberTxt">

Related

EditText fields showing different keyboards

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);

EditText OnClick Exception

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
});
}

making toast for validate edit text when i push a button

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();
}

java - Android app crashes when button is pressed

I am trying to get a part of a simple Android app working. I am confused as to why I am getting the error "Unfortunately, this app has stopped working".
Basically, I need the total value to increase when I click on a button based on what value they have. For example coffee adds 2 to the total. Every time I click a button that adds to the total value, the app crashes.
Here is the source code. I have just copied the parts that are specific to this problem.
package com.example.pp.application;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener {
TextView tv01;
Double Total = 0.00;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv01 = (TextView) findViewById(R.id.tv01);
}
#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 sendMessage(View view)
{
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
public void addCoffee() {
Total = Total + 2.20;
tv01.setText(""+Total+"");
}
public void addBus() {
Total = Total + 1.90;
tv01.setText(""+Total+"");
}
public void addMilk() {
Total = Total + 1.50;
tv01.setText(""+Total+"");
}
}
And here is the Manifest:
<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/label">
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Coffee"
android:id="#+id/button"
android:onClick="addCoffee"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="42dp" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Bus"
android:onClick="addBus"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Milk"
android:onClick="addMilk"
android:id="#+id/button4"
android:layout_below="#+id/button3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:onClick="sendMessage"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/button5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="------------------"
android:id="#+id/tv01"
android:layout_alignRight="#+id/button"
android:layout_alignEnd="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Total"
android:id="#+id/textView"
android:layout_toStartOf="#+id/tv01"
android:layout_toLeftOf="#+id/tv01" />
Instead of public void addCoffee() your onClick method definition should look like public void addCoffee(View v), where v is the widget you clicked on (in this case the Button). Take the same approach when updating other onClick methods. This requirement applies only to callbacks defined via android:onClick attribute in XML layout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv01 = (TextView) findViewById(R.id.tv01);
public void addCoffee(View v) {
Total = Total + 2.20;
tv01.setText(""+Total+"");
}
}
and continue with another function with same way
Since you haven't posted the stack trace of the LogCat, I have no way of telling when in the code your error has been.
But it's likely to have occured before. These links contain similar stances and documentations about exceptions.
My Android App Keeps Crashing
https://developers.google.com/analytics/devguides/collection/android/v4/exceptions
https://developer.android.com/distribute/essentials/optimizing-your-app.html
Android App Crashes on Button Click

How to add icon to tabs

I am trying to add an icon to my tabs and it isnt working,
I tried adding
getResources().getDrawable(R.drawable.bodyicon));
and it still isnt working. When I run the application the tab bar just has the text and there is no icon
I outlined where my code is. If someone could figure out why it isnt working that would be great.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Body extends Activity implements OnTouchListener, OnClickListener {
Button bAbs, bQuad2, bPecs;
TabHost th;
ImageView body;
final Context context = this;
StretchType pop;
// above I am defining all of the buttons and images, etc...
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// here I am saying get rid of the nav bar
setContentView(R.layout.body);
th = (TabHost) findViewById(R.id.thbodyview);
bAbs = (Button) findViewById(R.id.bAbss);
bPecs = (Button) findViewById(R.id.bPecss);
bAbs.setOnClickListener(this);
bPecs.setOnClickListener(this);
//*********************below are my tabs*******************************************
th.setup();
TabSpec specs = th.newTabSpec("Front");
specs.setContent(R.id.Front);
specs.setIndicator("Front",getResources().getDrawable(R.drawable.bodyicon));
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.Back);
specs.setIndicator("Back");
th.addTab(specs);
specs = th.newTabSpec("tag3");
specs.setContent(R.id.tab3);
specs.setIndicator("More...");
th.addTab(specs);
}
//***************************Above are my tabs *******************************
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bAbss:
// below I am creating the alert dialogue
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.abs, null);
// above I am setting the customview of the alert dialogue
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setView(promptsView);
// here I am officially setting the custom layout
// set dialog message
alertDialogBuilder.setTitle("Stretch Type");
// alert dialogue title
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();
// above is creating the alert dialogue
final Spinner mSpinner = (Spinner) promptsView
.findViewById(R.id.sSType);
// above is initializing the spinner
/*
* dont need this button final Button mButton = (Button) promptsView
* .findViewById(R.id.bSpinclose);
*/
// reference UI elements from my_dialog_layout in similar fashion
mSpinner.setOnItemSelectedListener(new OnSpinnerItemClicked());
// show it
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
break;
}
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
public class OnSpinnerItemClicked implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
switch (pos) {
case (1):
Intent i = new Intent(Body.this, Practice.class);
Body.this.startActivity(i);
break;
}
}
#Override
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
}
Here is the xml
<TabHost
android:id="#+id/thbodyview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/Front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/llbottomtop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
<TextView
android:id="#+id/tvupper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/bAbs"
android:text="Upper"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF" />
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_centerVertical="true"
android:background="#color/orange" />
<TextView
android:id="#+id/tvlower"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1"
android:text="Lower"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF" />
</LinearLayout>
<ImageView
android:id="#+id/ivBody"
android:layout_width="210dp"
android:layout_height="430dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/body_front" />
<Button
android:id="#+id/bPecss"
android:layout_width="83dp"
android:layout_height="50dp"
android:layout_above="#+id/bAbss"
android:layout_alignRight="#+id/bAbss"
android:text="Pecs" />
<Button
android:id="#+id/bAbss"
android:layout_width="80dp"
android:layout_height="77dp"
android:layout_alignBottom="#+id/llbottomtop"
android:layout_centerHorizontal="true"
android:layout_marginBottom="42dp"
android:text="Abs" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/Back"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/llbottomtop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
<TextView
android:id="#+id/tvupper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/bAbs"
android:text="Upper"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF" />
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_centerVertical="true"
android:background="#color/orange" />
<TextView
android:id="#+id/tvlower"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1"
android:text="Lower"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF" />
</LinearLayout>
<ImageView
android:id="#+id/ivBody"
android:layout_width="210dp"
android:layout_height="430dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/body_back" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
</FrameLayout>
</RelativeLayout>
</TabHost>
My tip is to get access to the tab title textview and set left|top|right|bottom drawable
Example:
//to get first tab title as textView from tabHost
TextView tabTitle = (TextView) tabHost.getTabWidget().getChildAt(0)
.findViewById(android.R.id.title);
//to set the icon to left of the tab title
tabTitle.setCompoundDrawablesWithIntrinsicBounds(
getActivity().getResources().getDrawable(
R.drawable.ic_tab_icon), null, null, null);
I have two physical devices one 2.2 and the other 4.2.2. on 2.2 there is no issue and the icon appears. on 4.2.2 there is no icon. Somethings changed in how tabs are laid out in Android. If you really required to use a TabHost i saw you can pass in a view as the tabindicator. This code is kinda pseudo code as it still some adjustment in the UI in terms of layout but try this:
define a layout called tabindicator_layout.xml and put it in res/layout. the contents of which look like this:
<?xml version="1.0" encoding="utf-8"?>
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:scaleType="center" >
</ImageView>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
then in your class code at runtime inflate this view and populate the image and textview with what you desire. do this for each tab:
//*********************below are my tabs*******************************************
th.setup();
TabSpec specs = th.newTabSpec("Front");
specs.setContent(R.id.Front);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tabindicator_layout, th.getTabWidget(), false);
((TextView) tabIndicator.findViewById(R.id.title)).setText("Front");
((ImageView) tabIndicator.findViewById(R.id.image))
.setImageResource(R.drawable.ic_launcher);
specs.setIndicator(tabIndicator);
TabSpec specs2 = th.newTabSpec("tag2");
specs2.setContent(R.id.Back);
View tabIndicator2 = LayoutInflater.from(this).inflate(
R.layout.tabindicator_layout, th.getTabWidget(), false);
((TextView) tabIndicator2.findViewById(R.id.title)).setText("Back");
((ImageView) tabIndicator2.findViewById(R.id.image))
.setImageResource(R.drawable.ic_launcher);
specs2.setIndicator(tabIndicator2);
TabSpec specs3 = th.newTabSpec("tag3");
specs3.setContent(R.id.tab3);
View tabIndicator3 = LayoutInflater.from(this).inflate(
R.layout.tabindicator_layout, th.getTabWidget(), false);
((TextView) tabIndicator3.findViewById(R.id.title)).setText("...More");
((ImageView) tabIndicator3.findViewById(R.id.image))
.setImageResource(R.drawable.ic_launcher);
specs3.setIndicator(tabIndicator3);
th.addTab(specs);
th.addTab(specs2);
th.addTab(specs3);
of course replace R.drawable.ic_launcher with whatever icon you want to show
another interesting thing that might help..i notice if i pass in a blank for the title that the original way works but shows no title. So you could go into photoshop and just add the title to the image and make it even better looking. Try this way:
TabSpec specs = th.newTabSpec("Front");
specs.setContent(R.id.Front);
specs.setIndicator("",getResources().getDrawable(R.drawable.ic_launcher));
th.addTab(specs);

Categories