I created this simple app using android studio, which is supposed to calculate x percent of y and it shows no errors in the code in the android studio window however when I click the button in the app it crashes????? I am new to coding, I would appreciate any help.
package com.sabri.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText percentText;
EditText numberText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button button = (Button) findViewById(R.id.button);
if (button == null) throw new AssertionError();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
float percentage = Float.parseFloat(percentText.getText().toString());
float dec = percentage / 100;
float total = dec * Float.parseFloat(numberText.getText().toString());
textView.setText(Float.toString(total));
}
});
}
@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);
}
}
I'm assuming that you're getting a NullPointerException
error. You never initialized the percentText
and numberText
variables.
Try putting this in your onCreate()
method where you assign your Button variable
textView = (TextView)findViewById(R.id.textView);
numberText = (EditText)findviewbyid(R.id.numberText);
percentText = (EditText)findviewbyid(R.id.percentText);
Always make sure that your variables are initialized before you ever try doing anything to/with them. Might be a good idea to create a new method intializeViewVariables()
in which you initialize all of your View
variables you plan on working with and just calling that method in your onCreate()
.
And please, if you're asking for help with a crash/compiler errors, include the error message in your post!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.