OnClickListener对空对象的引用

时间:2015-11-14 20:00:59

标签: android onclick onclicklistener

你好任何人都可以帮我处理这个错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at de.kwietzorek.fulcrumwebview.MainActivity$AddServerFragment.onCreateView(MainActivity.java:141)

141是btn_back.setOnClickListener(new View.OnClickListener() {

片段:AddServerFragement

public class AddServerFragment extends Fragment
        implements View.OnClickListener {

    @Override
        public void onClick(View view) {
        }

    public AddServerFragment(){
    }

    Button btn_back, btn_add;
    EditText server_ip, server_name;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.add_ip, container, false);

        server_ip = (EditText) findViewById(R.id.edit_server_address);
        server_name = (EditText) findViewById(R.id.edit_server_name);

        btn_back = (Button) findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }
        });

        btn_add = (Button) findViewById(R.id.btn_add);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String new_server_ip = null, new_server_name = null;

                ArrayList<String> server_name_list = new ArrayList<String>();
                ArrayList<String> server_ip_list = new ArrayList<String>();

                new_server_ip = server_ip.getText().toString();
                server_ip_list.add(new_server_ip);

                new_server_name = server_name.getText().toString();
                server_name_list.add(new_server_name);
            }
        });

        return view;
    }
}

2 个答案:

答案 0 :(得分:2)

替换

    btn_back= (Button) findViewById(R.id.btn_back);

    btn_back = (Button) view.findViewById(R.id.btn_back);

对您要启动的所有其他布局元素执行相同的操作。

原因是:由于你在片段中夸大了一个布局文件,你必须将所有的UI元素引用到那个文件,你打电话给#34;查看&#34;在这里:

     View view = inflater.inflate(R.layout.add_ip, container, false);

所以istruction&#34; findViewById&#34;必须提到该视图。

答案 1 :(得分:1)

您需要在充气的视图中找到视图:

btn_back = (Button) view.findViewById(R.id.btn_back);