这个Android应用程序代码只运行一次,应用程序停止工作

时间:2017-05-25 09:00:27

标签: java android stack

这是堆栈的代码; 单击按钮编号添加到堆栈中并按下显示在textview上,同样点击推送编号从堆栈中推送。但只进行了一次操作或交替进行,我不能再推两次。

    Button b1 = (Button) findViewById(R.id.btn1);
    b1.setOnClickListener(this);
    Button b2 = (Button) findViewById(R.id.btn2);
    b2.setOnClickListener(this);
    EditText e1 = (EditText) findViewById(R.id.etn1);
     x =  e1.getId();
}
@Override
public void onClick(View v) {
    TextView t1 = (TextView) findViewById(R.id.tvn);

  if (v.getId()== R.id.btn1) {
     Stack s1 = new Stack();
      s1.push(x);
      EditText e1 = (EditText) findViewById(R.id.etn1);
      e1.setId(0);

      t1.setText("Pushed");
      t1.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left));
  }
  else if (v.getId() == R.id.btn2) {
      Stack s2 = new Stack();
      s2.pop();
      t1.setText("Poped");
      t1.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left));
}
}
}

1 个答案:

答案 0 :(得分:0)

您很可能在NullPointerException获得s2.pop()。您正在尝试pop一个null对象,因为您的堆栈object中没有s2

1。尝试使用单个Stack并将其声明为global,并将其用于pushpop操作。

2。在执行任何pop操作之前,检查天气stack是否为empty

试试这个:

public class YourActivity extends AppCompatActivity {

    ........
    ................

    Stack stack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ........
        ................

        Button b1 = (Button) findViewById(R.id.btn1);
        b1.setOnClickListener(this);
        Button b2 = (Button) findViewById(R.id.btn2);
        b2.setOnClickListener(this);
        EditText e1 = (EditText) findViewById(R.id.etn1);

        // Stack
        stack = new Stack();
    }

    @Override
    public void onClick(View v) {
        TextView t1 = (TextView) findViewById(R.id.tvn);

        // Get id
        x =  e1.getId();

        if (v.getId()== R.id.btn1) {

            // Push
            stack.push(x);

            EditText e1 = (EditText) findViewById(R.id.etn1);
            e1.setId(0);

            t1.setText("Pushed");
            t1.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left));
        }
        else if (v.getId() == R.id.btn2) {

            if (stack.empty()) {
                // Show message
                Toast.makeText(getApplicationContext(), "Stack is empty!", Toast.LENGTH_SHORT).show();
            } else {
                // Pop
                stack.pop();

                t1.setText("Poped");
               t1.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left));
            }
        }
    }
}

希望这会有所帮助〜