Cant save my files to phone storage Android - java

Hi I'm having a problem while making an app on Android Studio. I want the user to input some text and then click the save button, which should save the text file on my phone. I have the following code running without any errors, however it is not doing anything. I cant find the file that it is supposed to save in.
public class TakeNotes extends Activity implements View.OnClickListener {
String content = "";
File file;
FileOutputStream outputStream;
TextView tv;
Button btnSave;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_notes);
tv = (TextView) findViewById(R.id.txtInput);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
}
public void onClick(View v) {
if (v == findViewById(R.id.btnSave)) {
try {
file = new File(Environment.getExternalStorageDirectory(), "test.txt");
outputStream = new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

You need to add runtime permission in Android 6.0 (API Level 23) and up
This is the code for WRITE_EXTERNAL_STORAGE
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"Permission is granted");
return true;
}
Ask for permission else like this
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
Here is the official docs

You should include permissions in your AndroidManifest :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Related

How to show a pdf file from storage using AndroidPdfViewer library?

I want to load a pdf file from external storage (Download/Pdfs/myfile.pdf) using AndroidPdfViewer but it shows blank screen without any error. I tried lots of ways but it's not working.
public class PdfViewActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/Pdfs/myfile.pdf");
PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromFile(path).load();
I have a pdf file in my "Download/Pdfs/myfile.pdf" and i used the above code to load the file but it's not working.
I have given storage permission manually from settings.
Can anyone please correct me where i am making a mistake.
I have tested your code and it works just fine on Android 10 device. Your are missing something from the below:
1.In Android Manifest File add the READ_EXTERNAL_STORAGE permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
and inside application tag add requestLegacyExternalStorage to true to be able to have access on External Storage on Android 10 device and above.
<application
android:requestLegacyExternalStorage="true"
2.Verify that the pdf exists on the device under "/Download/Pdfs/myfile.pdf" path.
3.Change your activity using the below code by requesting External Storage permission at runtime first in onCreate method:
public class PdfViewActivity2 extends AppCompatActivity {
private static final int READ_STORAGE_PERMISSION_REQUEST_CODE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//check if Read External Storage permission was granded
boolean granded = checkPermissionForReadExtertalStorage();
if(!granded){
requestPermissionForReadExtertalStorage();
}
else {
readPdf();
}
}
public boolean checkPermissionForReadExtertalStorage() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int result = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
return false;
}
public void requestPermissionForReadExtertalStorage() {
try {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_STORAGE_PERMISSION_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case READ_STORAGE_PERMISSION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Read Pdf from External Storage
readPdf();
} else {
// permission denied. Disable the functionality that depends on this permission.
}
}
}
}
private void readPdf(){
File path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/Pdfs/myfile.pdf");
PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromFile(path).load();
}
}
First, add the library to your build.gradle file
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
To open a PDF file from storage, use this code. There are comments that explain what it does.
public class PdfViewActivity2 extends AppCompatActivity {
// Declare PDFView variable
private PDFView pdfView;
private final int PDF_SELECTION_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize it
pdfView = findViewById(R.id.pdfView);
// Select PDF from storage
// This code can be used in a button
Toast.makeText(this, "selectPDF", Toast.LENGTH_LONG).show();
Intent browseStorage = new Intent(Intent.ACTION_GET_CONTENT);
browseStorage.setType("application/pdf");
browseStorage.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(browseStorage, "Select PDF"), PDF_SELECTION_CODE);
}
// Get the Uniform Resource Identifier (Uri) of your data, and receive it as a result.
// Then, use URI as the pdf source and pass it as a parameter inside this method fromUri(Uri uri)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PDF_SELECTION_CODE && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedPdfFromStorage = data.getData();
pdfView.fromUri(selectedPdfFromStorage).defaultPage(0).load();
}
}
}
In an Android 10 device your app has no access to external storage.
Unless you add
android:requestLegacyExternalStorage="true"
in application tag of manifest file.
Instead of using fromFile() use fromSource(). i.e. Declare pathe as DocumentSource instead of File.
public class PdfViewActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DocumentSource path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/myfile.pdf");
PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromSource(path).load();

Permission to save text in storage android not working

