我的应用会收集很长的数字并将它们添加到数组中。我想将它们添加到Viewgroup
(在捕获数字的时候),但我得到NullPointerException
。
扩展片段:
public class detailed extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContainerView = (ViewGroup) findViewById(R.id.container); //Viewgroup container (item list)
return inflater.inflate(R.layout.detailed_nodata, container, false);
}}
addView
代码:
private void addItem() {
// Instantiate a new "row" view.
findViewById(android.R.id.empty).setVisibility(View.GONE);
final ViewGroup newView = (ViewGroup) LayoutInflater.from(getApplicationContext()).inflate(
R.layout.detailed, mContainerView, false);
((TextView) newView.findViewById(android.R.id.text1)).setText(String.valueOf(dtotal));
// Set a click listener for the "X" button in the row that will remove the row.
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Remove the row from its parent (the container view).
// Because mContainerView has android:animateLayoutChanges set to true,
// this removal is automatically animated.
mContainerView.removeView(newView);
// If there are no rows remaining, show the empty view.
if (mContainerView.getChildCount() == 0) {
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
}
});
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
mContainerView.addView(newView, 0);
return;
}
logcat的:
09-28 21:43:58.480 9965-9965/com.jawright.cruisespeed E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3633)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at android.view.View$1.onClick(View.java:3628)
... 11 more
Caused by: java.lang.NullPointerException
at com.jawright.cruisespeed.MainActivity.addItem(MainActivity.java:703)
at com.jawright.cruisespeed.MainActivity.testClick(MainActivity.java:372)
答案 0 :(得分:3)
尝试在mContainerView
的{{1}}方法中获取对onActivityCreated
的引用。