NullPointer为TextView赋值时发生异常

时间:2014-04-15 08:34:00

标签: java android eclipse android-layout android-intent

我只想将值从一个活动传递到另一个活动,但无法从视图中找到Textview值。我只是通过文本框将一条消息从主活动传递到此活动,我看到了文本框值这里但不能将其分配给textView ...

这是我的代码..

public class DisplayMessageActivity extends Activity {

private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new   PlaceholderFragment()).commit();
    }

    textView = (TextView) findViewById(R.id.displayText);
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    textView.setText(message);


}

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.activityapps.DisplayMessageActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/displayText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="TextView" />

请帮帮我..

2 个答案:

答案 0 :(得分:2)

TextView不属于“活动”布局。将TextView的初始化移至onCreateView的{​​{1}}。

PlaceholderFragment

活动

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_display_message, container, false);
    TextView textView = (TextView) rootView.findViewById(R.id.displayText);
    return rootView;
}

然后

   if (savedInstanceState == null) {
   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
   Bundle bundle = new Bundle();
   bundle.putString("key", message);
   PlaceholderFragment fragobj = new   PlaceholderFragment();
   fragobj.setArguments(bundle);
        getFragmentManager().beginTransaction()
                .add(R.id.container,  fragobj).commit();
    }

答案 1 :(得分:0)

View view = inflater.inflate(R.layout.fragment_display_message, container, false);
TextView textView = (TextView) view.findViewById(R.id.displayText);
return view; //in onCreate method

您已经从可以使用的活动中扩展了

 TextView textView = (TextView) findViewById(R.id.displayText);
  //in onCreate method