Search code examples
javaandroidandroid-cursorloader

cursorLoader in androidstudio


I'm a super beginner so I'm just following some project and I knew that startActivityforResult has been deprecated, so I changed the code by using ActivityResultLauncher. But I don't know how to fix CursorLoader error. Can you tell me how to fix it?

So the original code was this.

 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        
        if(requestCode == PICK_PROFILE_FROM_ALBUM && resultCode == RESULT_OK) {

            String[] proj = {MediaStore.Images.Media.DATA};

            CursorLoader cursorLoader = new CursorLoader(this, data.getData(), proj, null, null, null);
            


            Cursor cursor = cursorLoader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();

            //image path
            String photoPath = cursor.getString(column_index);

           
    }

This is the current code

ActivityResultLauncher<Intent> startActivityResult = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    
                    if(result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        String[] proj = {MediaStore.Images.Media.DATA};

                        CursorLoader cursorLoader = new CursorLoader(this, data.getData(), proj, null, null, null);
                       

                        Cursor cursor = cursorLoader.loadInBackground();
                        int column_index =cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        cursor.moveToFirst();

                        
                        String photoPath = cursor.getString(column_index);
 }

So the context in CursorLoader should be fixed. It needs 'Context' but it is ActivityResultCallback now.


Solution

  • It is typical situation in long running Projects that sometimes You will need to migrate Your existing code base to newer API.

    About CursorLoader. If startActivityResult Launcher is field inside your Activity This line

    CursorLoader cursorLoader = new CursorLoader(this, data.getData(), proj, null, null, null);
    

    can be replaced with

    CursorLoader cursorLoader = new CursorLoader(YourActivityClass.this, data.getData(), proj, null, null, null);
    

    I also see that cursor is loaded on UI Thread and it can have an impact on performance