I am trying to set an image from the sdcard to an ImageView
, but it does not work. What am I doing wrong? I am sure that the file exists.
Here is code for MainActivity
:
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = findViewById(R.id.imageView);
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Naruto_newshot.png";
File file = new File(filePath);
if (file.exists())
imageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
}
}
Here is the code for the XML
layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
The AndroidManifest.xml
:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mbo.testimage">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
...
</application>
</manifest>
Finally the image 200 × 149 pixels :