Android Application Crash on button event - android

I am trying to make a simple android application that can add two numbers, but it is crashing as soon as I press on add button.Please find the code below.The emulator uses 300 MB RAM
I have two editboxes in which numbers are being inputted and their sum is being displayed on third input box by tapping on add button
package example.sample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.close);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
EditText E1=(EditText)findViewById(R.id.editText1);
EditText E2=(EditText)findViewById(R.id.editText2);
EditText E3=(EditText)findViewById(R.id.editText3);
String s=E1.toString();
String m=E2.toString();
// String k="sud";
int num1=Integer.parseInt(s);
int num2=Integer.parseInt(m);
int num3 =num1+num2;
String f=Integer.toString(num3);
E3.setText(f);
}
});
}
#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;
}

change
String s=E1.toString();
String m=E2.toString();
to
String s=E1.getText().toString();
String m=E2.getText().toString();
for getting text from EditText's on Button Click. currently you are trying to parse View's as Integer

String s=E1.getText().toString();
String m=E2.getText().toString();
you are not performing addition operation on numbers. That is why your app is crashing.

Related

Adding different values based on which option they choose on Spinner - Android Studio

I am trying to create a app that calculates fuel mileage for racecars. I'm in the very basics of this app right now, I would like to know how to add a formula to each option on the spinner.
For instance I want the formula to be:
thesum= (int) (fulltank-(n1*avglapgal));
thesum1= (int) (thesum-(n2*avglapgal));
I want "avglapgal" (average gallon per lap) to change based on which option they choose on the spinner.
How do I accomplish this?
Thanks in advance!
My strings.xml:
<resources>
<string name="app_name">MidTermApp</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="trackname">Choose your Track</string>
<string-array name="trackchoices">
<item>Short Track (Half mile)</item>
<item>Intermediate (Mile)</item>
<item>Speedway (1.5 miles)</item>
<item>Super-Speedways (2.5 miles)</item>
</string-array>
</resources>
My JAVA file:
package com.example.fuelapp;
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; import android.widget.Spinner; import
android.widget.TextView;
import java.text.DecimalFormat;
public class Grade{
String mLabel;
Float mValue;
....... } public class MainActivity extends ActionBarActivity {
double fulltank=18.5;
double avglapgal=.25;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v)
{
int n1;
int n2;
int thesum;
double thesum1;
EditText e1=(EditText)findViewById(R.id.lapscomplete);
EditText e2=(EditText)findViewById(R.id.lapstogo);
TextView t1=(TextView)findViewById(R.id.answer);
n1=Integer.parseInt(e1.getText().toString());
n2=Integer.parseInt(e2.getText().toString());
thesum= (int) (fulltank-(n1*avglapgal));
thesum1= (int) (thesum-(n2*avglapgal));
final Spinner trackchoose = (Spinner) findViewById(R.id.tracks);
DecimalFormat currency = new DecimalFormat("#.00");
String choice = trackchoose.getSelectedItem().toString();
t1.setText("You'll have " + currency.format(thesum1) + " gallon(s) of gas remaining.");
}
#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);
} }
You have to do two things:
You need to set a ListAdapter on the Spinner to provide a source for the choices. Since you already have a String array, you can use ArrayAdapter<String>.
You need to set an OnItemSelectedListener on the Spinner to respond to the user action. The onItemSelected() method will tell you which item the user chose.
Please see this great example on Android Developers: Spinners | Android Developers

How to move a image View left and right in android development

I am very new to Android Development, and I am trying to develop a game. In this game, I will require a Imageview to move left and right when pressed by a button. My current IDE that I am using is "Android Studio". So I have done research but am not finding any answers. My current code is
package com.example.turtle;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
Button left, right ;
ImageView turtle ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
left = (Button) findViewById(R.id.bl);
right = (Button) findViewById(R.id.br);
turtle = (ImageView) findViewById(R.id.IVT);
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#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;
}
}
So yeah, As you can see I set up an OnClcikListener but I don't know what goes under it. I heard I can lessen a position, but how would I do that ? Like what is the code to lessen a position ? Thanks
At least for the newer Android studio this is how I would do it.
In your xml text code,(in your design/layout page go on the bottom and click text)
<Button
android:onClick="LeftBonClick"
(plus any additional xml code you have for this button.)
/>
And then on you java code...
public void LeftBonClick(View view) {
turtle.setX(turtle.getX() - 2); //<<code depending on your preference and what layout your turtle is in.
//add any code you want to happen here, when the left button is clicked
}
You can set the new parameteres for your ImageView with the following code inside onClick() method:
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(50,50, 0,0);
// OR
params.topMargin= 50;
turtle.setLayoutParams(params);
Hope that will help you.

