在你们之前告诉我之前已经多次回答过这个问题之前,让我澄清一下那些问过这个问题的大多数人提供了错误的视图ID或设置了与TextView所在位置不同的ContentView。我已经在不同的地方使用过这个功能了。我尝试在TextView.setText()中使用字符串文字,但这是徒劳的。
contactstory.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textyman"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="100dp"
android:text="TextView" />
<Button
android:id="@+id/close"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Close" />
</LinearLayout>
java文件中的函数
public void ShowStory(int pos)
{
final Dialog dialog = new Dialog(this);
dialog.setTitle(srcnames[pos]);
dialog.setContentView(R.layout.contactstory);
String username=getIntent().getStringExtra("username");
LoginDataBaseAdapter loginDataBaseAdapter=new
LoginDataBaseAdapter(this);
loginDataBaseAdapter.open();
String story=loginDataBaseAdapter.GetStory(pos,username);
TextView t1=(TextView)findViewById(R.id.textyman);
Button btnend=(Button)findViewById(R.id.close);
if(TextUtils.isEmpty(story)){
t1.setText(username+" hasn't added any story for this song");
}
else {
t1.setText(story); //Exception is thrown here
}
btnend.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
logcat的
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.sherry.escuchame.ContactInfo.ShowStory(ContactInfo.java:157)
at
com.example.sherry.escuchame.ContactInfo.onContextItemSelected
(ContactInfo.java:140)
at android.app.Activity.onMenuItemSelected(Activity.java:2660)
at android.support.v4.app.FragmentActivity.onMenuItemSelected
(FragmentActivity.java:408)
at
android.support.v7.app.AppCompatActivity.onMenuItemSelected
(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected
(WindowCallbackWrapper.java:113)
答案 0 :(得分:0)
不要像R.layout.contactstory那样直接设置传递布局ID,而是使用布局inflater来扩展布局,如下面的代码
View view = LayoutInflater.from(context).inflate(R.layout.contactstory,null);
dialog.setContentView(view);
TextView t1=(TextView)view.findViewById(R.id.textyman);