Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM startActivityForResult

Tags:

android

mvvm

When a view is clicked, startActivityForResult should be called. But I cannot call startActivityForResult in viewModel. How can I achieve it?

like image 399
MarStarck Avatar asked Apr 13 '18 10:04

MarStarck


People also ask

Can startActivityForResult still be used?

onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.

What is startActivityForResult?

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.

What is the replacement of startActivityForResult?

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.

What is request code startActivityForResult?

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.


1 Answers

I have read the google samples here (https://github.com/googlesamples/android-architecture/tree/todo-mvvm-databinding) and find the solution:

  1. create a interface to implement:

    public interface TaskItemNavigator {
        void openTaskDetails(String taskId);
    }
    
  2. have a weak reference in view model:

    @Nullable
    private WeakReference<TaskItemNavigator> mNavigator;
    
  3. 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);
        }
    }
    
like image 137
MarStarck Avatar answered Oct 19 '22 18:10

MarStarck