问题
Image is copied from assets directory to internal storage directory and new image is successfully found in the directory using Android Studio's Device File Explorer. But UI is blank. What am I missing here?
public class MainActivity extends AppCompatActivity {
Context context;
private final String assetImage = "qtest1.png";
boolean isDirectoryCreated;
private ImageView myImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImageView = findViewById(R.id.imageview);
context = getApplicationContext();
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(assetImage);
File dir = new File(context.getFilesDir().getAbsolutePath());
isDirectoryCreated = dir.mkdirs();
out = new FileOutputStream(dir + File.separator + "qtest1InStor.png");
copyFile(in, out);
} catch (IOException e) {
//
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
// NOOP
}
}
}
File imgInStor = new File(context.getFilesDir().getAbsolutePath() + File.separator + "qtest1InStor.png");
if (imgInStor.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imgInStor.getAbsolutePath());
myImageView.setImageBitmap(bitmap);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="testpng" />
</androidx.constraintlayout.widget.ConstraintLayout>
来源:https://stackoverflow.com/questions/61846723/android-copy-internal-storage-image-to-imageview