在SecondActivity中: 复制 // 获取Intent中的Bitmap对象 Bitmap bitmap = (Bitmap) getIntent().getExtras().get("photo"); // 将Bitmap对象设置为ImageView的源 ImageView imageView = (ImageView) findViewById(R.id.imageView); imageView.setImageBitmap(bitmap);这段代码是写在onCreate里面吗
时间: 2024-01-22 15:17:55 浏览: 28
是的,这段代码应该写在 `onCreate()` 方法中,以在活动创建时设置 ImageView 的图像。例如:
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// 获取Intent中的Bitmap对象
Bitmap bitmap = (Bitmap) getIntent().getExtras().get("photo");
// 将Bitmap对象设置为ImageView的源
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
}
```
在这个例子中,先调用 `setContentView()` 方法来设置布局,然后获取 Intent 中传递的 Bitmap 对象,并将其设置为 ImageView 的图像。
相关问题
bundle = this.getIntent().getExtras();中的bundle为null
这种情况可能是因为Intent没有设置Extras导致的,或者是在调用getIntent().getExtras()方法时,Intent对象还没有被完全初始化。你可以先通过Log等方式打印出Intent对象,确认是否设置了Extras。如果Intent对象中没有设置Extras,可以通过以下方式设置:
```java
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("key", "value");
intent.putExtras(bundle);
```
如果Intent对象中已经设置了Extras,那么可以尝试在调用getIntent().getExtras()之前先调用一次getIntent()方法,以确保Intent对象已经被完全初始化:
```java
Intent intent = getIntent();
if(intent != null && intent.getExtras() != null) {
Bundle bundle = intent.getExtras();
// do something with bundle
} else {
// handle null case
}
```
android.os.FileUriExposedException: file:///storage/emulated/0/temp.png exposed beyond app through Intent.getData()
这个问题通常出现在 Android 7.0 及以上版本中,是由于 Android 7.0 引入了一项安全机制,禁止应用使用 file:// URI 访问其他应用或用户的文件。解决此问题的方法是使用 FileProvider 来共享文件。您可以按照以下步骤解决此问题:
1. 在 Manifest 文件中添加一个 FileProvider:
```
<application>
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
...
</application>
```
2. 在 res/xml 文件夹中创建一个 provider_paths.xml 文件,指定要共享的文件路径:
```
<paths>
<external-path name="external_files" path="."/>
</paths>
```
3. 在代码中使用 FileProvider 获取文件的 URI:
```
File file = new File(getExternalFilesDir(null), "temp.png");
Uri uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
```
4. 在 Intent 中使用获取到的 URI:
```
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
```
这样就可以避免出现文件 URI 暴露的问题。