-2
For some reason you can’t create a file.
W/System.err: java.io.IOException: No such file or directory
Follow the code below:
public class MainActivity extends AppCompatActivity {
ImageView imageView;
OutputStream outputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.image);
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File dir = new File(Environment.DIRECTORY_PICTURES);
dir.mkdir();
File file = new File(dir,System.currentTimeMillis() + ".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Toast.makeText(MainActivity.this, "Salve", Toast.LENGTH_SHORT).show();
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
And the xml:
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:id="@+id/image"
app:srcCompat="@drawable/mario"></ImageView>
<Button
android:id = "@+id/save"
android:text = "save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
And in the manifest I put the permissions to read and write
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and also gave permissions inside android.
I tried several different ways and it still doesn’t work, if I check the directory and/ or the file already exist, it indicates that it doesn’t exist, and when trying to create the file it returns the error No such file or directory
.
Does anyone have any idea what might be, or that I’m doing it wrong?
I’ll test it here
– Jabs
I tried here and in doing it says that can not change because only this in Read mode, I changed the say to
File dir = getDir(Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);
and it worked. vlw– Jabs
After a read on the use of Try catch and Finally will improve the writing of your code. [1]: https://www.devmedia.com.br/blocos-try-catch/7339
– Guilherme Oliveira
I’ve got it all wrong, I was doing some tests only kkkk
– Jabs