有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何解决安卓中的空指针异常?

这是安卓系统中的一个简单应用。它在执行时显示nullpointerexception。 我无法从edittext中获取值。这里我只想从edittext中获取值。 但它显示了nullpointerexception

如何解决这个问题

public class Calci extends Activity  {
    Button add;
    String str1;
    String str2;
    EditText txt1;
    EditText txt2;
    TextView tv;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calci);

        add=(Button) findViewById(R.id.button1);
        txt1=(EditText) findViewById(R.id.editText1);
        str1=txt1.getText().toString();
        txt2=(EditText) findViewById(R.id.editText2);
        str2=txt2.getText().toString();
        tv=(TextView) findViewById(R.id.textView4);

        addition();

        add.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                addition(); 
            }
        });
    }


    private void addition(){
        int res=0;
        res=Integer.parseInt(str1)+Integer.parseInt(str2);
        tv.setText(String.valueOf(res));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_calci, menu);
        return true;
    }
}

共 (4) 个答案

  1. # 1 楼答案

    只需替换oncreate()中的additiion()方法,并按如下所示更改该方法

    private void addition()
      {
             str1= str1==null?"0":str1;// do like this, so that if str1 returns null then it will be replaced by 0
             str2= str2==null?"0":str2;
             int res=0;
             res=Integer.parseInt(str1)+Integer.parseInt(str2);
             tv.setText(String.valueOf(res));
      }
    
  2. # 2 楼答案

    此处不调用addition()方法:

            str2=txt2.getText().toString();
            tv=(TextView) findViewById(R.id.textView4);
    
            //addition();
    
    
            add.setOnClickListener(new View.OnClickListener() 
    
  3. # 3 楼答案

    确保在xml中为editText1editText2设置默认值,或者如果要访问用户输入的值,请将代码更改为,并在setOnClickListener之前删除addition():

          //  addition();  comment this line 
            add.setOnClickListener(new View.OnClickListener() 
            {
    
                public void onClick(View v) 
                {
                      str1=txt1.getText().toString();
                      str2=txt2.getText().toString();
                      addition(); 
    
                }
            });
    
  4. # 4 楼答案

    只需从onCreate()中删除addition();。就像我怀疑它第一次叫你的EditTexts是空的一样

    另外,当调用addition()方法时,必须从两个EditTexts中获取文本

    你的方法是

     private void addition()
     {
    
      int res=0;
      str1=txt1.getText().toString();
      str2=txt2.getText().toString();
      res=Integer.parseInt(str1)+Integer.parseInt(str2);
      tv.setText(String.valueOf(res));
     }