簡體   English   中英

設置結果導致textview時出現空指針異常

[英]Null pointer exception when setting results in a textview

Computecost按鈕時,應用程序崩潰

package com.example.hw_3;

import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import android.content.*;

public class ShoppingExpensesPage extends Activity  

{
    TextView et;
    Button computecost;
    Button save;
    Button cancel;
    RadioGroup drinks;
    RadioButton drink;
    int tottalcost=0;

    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
        et=(TextView)findViewById(R.id.tv11);
          Bundle extra = getIntent().getExtras();
          String val1 = extra.getString("value");
          et.setText(val1);
          computecost=(Button)findViewById(R.id.btn11);
          computecost.setOnClickListener(new View.OnClickListener() 
          {
            @Override
            public void onClick(View view) 
            {
                String val;

                int selectedId = drinks.getCheckedRadioButtonId();
                drink = (RadioButton)findViewById(selectedId);
                val=(String) drink.getText();
                if(val=="Juice")
                {tottalcost=tottalcost+3;

                }
                else if (val=="Cola")
                {

                    tottalcost=tottalcost+2;

                }

                et.setText(Integer.toString(tottalcost));
            }
          });

          save=(Button)findViewById(R.id.btn21);
          save.setOnClickListener(new View.OnClickListener()
          {
            @Override

            public void onClick(View v) {
                Intent returnIntent = new Intent();
                 String  str=Integer.toString(tottalcost);//(String) et.getText();
                returnIntent.putExtra("return", str);
                 setResult(RESULT_OK,returnIntent);     
                 finish();                  
            }
          });
    }
}

你還沒定下drinks

int selectedId = drinks.getCheckedRadioButtonId();

computecost.setOnClickListener之前找到它的視圖:

drinks = (RadioGroup) findViewById(...);

這是比較Strings的錯誤方法

if(val=="Juice")

在Java中,“ ==”比較Objects的引用,而不是它們的值。 您需要使用.equals()

 if("Juice".equals(val))
 {   // do something  }

如果這不能解決您的問題,請從錯誤中發布日志,但是仍然需要更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM