Can I share a .csv file by whatsapp or email? - java

I have a problem. When I try share a .csv file generated by my application by whatsapp this app opens and closes immediately no consigo and I can't share the file.
The way to generate the file is as follows:
private void guardarFichero() {
//Date date=new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("ddMMhhmmss");
// Nombre del fichero
fileName="Inventario_"+ dateFormat.format(new Date())+".csv";
// obtenemos los datos a guardar
String inventario=textoEyoyo.getText().toString();
File file =new File (getExternalFilesDir(null),fileName);
try {
OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(file));
osw.write(inventario);
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
method share:
private void compartir(){
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Log.i("Mensaje", "nombre de la path: "+ path);
try {
File file =new File(getExternalFilesDir(null), fileName);
Uri uri = Uri.fromFile(file);
Log.i("Mensaje", "nombre de la URL: " + uri);
Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.setType("*/*");
share.putExtra(Intent.EXTRA_STREAM,uri);
//share.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivity(share);
} catch (Exception e) {
e.printStackTrace();
}
}

Related

how do i append text inside a file using FileWriter

I'm trying to keep adding text into my file (internal storage)
it was tried using FileOutputStream and it was fine but after i changed to use FileWriter then i started having the read-only file-system error
EditText edd = findViewById(R.id.editTextData);
Spinner spp = findViewById(R.id.spinnerCategory);
String text1 = edd.getText().toString();
String text2 = spp.getSelectedItem().toString();
String filepath = text2 + ".txt";
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filepath, true));
bw.write(text1);
bw.newLine();
bw.close();
Toast.makeText(getBaseContext(), "Information Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
} //End try catch statement
}```
It's supposed to say Information Saved but i keep getting read-only file system
EditText edd = findViewById(R.id.editTextData);
Spinner spp = findViewById(R.id.spinnerCategory);
String text1 = edd.getText().toString();
String text2 = spp.getSelectedItem().toString();
String filename = text2 + ".dat";
try {
File fa = new File(getFilesDir(),filename); //getting the filename path
FileWriter fw = new FileWriter(fa,true);
fw.write(text1 + "\n");
fw.close();
Toast.makeText(getBaseContext(), "Information Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
} //End try catch statement

Opening a file present in assets folder using an intent

Hello I am tring to open a .pdf file present in a file using an intent but it is giving me 2 errors on the following line
File file = new File(getContext().getAssets().open("assets/test.pdf"));
Errors
1.Unhandled java.IO.Exception.
2.getAssets()may produce java.lang.NullPointerException
Here us the code in a fragment
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
File file = new File(getContext().getAssets().open("assets/test.pdf"));
if (file .exists())
{
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent ); }
catch (ActivityNotFoundException e)
{
Toast.makeText(getActivity(), "Please install a pdf file viewer",
Toast.LENGTH_LONG).show();
}
}
}
}
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abc.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card
try with the file provider
Intent intent = new Intent(Intent.ACTION_VIEW);
// set flag to give temporary permission to external app to use your FileProvider
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
String uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
// I am opening a PDF file so I give it a valid MIME type
intent.setDataAndType(uri, "application/pdf");
// validate that the device can open your File!
PackageManager pm = getActivity().getPackageManager();
if (intent.resolveActivity(pm) != null) {
startActivity(intent);
}
To serve a file from assets to another app you need to use a provider.
Google for the StreamProvider of CommonsWare.

Create views dynamically depending on data

I have a name, time and experience. I save them in one screen and want to load them on another. I think, creating a view for each would be a good solution. But i'm open to other suggestions. This is the code that I use to save the data.
//Sacando el texto de los editText y guardandolos en sus variables
d_TaskName = etxt_TaskName.getText().toString();
d_TaskTime = etxt_TaskTime.getText().toString();
d_TaskExp = etxt_TaskExp.getText().toString();
// Guardar nombre de la tarea en TaskName.txt
try {
FileOutputStream fou1 = openFileOutput("TaskName.txt", MODE_WORLD_WRITEABLE);
OutputStreamWriter osw1 = new OutputStreamWriter(fou1);
try {
osw1.write(d_TaskName);
osw1.flush();
osw1.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Guardar tiempo que dura la tarea en TaskTime.txt
try {
FileOutputStream fou2 = openFileOutput("TaskTime.txt", MODE_WORLD_WRITEABLE);
OutputStreamWriter osw2 = new OutputStreamWriter(fou2);
try {
osw2.write(d_TaskTime);
osw2.flush();
osw2.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Guardar la experiencia de la tarea en TaskExp.txt
try {
FileOutputStream fou3 = openFileOutput("TaskExp.txt", MODE_WORLD_WRITEABLE);
OutputStreamWriter osw3 = new OutputStreamWriter(fou3);
try {
osw3.write(d_TaskExp);
osw3.flush();
osw3.close();
Toast.makeText(getBaseContext(), "Tarea Guardada", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Why don't you use SharedPreferences?
For store your data:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("TaskName", etxt_TaskName.getText().toString());
editor.apply();
For load your data:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String taskName = sharedPref.getString("TaskName", "");

Android Activity Restarts When Turning Back To App From Adobe Reader

My app downloads a PDF file from webserver and opens it with Adobe Reader. But when I click back button on Adobe Reader, my app restarts. I don't want my app to restart when closing Adobe Reader. Note: My app has a file browser dialog, I choose a PDF and display it.
How can I prevent restarting the acitivity when turn back from Adobe Reader?
My code ...
private class DownloadFile extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/dokuman.pdf
String fileName = strings[1]; // -> dokuman.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "dokuman");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
Downloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
...
public class Downloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
...
new DownloadFile().execute(host+"dene.pdf", "dokuman.pdf");
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/dokuman/" + "dokuman.pdf"); // -> filename = dokuman.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No PDF Viewer App!", Toast.LENGTH_SHORT).show();
...

"Invalid File" error when the images in sdcard are clicked

To share the image via Email and mms first step I need to save the image in sdcard but for me the saved image is not getting opened instead "Invalid File" error, I checked with the extension format everything is correct but don't know where I'm going wrong.
Below is the java code.
public class Share extends CordovaPlugin {
public static final String ACTION_POSITION = "ShareImage";
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (ACTION_POSITION.equals(action)) {
try {
JSONObject arg_object = args.getJSONObject(0);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("image/jpg");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, arg_object.getString("image"));
String name = arg_object.getString("image");
String defType = "drawable";
String defPackage = "com.picsswipe";
int drawableId = this.cordova.getActivity().getResources().getIdentifier( name , defType, defPackage );
// Bitmap bbicon = BitmapFactory.decodeFile( arg_object.getString("image") );
Bitmap bbicon = BitmapFactory.decodeResource( this.cordova.getActivity().getResources(),drawableId );
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File f = new File(extStorageDirectory + "/Download/",
"jj.jpg" );
try {
outStream = new FileOutputStream(f);
bbicon.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
}
File r1 = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Download/", "jj.jpg");
//RETRIEVING IMAGES FROM SDCARD
Uri uri1 = Uri.fromFile(r1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri1);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(r1));
Uri uris = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "jj.jpg"));
this.cordova.getActivity().startActivity(sendIntent);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
return true;
}
}
File file;
File rootPath = android.os.Environment
.getExternalStorageDirectory();
File directory = new File(rootPath.getAbsolutePath()
+ "/Download");
if (!directory.exists())
directory.mkdir();
file = new File(directory, "filename.PNG");//.png/.jpg anything you want
try {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pincheck);
FileOutputStream outStream;
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and you should add this permission in your manifest file..Then only file will copied to your external sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Categories