Good morning. I've been looking for a solution to my problem for a long time and I can't find it. I have reviewed and tried the similar solutions shown on Stackoverflow and they do not work with my application. What I am trying to do is import the data from a csv file that I have previously selected. Thanks in advance.
1.I have given permission on AndroidManifest to write and read.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.serviciosus">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
By selecting the ImportarServices menu item, I select the file to import. So far so good.
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.addMembers) { openDialogMember(); } else if (item.getItemId() == R.id.addservices ) { Intent intent = new Intent(context, MainActivityServices.class); startActivity(intent); } else if (item.getItemId() == R.id.importServices) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, CHOOSE_FILE); } else { Intent getFile = new Intent(Intent.ACTION_GET_CONTENT); getFile.addCategory(Intent.CATEGORY_OPENABLE); getFile.setType("*/*"); startActivityForResult(Intent.createChooser(getFile, "Services.csv"), CHOOSE_FILE); } {
I capture the Uri of the file and through onActivityResult, sending it to the method of reading and saving data importCSV().
protected void onActivityResult(int requestCode, int resultCode, @Nullable final Intent data) { super.onActivityResult(requestCode, resultCode, data); Uri route = data.getData(); if (route != null) { try { importCSV(route); } catch (IOException e) { e.printStackTrace(); } } }
Method to save the data in the database.
public void importCSV(Uri uri) throws IOException { File file = null; file = new File(uri.getPath()); try { CSVReader reader = new CSVReader(new FileReader(file)); groupDate=null; while (( groupDate = reader.readNext()) != null){ String type=groupDate[0]; String date=groupDate[1]; String observations=groupDate[2]; int idPersons=Integer.valueOf(array[3]); // basedate insert method servicios.insertServices(type,date,observations,idPersons); } }catch (IOException e){ Toast.makeText(this, "File does not exist", Toast.LENGTH_SHORT).show(); } }
This is where I have the problem or so I think. I used a Toast to see what file it shows me and it shows it fine, but then it throws me the "File does not exist" exception. And that's what I can't fix. I would appreciate your help.