When a view is clicked, startActivityForResult should be called. But I cannot call startActivityForResult in viewModel. How can I achieve it?
onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.
The android startActivityForResult method, requires a result from the second activity (activity to be invoked). In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.
Among the contracts available, the StartActivityForResult contract is the replacement to the startActivityForResult . The callback is to be called once the activity result is available.
The request code is any int value. The request code identifies the return result when the result arrives. ( You can call startActivityForResult more than once before you get any results. When results arrive, you use the request code to distinguish one result from another.
I have read the google samples here (https://github.com/googlesamples/android-architecture/tree/todo-mvvm-databinding) and find the solution:
create a interface to implement:
public interface TaskItemNavigator {
void openTaskDetails(String taskId);
}
have a weak reference in view model:
@Nullable
private WeakReference<TaskItemNavigator> mNavigator;
implement it in activity:
public class TasksActivity extends AppCompatActivity implements TaskItemNavigator{
...
@Override
public void openTaskDetails(String taskId) {
Intent intent = new Intent(this, TaskDetailActivity.class);
intent.putExtra(TaskDetailActivity.EXTRA_TASK_ID, taskId);
startActivityForResult(intent, AddEditTaskActivity.REQUEST_CODE);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With