How to access packagemanager in viewmodel - android-studio

I was using fragment and now I attached ViewModel to it and was transferring code to ViewModel and activity?.packageManager?.getPackageInfo(uri, PackageManager.GET_ACTIVITIES) this line shows an error. How can I access package manager in ViewModel?

On way is to extend AndroidViewModel instead of ViewModel as:
class MyFragmentViewModel(application: Application) : AndroidViewModel(application) {
...
Now you can call:
application.packageManager?.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)

Theoretically if you are implementing MVVM pattern (I see you implementing ViewModel), android.* layer should be handled in the View, Activities/Contexts shouldn't be managed in the ViewModel to avoid Memory Leaks. Even though, depending on the project context, of course this rule doesn't apply to every single project context, I think the best approach would be (if not Dependency Injection is been used) to have an Application Provider.
Create an object:
object ApplicationProvider {
#Volatile
lateinit var application: Application
fun initialize(_application: Application) {
if (!::application.isInitialized) {
synchronized(this) {
application = _application
}
}
}
}
In your MainActivity, initialise the ApplicationProvider as the following:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
ApplicationProvider.initialize(this.application)
}
Now you can access the ApplicationContext in your whole project where is needed with:
ApplicationProvider.application.applicationContext
Remember to not assign ApplicationContext to static fields (as a val e.g.) to avoid Memory Leaks.
PD: I'm not very fan of AndroidViewModel, but I guess it is a good solution as well, as a colleague mentioned before :D

Related

Passing data from one fragment to another (Kotlin)

