TextView不能在自定义方法中工作,但只能在onCreate();中工作;



我的文本视图没有按我希望的方式运行。当从我的recyclerView适配器调用newInstance时(按下项目时),它会将用户带到一个新的"活动",以显示有关按下的项目的信息。

但是,当我在newInstance方法中使用我的文本视图时,演示文本"hello"不会显示,我会得到一个NullPointerException,但在onCreate中它可以工作。

我得到的错误是:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
com.example.muddii.traveldiary.TravelDiary.ShowNoteActivity.newInstance(ShowNoteActivity.java:54)    

//Textview location works her and shows "helloooo" when it is in here
   @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.show_notepage);
    getSupportActionBar().setTitle("Holiday at Red Sea");
    getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    location = (TextView)findViewById(R.id.showLocation);
    location.setText("helloooo");

}

//Textview location dosn't work here
public static Intent newInstance(Context packageContext, long timestampID){

    Intent intent = new Intent(packageContext, ShowNoteActivity.class);
    Realm realm = Realm.getInstance(App.getAppContex());
    TravelNote getRowItem = realm.where(TravelNote.class).equalTo("timestamp", timestampID).findFirst();
    //getRowItem.getLocation().toString();

    location.setText("helloooo");
    return intent;
}

newInstance在RecyclerView中被称为我的viewHolder:

@Override
    public void onClick(View v) {
        Toast.makeText(App.getAppContex(), "" + getAdapterPosition(),Toast.LENGTH_SHORT).show();
        ShowNoteActivity showNoteActivity = new ShowNoteActivity();
        Intent intent = showNoteActivity.newInstance(App.getAppContex(),travelDiaries.get(getAdapterPosition()).getTimestamp());
        context.startActivity(intent);

    }

不能从静态引用中引用非静态字段。

静态块首先执行,在静态块中只能使用静态字段。

这里的位置没有得到任何引用,静态块尝试执行它。

newInstance()何时被调用,它如何知道布局文件是什么?

由于它是一个静态方法,它不知道类中的其他字段,主要是location字段。

我假设您的类是通过newInstance()方法初始化的,该方法将在onCreate方法之前调用,因此,您的布局还没有被膨胀并设置为内容视图,因此位置文本字段还不存在。

即使使用location的静态实例,您仍然会得到一个空指针,因为您将有以下两种情况之一

  1. 您将没有加载布局文件(即setContentView)
  2. 您之前已经加载了内容视图,因此您的静态变量现在将指向已回收视图中的文本视图

确保您只在调用后访问位置变量

location = (TextView)findViewById(R.id.showLocation);

最新更新