我知道这些信息遍布互联网,但我无法终生弄清楚我做错了什么。当我尝试运行我的代码时,它会立即崩溃并出现空指针异常,但我似乎无法弄清楚为什么会发生这种情况或发生在哪里。我想我错过了一些相当简单的东西,但我是 android 新手,所以我不知道它是什么。这是代码:
主要活动:
public class MainActivity extends Activity implements GetConnInfoFragment.ConnInfoReceiver {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
GetConnInfoFragment frag = new GetConnInfoFragment();
fragmentTransaction.add(R.id.mainFragmentContainer, frag);
fragmentTransaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
....
获取ConnInfoFragment:
public class GetConnInfoFragment extends Fragment {
ConnInfoReceiver ownerActivity;
@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button goButton = (Button) getView().findViewById(R.id.connectButton);
goButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText portBox = (EditText) v.findViewById(R.id.portBox);
int port = Integer.parseInt(portBox.getText().toString());
EditText ipBox = (EditText) v.findViewById(R.id.ipAddressBox);
String address = ipBox.getText().toString();
// create sockets, might these be garbage collected ?
// in which case the main activity should create them. That makes
// more sense anyway
// activate next fragment -- call back up to the main activity to trigger this
ownerActivity.receiveConnInfo(port, address);
}
});
return inflater.inflate(R.layout.getconninfofragment, container, false);
}
这是错误消息:
E/AndroidRuntime(1470): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.htpccontrol/com.htpccontrol.MainActivity}: java.lang.NullPointerException
编辑:这是我的 getConnInfoFragment.xml 的 .xml 文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/ipAddressBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/enterIP" />
<EditText
android:id="@+id/portBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/enterPort" />
<Button
android:id="@+id/connectButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Connect" />
</LinearLayout>