I have a project with 2 fragments. I am looking to pass an iterable from the first fragment to the second. Using navArgs is not an option, since it makes the program crash. Bundle seems to only work with primary data types. Is there a way to go about it, without using some super hacky solution, like passing a string of all the data separated by commas as a string?
The modern way to do this is with a ViewModel (here and here or with the FragmentResult API (last link). Otherwise you're looking at doing it manually through the parent Activity - call a function on the Activity that passes your data to the other Fragment, that kind of thing.
If these Fragments are in separate Activities then you're looking at making your data Parcelable so it can go in a Bundle, or serialisation (e.g. the Kotlin Serialization library) so you can put it in a Bundle as a String, or persist it on disk so you can load it from the next Activity. Serialisation libraries are a robust way of turning objects and data into a stream of text (and other formats if you like) but there's nothing wrong with a String and some separator character if it's all you need, e.g. storing a list of indices or IDs
You can use a shared view model.
In your first fragment:
<code>class FirstFragment : Fragment() {
private lateinit var viewModel: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class.java)
viewModel.setData(yourIterable)
}
}
</code>
In your second fragment:
<code>class SecondFragment : Fragment() {
private lateinit var viewModel: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class.java)
val data = viewModel.getData()
}
}
</code>
And your <code>SharedViewModel</code>:
<code>class SharedViewModel : ViewModel() {
private val _data

How to update the listview from another thread with kotlin

I'm learning Android studio with Kotlin, I have setup one listview in Oncreate, it list out user data, then I have another function onOptionItemSelected which add/delete user data item, the problem is : after I add/delete from another function, the data on listview cannot be updated:
Here is my code:
class MainActivity : AppCompatActivity() {
private lateinit var listView : ListView
override fun onCreate(savedInstanceState: Bundle?) {
.....
listView = findViewById(R.id.listview_main)
val adapter2 = listViews(this, array_firstname, array_lastname,array_age)
listView.adapter = adapter2
....
override fun onOptionsItemSelected(item: MenuItem): Boolean {
........
GlobalScope.launch {
db1.UsersDao().insertAll(User_tb(0,firstName, lastName, userAge))
(listView.adapter as listViews).notifyDataSetChanged()
}
With this, I got error "Only the original thread that created a view hierarchy can touch its views."
I searched internet and found I need to use runOnUiThread, then I below part under "listView.adapter = adapter2", but it still does not work:
Thread(Runnable {
this#MainActivity.runOnUiThread(java.lang.Runnable {
(listView.adapter as listViews).notifyDataSetChanged()
})
}).start()
I guess I did not understand runOnUiThread correctly but cannot figure out how, could somebody help?
Thanks!
You don't need to mess with Threads directly since you're using coroutines.
Replace this:
GlobalScope.launch {
db1.UsersDao().insertAll(User_tb(0,firstName, lastName, userAge))
(listView.adapter as listViews).notifyDataSetChanged()
}
with this:
lifecycleScope.launch {
withContext(Dispatchers.IO) {
db1.UsersDao().insertAll(User_tb(0,firstName, lastName, userAge))
}
listView.adapter.notifyDataSetChanged() // your cast was unnecessary
}
lifecycleScope runs on the UI thread, except where you wrap the code using withContext to run in the background. So after the withContext block is done, it automatically returns to the main UI thread to run your last line.
This scope also gives you leak protection. If the Activity is closed before the job is done, the coroutine is automatically cancelled and the view elements can be freed to the GC. It won't try to run the last line that updates the UI.
Also, a tip: Your class names should start with a capital letter so they are clearly distinguishable from variable/property names. And they should be more descriptive. For example, I would change the listviews class name to something like UserListAdapter.

How can I run code in JUnit before Spring starts?

How can I run code in my #RunWith(SpringRunner.class) #SpringBootTest(classes = {...}) JUnit test before Spring starts?
This question has been asked several times (e.g. 1, 2) but was always "solved" by some configuration recommendation or other, never with a universal answer. Kindly don't question what I am about to do in that code but simply suggest a clean way to do it.
Tried so far and failed:
Extend SpringJUnit4ClassRunner to get a class whose constructor can run custom code before initializing Spring. Failed because super(testClass) must be called first thing and already does a whole lot of things that get in the way.
Extend Runner to get a class that delegates to SpringRunner instead of inheriting it. This class could run custom code in its constructor before actually instantiating the SpringRunner. However, this setup fails with obscure error messages like java.lang.NoClassDefFoundError: javax/servlet/SessionCookieConfig. "Obscure" because my test has no web config and thus shouldn't meddle with sessions and cookies.
Adding an ApplicationContextInitializer that is triggered before Spring loads its context. These things are easy to add to the actual #SpringApplication, but hard to add in Junit. They are also quite late in the process, and a lot of Spring has already started.
One way to do it is to leave out SpringRunner and use the equivalent combination of SpringClassRule and SpringMethodRule instead. Then you can wrap the SpringClassRule and do your stuff before it kicks in:
public class SomeSpringTest {
#ClassRule
public static final TestRule TestRule = new TestRule() {
private final SpringClassRule springClassRule =
new SpringClassRule();
#Override
public Statement apply(Statement statement, Description description) {
System.out.println("Before everything Spring does");
return springClassRule.apply(statement, description);
}
};
#Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
#Test
public void test() {
// ...
}
}
(Tested with 5.1.4.RELEASE Spring verison)
I don't think you can get more "before" than that. As for other options you could also check out #BootstrapWith and #TestExecutionListeners annotations.
Complementing jannis' comment on the question, the option to create an alternative JUnit runner and let it delegate to the SpringRunner does work:
public class AlternativeSpringRunner extends Runner {
private SpringRunner springRunner;
public AlternativeSpringRunner(Class testClass) {
doSomethingBeforeSpringStarts();
springRunner = new SpringRunner(testClass);
}
private doSomethingBeforeSpringStarts() {
// whatever
}
public Description getDescription() {
return springRunner.getDescription();
}
public void run(RunNotifier notifier) {
springRunner.run(notifier);
}
}
Being based on spring-test 4.3.9.RELEASE, I had to override spring-core and spring-tx, plus javax.servlet's servlet-api with higher versions to make this work.

Does Dart/Flutter have the concept of weak references?

I'm in the early stages of learning Dart & Flutter. I'm looking at how to implement an eventbus, which works fine, but I've noticed that Widgets (and/or their associated state) hold a strong reference to the (global) eventbus, causing a memory leak. The solution is to cancel the subscription in the widget-state's dispose method, but I'd like to know if there's a better approach (I'm coming from Swift which allows variables to be declared as 'weak').
EDIT
I ended up subclassing the state as follows... any better suggestions?
abstract class CustomState<T extends StatefulWidget> extends State {
List<StreamSubscription> eventSubscriptions = [];
void subscribeToEvent(Object eventClass, Function callback) {
StreamSubscription subscription = eventBus.on(eventClass).listen(callback);
eventSubscriptions.add(subscription);
}
void dispose() {
super.dispose();
eventSubscriptions.forEach((subscription) => subscription.cancel());
eventSubscriptions = null;
}
}
class MyEvent {
String text;
MyEvent(this.text);
}
class _MyHomePageState extends CustomState<MyHomePage> {
#override
void initState() {
super.initState();
subscribeToEvent(MyEvent, onEventFired);
}
void onEventFired(event) {
print('event fired: ${event.runtimeType} ${event.text}');
}
}
Dart doesn't provide weak reference feature.
An Expando has a weak reference behavior though.
Not sure if this is of use in your use case.
https://api.dartlang.org/stable/1.24.3/dart-core/Expando-class.html
https://groups.google.com/a/dartlang.org/forum/m/#!topic/misc/S7GGxegtJe4
What is the Dart "Expando" feature about, what does it do?
https://github.com/dart-lang/sdk/issues/16172
I sometimes use a Mixin that provides a list where I can add subscriptions and a dispose methode that cancels all subscriptions and add it to widgets and other classes where I need it.
As of 2020, I'd like to add to Günter's answer that I've just published a package that goes as close as possible to a weak-reference by implementing a weak-map and a weak-container, as well as cache functions that take advantage of weak references.
https://pub.dev/packages/weak_map
It's much easier to use than an Expando (it uses Expando internally).
Since dart 2.17 you can use WeakReference.
Any object wrapped in WeakReference(obj) is not kept from being garbage collected.
You access the object via the target property which becomes null when the object got garbage collected.
final myWeakRef = WeakReference(ExampleObj());
// access obj, may be null
print(myWeakRef.target);

Guice and RequestScoped behaviour in multiple threads

I am using Guice's RequestScoped and Provider in order to get instances of some classes during a user request. This works fine currently. Now I want to do some job in a background thread, using the same instances created during request.
However, when I call Provider.get(), guice returns an error:
Error in custom provider, com.google.inject.OutOfScopeException: Cannot
access scoped object. Either we are not currently inside an HTTP Servlet
request, or you may have forgotten to apply
com.google.inject.servlet.GuiceFilter as a servlet
filter for this request.
afaik, this is due to the fact that Guice uses thread local variables in order to keep track of the current request instances, so it is not possible to call Provider.get() from a thread different from the thread that is handling the request.
How can I get the same instances inside new threads using Provider? It is possible to achieve this writing a custom scope?
I recently solved this exact problem. There are a few things you can do. First, read up on ServletScopes.continueRequest(), which wraps a callable so it will execute as if it is within the current request. However, that's not a complete solution because it won't forward #RequestScoped objects, only basic things like the HttpServletResponse. That's because #RequestScoped objects are not expected to be thread safe. You have some options:
If your entire #RequestScoped hierarchy is computable from just the HTTP response, you're done! You will get new instances of these objects in the other thread though.
You can use the code snippet below to explicitly forward all RequestScoped objects, with the caveat that they will all be eagerly instantiated.
Some of my #RequestScoped objects couldn't handle being eagerly instantiated because they only work for certain requests. I extended the below solution with my own scope, #ThreadSafeRequestScoped, and only forwarded those ones.
Code sample:
public class RequestScopePropagator {
private final Map<Key<?>, Provider<?>> requestScopedValues = new HashMap<>();
#Inject
RequestScopePropagator(Injector injector) {
for (Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) {
Key<?> key = entry.getKey();
Binding<?> binding = entry.getValue();
// This is like Scopes.isSingleton() but we don't have to follow linked bindings
if (binding.acceptScopingVisitor(IS_REQUEST_SCOPED)) {
requestScopedValues.put(key, binding.getProvider());
}
}
}
private final BindingScopingVisitor<Boolean> IS_REQUEST_SCOPED = new BindingScopingVisitor<Boolean>() {
#Override
public Boolean visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
return scopeAnnotation == RequestScoped.class;
}
#Override
public Boolean visitScope(Scope scope) {
return scope == ServletScopes.REQUEST;
}
#Override
public Boolean visitNoScoping() {
return false;
}
#Override
public Boolean visitEagerSingleton() {
return false;
}
};
public <T> Callable<T> continueRequest(Callable<T> callable) {
Map<Key<?>, Object> seedMap = new HashMap<>();
for (Map.Entry<Key<?>, Provider<?>> entry : requestScopedValues.entrySet()) {
// This instantiates objects eagerly
seedMap.put(entry.getKey(), entry.getValue().get());
}
return ServletScopes.continueRequest(callable, seedMap);
}
}
I have faced the exact same problem but solved it in a different way. I use jOOQ in my projects and I have implemented transactions using a request scope object and an HTTP filter.
But then I created a background task which is spawned by the server in the middle of the night. And the injection is not working because there is no request scope.
Well. The solutions is simple: create a request scope manually. Of course there is no HTTP request going on but that's not the point (mostly). It is the concept of the request scope. So I just need a request scope that exists alongside my background task.
Guice has an easy way to create a request scope: ServletScope.scopeRequest.
public class MyBackgroundTask extends Thread {
#Override
public void run() {
RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
try ( RequestScoper.CloseableScope ignored = scope.open() ) {
doTask();
}
}
private void doTask() {
}
}
Oh, and you probably will need some injections. Be sure to use providers there, you want to delay it's creation until inside the created scope.
Better use ServletScopes.transferRequest(Callable) in Guice 4

Resources