2017-04-18 44 views
-1

任何你之前告訴我,這已經回答過很多次了,讓我澄清大多數那些誰問過這個問題提出的給了錯誤的觀點ID或視圖中正確的內容查看被扔空指針設置與TextView所在位置不同的ContentView。我已經在不同的地方使用這個函數,它工作正常。我試過在TextView.setText()中使用字符串文字,但它是徒勞的。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

可能重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i -fix-it) –

回答

0

不要設置通佈局ID一樣,直接R.layout.contactstory函數,而不是使用佈局充氣器充氣佈局如下代碼

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

工作。非常感謝你。 :d –