开发者

Android context from tab activity

开发者 https://www.devze.com 2023-03-07 12:28 出处:网络
I have a helper class that I need context so I can access the SharedPrefences. Other posts recommend passing in the application context on instantiation of the helper class. So I made that change, it

I have a helper class that I need context so I can access the SharedPrefences. Other posts recommend passing in the application context on instantiation of the helper class. So I made that change, it works very well except within a ta开发者_运维技巧b activity. The tab activity need to call a webservice to determine what data to display. The helper class makes the webservice call.


You can call getContext() from any activity. If the helper class is defined as a subclass of the activity, it can call it directly. Otherwise, passing the context through instantiation would be my second choice. I agree, it's not pretty passing contexts everywhere. There are probably some complicated OOP patterns you could use to avoid this, but I can't see it being an advantage overall.


If you get a null pointer you might be calling the function too early. In what function are you calling it?

0

精彩评论

暂无评论...
验证码 换一张
取 消