What I am using is the new features of androidx.activity:
activity_version = "1.2.0-alpha06"
implementation "androidx.activity:activity:$activity_version"
Assume that there is a button. When I click it, it displays the images directory, and I can select several images at a time. After confirming the selection, I get a list of uris of selected images. The code looks like this:
package com.example.test_contracts;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button test_button=findViewById(R.id.test_button);
test_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityResultContracts.GetMultipleContents contracts=new ActivityResultContracts.GetMultipleContents();
ActivityResultLauncher<String> launcher=registerForActivityResult(contracts, new ActivityResultCallback<List<Uri>>() {
@Override
public void onActivityResult(List<Uri> result) {
//.....do something with the list of urls
}
});
launcher.launch("image/*");
}
});
}
}
This piece of code runs perfectly on Fragment, but when running on AppCompatActivity, some weird things occur, as I describe in title: the first time when I click the button, the images directory appears. After I comfirm the selection, return to the previous activity and click the button again, the app will crash immediately. The exception says: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode.
So I try to figure out why this happen. After setting a lot of breakpoints, I find that when I apply this piece of code on AppCompatActivity, the requestcode will be initally set to 65535, on the class ActivityResultRegistry; And when I launch the activity again, the requestcode +1 and set to 65536, which leads to the Exception.
private final AtomicInteger mNextRc = new AtomicInteger(0x0000ffff);
So I basically know a little about the cause. But why they set the requestcode so large? And how can I solve this problem?
User contributions licensed under CC BY-SA 3.0