Radio group not working in android

I ahve made a simple radioButton demo in android.In that i have put a radiogroup with two radio buttons named "male" and "female"...and a button .I want is when one of them pressed the name related to that particular radiobutton should be in toast.I have tried as below thats not working:
Activity.java
package com.example.radiobuttondemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
RadioButton rd1,rd2;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rd1=(RadioButton)findViewById(R.id.radio0);
rd2=(RadioButton)findViewById(R.id.radio1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(rd1.isChecked()){
Toast.makeText(getApplicationContext(), "male", 0).show();
}
else{
Toast.makeText(getApplicationContext(), "Female", 0).show();
}
}
});
}
}
You forgot to initialize your Button b.
So when you're doing b.setOnClickListener, your program throws a NullPointerException and make your app closed.
You must bind your button with the Button object (that you named b) in your MainActivity class.
There is an action listener on b, but b is not binded...
Personally, I've always used RadioGroup for my radio buttons. If you didn't use that, how would it know to uncheck one radio button when you checked the other radio button?
See http://www.mkyong.com/android/android-radio-buttons-example/
Now if you're dealing with a normal checkbox, your approach would be fine I suppose. A normal checkbox wouldn't need to know about its siblings.
Do the check against RadioButton group itself:
switch (radioGroup.getCheckedRadioButtonId()) {
case rd1:
Toast.makeText(getApplicationContext(), "male", 0).show();
break;
case rd2:
Toast.makeText(getApplicationContext(), "Female", 0).show();
break;
)

show the text of an EditText into a TextView

Describing the functionality of my application: I have put in a Relative Layout a TextView, an EditText and a button. All I am trying to do is: when the user writes something in the EditText and push the button, then the content of the EditText is appeared in the TextView(just like a chat-virtual chat). Everything works perfectly, but when the EditText is empty,and the button get pushed, an empty line is appeared in the TextView(and i don't want to..). Although I've tried to solve it using an if the empty line is still appearing in the TextView. I would be really greatfull, if you could help!!! Than you in advance!
Here is my code:
package teiath.android.appliacation;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class M_chat extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/**Code for the scroll bars in the TextView. */
final TextView tv = (TextView)findViewById(R.id.TEXT_VIEW);
tv.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
/** Code for the scroll bars in the EditText. */
final EditText wr = (EditText)findViewById(R.id.EDIT_TEXT);
wr.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
final Button button = (Button) findViewById(R.id.btn1);//find the button by id in main.xml
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String wrcontent = wr.getText().toString();//gets the text of the EditText and put it in "tvcontent" variable.
String tvcontent = tv.getText().toString();//gets the text of the textView and put it in "tvcontent" variable.
if (wrcontent!="")//if the EditText is not empty
{
//check if the TextView is empty or not
if (tvcontent!="")//If it is not empty...
{
tv.setText(tvcontent + "\n" + wrcontent);//add its current(TextView's text) text, new line and the text of the EditText as the new text of TextView.
//tv.setVisibility(0);//makes visible the textView with the cloud1.png background
wr.setText("");//set the text of the Edit Text as empty
//wrcontent = "";
}
else//if the TextView is empty...
{
tv.setText(wrcontent);//add the text of the editText as the new text of the TextView
wr.setText("");
}
}
/**if (wrcontent=="")
{
}*/
//finish();
}
});
}
}
Don't use !="" for String comparison. To check for empty text, use something like
if ( wrcontent != null && wrcontent.trim().length() == 0 ) {
Better yet, include Guava libraries in your code.

How the detect the "edittext" box whether it is nothing in Android?

I want to program a function that the toast exist when there is nothing
in the "edittext" box (id / password), but it dosen't work.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.text.Editable;
public class Test extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
EditText id = (EditText) findViewById(R.id.id);
EditText pwd = (EditText) findViewById(R.id.pwd);
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
button1.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v){
if(Str_id==null || Str_pwd == null){
Toast.makeText(Test.this, "Please Enter User ID / Password", Toast.LENGTH_LONG).show();
}
});
}
}
move the following lines inside onClick and try:
Str_id = id.getText();
Str_pwd = pwd.getText();
EDIT: Move
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
inside onClick().
I do not recommend toasting a message that a field is required. You're better off just giving the EditText focus, this focus tells the user that this field is required. Its less information on the screen and its subtle, which is important. You don't want to disturb the user too much.
The idea is...
When the submit button is clicked, check the EditTexts if any of them are empty, notify the user through requesting focus, also make sure your UI tells them before hand that the fields required. The hint of the EditText works well for this.

Categories

Resources