How do I use setText from within a callback?

你离开我真会死。 提交于 2020-01-25 20:19:28

问题


In my code below I am able to edit a text from my first setText() call but not from within the callback.
The error I receive is a NullPointerException for title in the callback.
How do I set this up so I can edit the text from within the callback?

public class ListingActivity extends AppCompatActivity {
    final String TAG = "ListingActivity";
    TextView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        title = (TextView)findViewById(R.id.tvTitle);

        Intent intent = getIntent();
        final String listingId = intent.getStringExtra("ObjectId");

        setContentView(R.layout.listing_activity);
        Log.e(TAG, "listingId: " + listingId);

        title.setText("listingId");//fine

        ListingManager.getListing(listingId, new ListingCB() {
            @Override
            public void done(String error, Listing listing) {
                title.setText("listingId");//null pointer error
            }
        });
    }
}

回答1:


Your setContentView() method must be called before giving references using findViewById() method, so your code will be -

    public class ListingActivity extends AppCompatActivity {
    final String TAG = "ListingActivity";
    TextView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listing_activity);

        title = (TextView)findViewById(R.id.tvTitle);

        Intent intent = getIntent();
        final String listingId = intent.getStringExtra("ObjectId");

        Log.e(TAG, "listingId: " + listingId);

        title.setText("listingId");//fine

        ListingManager.getListing(listingId, new ListingCB() {
            @Override
            public void done(String error, Listing listing) {
                title.setText("listingId");//null pointer error
            }
        });
    }
}



回答2:


title.setText("listingId");//fine

That shouldn't be fine...

You must put setContentView before any findViewById. That is number one reason why your TextView is null.

Your callback is fine.



来源:https://stackoverflow.com/questions/42477995/how-do-i-use-settext-from-within-a-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!