我在一个片段中启动我的活动但是变量变为空?

时间:2017-09-22 19:51:49

标签: java android android-fragments android-activity nullpointerexception

这是活动类的代码。

public class Form1Activity extends MainActivity {
    private EditText factory_name,cell_no, _email:
    private Spinner meter_type_spinner;
    private Button form1submitbutton;

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

        factory_name = (EditText) findViewById(R.id.factorynameTF);
        cell_no = (EditText) findViewById(R.id.cellnoTF);
        _email = (EditText) findViewById(R.id.emailTF);

        meter_type_spinner = (Spinner) findViewById(R.id.metertypedropdown);

        form1submitbutton = (Button) findViewById((R.id.form1submitbtn));

        List<String> metertype = new ArrayList<>();
        metertype.add("day");
        metertype.add("night");
        ArrayAdapter<String> adpterMeterType = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, metertype);
        adpterMeterType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        meter_type_spinner.setAdapter(adpterMeterType);
    }

以下是我调用活动的片段代码。知道请告诉我我做错了什么。我应该在片段中进行所有字段处理,还是为每个片段创建一个单独的活动来执行视图的工作,例如编辑tex,spinners等。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.form1, container, false);
    context = rootView.getContext();
    Intent intent = new Intent(context, Form1Activity.class);
    startActivity(intent);

    return rootView;
}

1 个答案:

答案 0 :(得分:0)

尝试:

Intent intent = new Intent(getActivity(), Form1Activity.class);
getActivity().startActivity(intent);

而不是

`Intent intent = new Intent(context, Form1Activity.class)`;
startActivity(intent);