I have build sample app for user to write some text and save it on internal storage.
Format TXT or pdf. I have tried on android Kitkat sdk 19 and It's working fine but when I tried on the latest android 9 I got denied could not save the text in internal storage
Edit : I wonder If have to manually create My files folder
What I'm I missing ?
AndroidManifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSaveTextBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mText = mResultEt.getText().toString().trim();
if(mText.isEmpty()){
Toast.makeText(MainActivity.this, "write text First...", Toast.LENGTH_SHORT).show();
}
else{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED){
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,WRITE_EXTERNAL_STORAGE_CODE);
}else {
saveToTxtFile(mText);
}
}else {
saveToTxtFile(mText);
}
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case WRITE_EXTERNAL_STORAGE_CODE: {
if (grantResults.length > 0 && grantResults[0]
== PackageManager.PERMISSION_GRANTED) {
//permission granted save data
saveToTxtFile(mText);
} else {
//permission denied
Toast.makeText(this, "Storage Permission required to store", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private void saveToTxtFile(String mText){
//get current time for file name
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(System.currentTimeMillis());
try{
//path tp storage
File path = Environment.getExternalStorageDirectory();
//create folder named "My file"
File dir = new File( path + "/My Files/");
dir.mkdirs();
//file name
String fileName = "MyFile_" + timestamp + ".txt";
File file = new File (dir, fileName);
//used to store characater in file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(mText);
bw.close();
//show file name and path where file saved
Toast.makeText(this, fileName+"is saved to\n" +dir, Toast.LENGTH_SHORT).show();
}catch (Exception e){
//if anything goes wrong
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
As suggested both Shashanth and kashyap answers.
This is just a workaround but it works.
I have added
android:requestLegacyExternalStorage="true"
to my <application> element in the AndroidManifest.xml file.
And changed the line
File path = Environment.getExternalStorageDirectory();
to
File path = new File(getExternalFilesDir(null).getAbsolutePath());
In your MainActivity you should check if permission is granted or not, then use != operator.
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {}
this line should be-
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){}

Android - Permission to use Camera and Write to External Storage

I am trying to ask for permission to use the Camera and Writing to External Storage.
My Main Activity is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
{
if(checkSelfPermission(Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{android.Manifest.permission.CAMERA});
}
}
if(ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_PERM_WRITE_STORAGE);
}
else
{
takePhoto(); // calls this method
}
}
});
}
I have included in my Manifest.xml:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I get this error:
cannot find symbol method requestPermissions(MainActivity,String[])
cannot find symbol method checkSelfPermission(Context,String)
What is it that I am doing wrong. Thanks
For the request camera part try this
final int RequestCameraPermissionID = 1001;
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.CAMERA},RequestCameraPermissionID);

Android create directory in internal storage not works in Android 7.0?

I am using this code in async to create directory if not exists in android with permissions. My code sucessfully works in android 5.1 but when i deployed app in android 7.0 the directory not created automatically
File sdcard = Environment.getExternalStorageDirectory() ;
File folder = new File(sdcard.getAbsoluteFile(), "Quoteimages");
if(!folder.exists()){
folder.mkdir();
}
Manifest file is
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
Link to detail of application apk App apk detail link
Now what should i do i want to create folder write images from url to it and then read them. This work for me in android 5.1 but not in Android version 7 .
You need to implement runtime permissions for android versions above lollipop
Maybe this piece of code will help you:
private static final int PERMS_REQUEST_CODE = 123;
//...........................................................................................................
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]
{android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
ListItem listItem = new ListItem();
Glide.with(getApplicationContext()).asBitmap().load(listItem.getImgurl()).into(new SimpleTarget<Bitmap>(){
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
FileOutputStream fileOutputStream = null;
File file = getDisc();
if(!file.exists()&& !file.mkdirs()){
Toast.makeText(getApplicationContext(),"Can't create directory to save image", Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat simpleDataFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDataFormat.format(new Date());
String name = "img"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file= new File(file_name);
try {
fileOutputStream=new FileOutputStream(new_file);
resource.getHeight();
resource.getWidth();
resource.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
Toast.makeText(getApplicationContext(),"SAVED", Toast.LENGTH_LONG).show();
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
refreshGallery(new_file);
}
public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}
private File getDisc(){
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(file, "FolderNamerYourChoice");
}
});
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}

Using Bitmap for saving image to Gallery in Android application with camera app

I have problems when i use some code from Capture Image from Camera and Display in Activity and https://developer.android.com/training/camera/photobasics.html
First, this is in MainActivity.java. I create onClickevent when user press button "snap"
Button snap = (Button) findViewById(R.id.button3);
snap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent start_cam = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File path = null;
try {
path = createImageFile();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
if(path!=null) {
start_cam.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(path));
startActivityForResult(start_cam, 1);
}
}
});
Next, i add createImageFile() method
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
root_file = "file:" + image.getAbsolutePath();
return image;
}
Last part, I add onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
try {
m = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(root_file));
try {
view.setImageBitmap(m);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I also add heading in my AndroidManifest.xml
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
After, i use this feature in android emulator API19 Nexus_one API19 (take a photo). The dialog appears and said "java.lang.nullPointerException".
I don't know why this problem appears. I think it may be my emulator or code.

Categories