片段中的TextView“在空对象引用上”

时间:2018-08-23 11:37:11

标签: android nullpointerexception

我有一个片段

public class Player extends Fragment {

private TextView songTitleLabel,songNameSinger;
private View view;
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.player, container, false);

    // All player buttons
    songTitleLabel = view.findViewById(R.id.Title);
    songNameSinger = view.findViewById(R.id.singer);
    return view;
}

在同一片段中有一个方法可以做到这一点

public void playSong(String id ,String Singer) {
   songTitleLabel.setText(id);
   songNameSinger.setText(Singer);       
}

我在主要活动中将此方法称为

String name = CardList.get(position).getId();
String singer = CardList.get(position).getSinger();
Player player = new Player();
player.playSong(name,singer);

并且我确保当字符串转到Fragment方法时它不会变成null,所以我放了一个Log并看到了它的not null,但是当我制作TextView.setText时它附带了这个错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

所以我尝试另一件事,我像这样由我自己设置值

songTitleLabel.setText("Value");

它确实起作用了,我不知道问题出在哪里... 谢谢大家...

1 个答案:

答案 0 :(得分:1)

仅创建该fragment的对象不会调用oncreateview of that fragment(您在其中初始化视图),因此您的TextView null

请像下面的示例一样从Activity调用您的片段方法

FragmentManager fm = getSupportFragmentManager();


Player fragment = (Player )fm.findFragmentById(R.id.fragment_id);
fragment.playSong(name,singer);

OR

Player fragment = (Player ) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.playSong(name,singer);