简体   繁体   中英

(Android) How to grab EditText value?

I have an app that is supposed to:
1. If Spinner value is "1", do a certain math equation from EditText value
2. If Spinner value is "2", do a certain math equation from EditText value I'm getting "NullPointerException"
Here is my code:

package org.infinitech.degreescalculator.app;
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.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity{
    public Button button=(Button)findViewById(R.id.button);
    public String selectedItem;
    Integer number;
    Integer a;
    String numberTwo;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText input=(EditText)findViewById(R.id.input);
        final TextView answerText=(TextView)findViewById(R.id.answer);
        final Spinner spinner=(Spinner)findViewById(R.id.options);
            final String inputTwo=(String)getText(R.id.input);
    selectedItem=(String)spinner.getSelectedItem();
        button.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                if(selectedItem.equals("Fahrenheit to Celsius")){
                    a=Integer.parseInt(inputTwo);
                    number=a*100;
                    numberTwo=number.toString();
                    answerText.setText(numberTwo);
                }
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        return super.onOptionsItemSelected(item);
    }
}

您可以像这样以String获取值:

editTextObject.getText().toString()

Actually this line final String inputTwo=(String)getText(R.id.input); will not give any value so instead doing it like that just directly get the text of it inside the onclick of the button.

Change this:

a=Integer.parseInt(inputTwo);

to:

a=Integer.parseInt(input.getText().toString());

Your problem is that selectedItem is assigned in your onCreate method, which runs before any of the items in your spinner have been selected, and is therefore always null . Move the line that assigns it to inside your button click listener's onClick method, and it should solve the problem.

Similarly, you may also need to move your inputTwo variable into the onClick method, so this too is not set at creation time and never updated.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM