简体   繁体   中英

Android: Update TextView from Non-Activity Class

I am writing an Android App and i need to display some results from a non-activity class. Basically my App gets the current location, activity and other things, and on those i run some functions, for example to check if the user has been at that place before. Anyway, an intent triggers these functions, and at the end of the function I want to update a TextView with the result of these functions.

But it doesn't seem to work from anywhere besides MainActivity. I tried making the TextView static, but that doesn't seem to work, and returning the results to MainActivity is not possible either in since it is not called directly from MainActivity.

Does some have an idea on how to solve this problem? This is my first android project, so there's still a lot of thing i don't know about. Thank you!

I don't know exactly what your code looks like, but do you have a model class that holds all your data (for example, some kind of singleton)? If so, you could just save the updated text there, and then update the TextView in a callback method.

If that doesn't fit what you're doing, I would considering refactoring your code so that the text you want is sent back to your MainActivity. You mentioned that the method is not called directly, but could your calculations pass the text to an intermediate class, which passes it to your MainActivity?

You should not update the ui drom background thread. If you want to update the ui from background thread use Handlers,AsyncTask or use some other thread concepts.

If you want to update the UI fro Service or Broadcast receiver for eg you receive a message inside onReceive of broadcasrReceiver now to update the ui use sendBroadcast and inside your activity registet a dynamic Broadcast receiver and then update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM