I've created a .csv file in SD card. Now I want to open this file but unable to do this.
How to open a .csv file?
I've created a .csv file in SD card. Now I want to open this file but unable to do this.
How to open a .csv file?
First of all, you design your XML in Android Studio, then you paste this line of code and check your apps. If you have any errors, you will send an error line or any feedback.
csvText=findViewById(R.id.csvtext);
select=findViewById(R.id.button);
select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//imp step
if(SDK_INT >= Build.VERSION_CODES.R)
{
if(Environment.isExternalStorageManager()){
//choosing csv file
Intent intent=new Intent();
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE,true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select CSV File "),101);
}
else{
//getting permission from user
Intent intent=new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uri=Uri.fromParts("package",getPackageName(),null);
startActivity(intent);
}
}
else{
// for below android 11
Intent intent=new Intent();
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE,true);
intent.setAction(Intent.ACTION_GET_CONTENT);
ActivityCompat.requestPermissions(MainActivity.this,new String[] {WRITE_EXTERNAL_STORAGE},102);
}
}
});
}
Uri fileuri;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==101 && data!=null){
fileuri=data.getData();
csvText.setText(readCSVFile(getFilePathFromUri(fileuri)));
}
}
// this method is used for getting file path from uri
public String getFilePathFromUri(Uri uri){
String[] filename1;
String fn;
String filepath=uri.getPath();
String filePath1[]=filepath.split(":");
filename1 =filepath.split("/");
fn=filename1[filename1.length-1];
return Environment.getExternalStorageDirectory().getPath()+"/"+filePath1[1];
}
//reading file data
public String readCSVFile(String path){
String filedata = null;
File file=new File(path);
try {
Scanner scanner=new Scanner(file);
while (scanner.hasNextLine()){
String line=scanner.nextLine();
String [] splited=line.split(",");
String row="";
for (String s:splited){
row=row+s+" ";
}
filedata=filedata+row+"\n";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_SHORT).show();
}
return filedata;
}