【问题标题】:Textview.setText throwing nullpointer despite the view being in the correct contentView尽管视图位于正确的 contentView 中,但 Textview.setText 仍会抛出空指针
【发布时间】:2017-04-18 10:25:14
【问题描述】:

在你们中的任何人告诉我这个问题之前已经回答过很多次之前,让我澄清一下大多数提出这个问题的人要么给出了错误的视图 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)

【问题讨论】:

标签: java android nullpointerexception textview settext


【解决方案1】:

不要像 R.layout.contactstory 那样直接设置 pass layout id 而是使用 layout inflater 来膨胀布局,如下代码所示

View view = LayoutInflater.from(context).inflate(R.layout.contactstory,null);
dialog.setContentView(view);
TextView t1=(TextView)view.findViewById(R.id.textyman);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2015-12-28
    • 2014-06-06
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多