致命异常:运行简单的android程序时出现main和Null指针异常

时间:2013-12-09 16:38:03

标签: java android eclipse android-emulator

我试图在Android上做一些简单的事情。我创建了一个登录页面并继续工作。当我尝试创建弹出窗口时,会抛出致命异常。帮忙

NewProjectActivity.java

public class NewProjectActivity extends Activity {

    PopupWindow popUp;
    LinearLayout layout;
    TextView tv;
    LayoutParams params;
    LinearLayout mainLayout;
    boolean click = true;

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_project);
        TextView alertdetail = (TextView) findViewById(R.id.link_to_register);
        alertdetail.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (click) {
                    popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10);
                    popUp.update(50, 50, 300, 80);
                    click = false;
                } else {
                    popUp.dismiss();
                    click = true;
                }
            }
        });


        params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layout.setOrientation(LinearLayout.VERTICAL);
        tv.setText("Hi this is a sample text for popup window");
        layout.addView(tv, params);
        popUp.setContentView(layout);
        popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
        mainLayout.addView(alertdetail, params);
        setContentView(mainLayout);

    }

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

2 个答案:

答案 0 :(得分:3)

TextView电视未初始化且layout以及popUpmainLayout

对于相同的活动,你有setContentView两次没有错,但设计不好

答案 1 :(得分:0)

您的简单应用程序崩溃了,因为您已声明了这些变量: -

PopupWindow popUp;
LinearLayout layout;
TextView tv;
LayoutParams params;
LinearLayout mainLayout;

并仅初始化: -

        TextView alertdetail = (TextView) findViewById(R.id.link_to_register);

这称为传递引用。你需要为上面的

做同样的事情