android-Textview.settext()提供nullpointer异常

这是调用textview并获得意图的活动

package com.example.smartbrowser;

import android.os.Bundle;

import android.app.Activity;

import android.content.Intent;

import android.view.Menu;

import android.widget.TextView;

public class MainActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

TextView vw =(TextView) findViewById(R.id.text);

Intent intent =getIntent();

String message = intent.getStringExtra(Browseractivity.Message);


vw.setText(message);


setContentView(R.layout.activity_main);
    }


}

和activity_main.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=".MainActivity" >


 <TextView

  android:id="@+id/text"

  android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:layout_alignParentLeft="true"

  android:layout_alignParentTop="true"


  />


</RelativeLayout>

为什么在MainActivity.java中出现空指针异常?

解决方法:

您必须放置setContentView(R.layout.activity_main);在初始化任何视图之前.在这里,在设置内容视图之前初始化了TextView,这就是为什么它返回null的原因.

@Override 
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView vw =(TextView) findViewById(R.id.text);

    Intent intent =getIntent();

    String message = intent.getStringExtra(Browseractivity.Message);
    vw.setText(message);
}
上一篇:使用名为JPQL的查询调用方法时,.jsp处的java-NullPointerException


下一篇:Android-Cocos 2D NullPointer异常