Share raw resource via WhatsApp "Failed to send, please try again" - java

i want to share an audio when a button is hold, i save the mp3 to the external storage and then share it but i have an error "failed to send, please try again" (something like that, the original is in spanish). what can i do?
the code:
b0.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
File dest = Environment.getExternalStorageDirectory();
InputStream in = getApplicationContext().getResources().openRawResource(R.raw.teagachas);
try
{
OutputStream out = new FileOutputStream(new File(dest, "lastshared.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch (Exception e) {}
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/lastshared.mp3"));
share.setType("audio/*");
getApplicationContext().startActivity(Intent.createChooser(share, "compartiendo \"" + b0.getText() + "\""));
return true;
}
});
PD: the code is in the onCreate method

Related

Unable to Unzip file when downloaded from URL, but works when downloaded from FTP

I am trying to download an e-book from URL and unzip it, which further goes for display. While the same unzip logic works perfectly for a FTP download, when it comes to URL, unzipping method does nothing after download.
My book download calling method :
DownloadBook db = new DownloadBook(localFile,"some url",book.key,context,(TaskListener) result -> {
if (result) {
runOnUiThread(() -> pBar.setVisibility(View.VISIBLE));
Runnable t = (Runnable) () -> {
unzip(localFile.getPath(), b.key.replace(".zip",""), b);
isDownloaded = true;
//Deleting downlaoded zip file
System.out.println("zip file deleted - "+localFile.delete());
String urls = localFile.getPath() + "/" + ((b.key).replace(".zip", ""));
System.out.println("URL IS " + urls);
System.out.println("Going for Display");
GlobalVars.title = b.title;
Intent intent = new Intent(My_Library.this, DisplayActivity.class);
startActivity(intent);//
};
t.run();
} else {
runOnUiThread(() ->
{
alert = new AlertDialog.Builder(this);
alert.setTitle("Error");
alert.setMessage("Could not download. Please try again !")
.setCancelable(true)
.setNegativeButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(My_Library.this, My_Library.class);
startActivity(intent);
dialog.cancel();
}
});
alert.create();
alert.show();
}
);
}
});
The zip file download method :
t = new Thread(new Runnable() {
#Override
public void run() {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("some url");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(localFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
System.out.println("Total is "+total);
if(fileLength>0)
{
System.out.println("File length is "+fileLength+" local file length is "+localFile.length());
percent = (int) (total * 100 / fileLength);
System.out.println("FTP_DOWNLOAD bytesTransferred /downloaded -> " + percent);
mProgress.setProgress(percent);
}
output.write(count);
output.flush();
}
mListener.finished(true);
} catch (Exception e) {
e.printStackTrace();
mListener.finished(false);
} finally {
try {
output.flush();
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
The unzip method
public void unzip(String _zipFile, String _targetLocation, Book b) {
pBar.setVisibility(View.VISIBLE);
GlobalVars.path = _targetLocation;
_targetLocation = getApplicationContext().getFilesDir().getPath();
dirChecker(_targetLocation);
try {
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(_zipFile));
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("Unzipping file -> " + ze.getName());
//create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
} else {
File f = new File(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
dirChecker(f.getParent());
long size = f.length();
BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(new File(String.valueOf(f.getAbsoluteFile()))));
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
fout.write(buffer, 0, read);
}
zin.closeEntry();
fout.close();
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
The FTP download class method Unzip works absolutely fine. But as I try to put download from url, it just downloads but not unzips.
You have to change the output buffer writing method.
So instead of, in zip download method
output.write(count);
Use,
output.write(data,0,count);

saving file in internal storage android for my app

I have audio mp3 in res/raw/suono1.mp3 and i need share(in my app) on whatapp my code is it, but when i send, don t share HELP ME PLS.
pulsante2.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//condividere
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.suono2);
fileOutputStream = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/mpeg");
startActivity(Intent.createChooser(intent, "Share audio"));
return false;
}
});
send code for android studio i need them
Have you asked permission in the manifest.xml file?

Saving File in internal memory and reading through intent

I want to download a file from URL and save it to the internal memory. Once file is saved in internal memory I want to fire an Intent to open it in apps.
**Following is the code to download the file and save in internal memory:**
private void getPDFContent(String myUrl, String sfilename) {
try {
FileOutputStream fos = this.openFileOutput(sfilename,Context.MODE_PRIVATE);
URL u = new URL(myUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
**Following is the code to read:**
public void readInternalStorageOption() {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
String filePath = getApplication().getFilesDir().getAbsolutePath()
+ File.separator + "test.pdf";
File f = new File(filePath);
if (f.exists()) {
Uri internal = Uri.fromFile(f);
intent.setDataAndType(internal, "application/pdf");
}
startActivity(intent);
} catch (NullPointerException ex) {
}
}
Issue is that file is saved successfully but when I try to open it via intent I got an error that file cannot be opened. Please suggest any solution for the same.

client.getInputStream returns null

I am trying to use the WifiDirect demo api to send a recorded audio to another android device but input stream from the socket always returns null.
Any help is much appreciated.
Here are portion of the code
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory(), File.separator + "SuDAB/received/"
+ "sudab-" + System.currentTimeMillis()
+ ".3gp");
File dirs = new File(f.getParent());
if (!dirs.exists()) {
dirs.mkdirs();
}
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
and
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime = System.currentTimeMillis();
if (inputStream == null) {
return false;
}
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime = System.currentTimeMillis() - startTime;
Log.v(WiFiDirectActivity.TAG, "Time taken to transfer all bytes is : " + endTime);
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
this is how i pass the file to be sent to the FileTransferService
mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Allow user to pick an image from Gallery or other
// registered apps
TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
statusText.setText("Sending: " + lastFile);
Log.d(WiFiDirectActivity.TAG, "Intent----------- " + lastFile);
Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
Log.d(WiFiDirectActivity.TAG, "File transfer service created...");
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, lastFile);
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
getActivity().startService(serviceIntent);
}
});
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, lastFile);
should be
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, "file://"+lastFile);
instead.

Android: Sharing an image from raw folder. Wrong image being shared

I have an Activity where the user can share an image from the raw folder.
The raw folder has 70 images, all named alphabetically. The first one is R.raw.recipe01 and the last is R.raw.recipe70.
I get the image int I would like to share from a Bundle and I have a method which copies the image from the raw folder to a accessible file.
I call startActivity(createShareIntent()); in the ActionBar MenuItem, which works successfully.
PROBLEM
The share intent will always select R.raw.recipe01 as the image, even if the int from the Bundle is for image for exmaple R.raw.recipe33.
I have shared my code below. Can anyone spot what I am doing wrong?
CODE:
private int rawphoto = 0;
private static final String SHARED_FILE_NAME = "shared.png";
#Override
public void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
rawphoto = bundle.getInt("rawphoto");
int savedphoto = rawphoto;
// COPY IMAGE FROM RAW
copyPrivateRawResourceToPubliclyAccessibleFile(savedphoto);
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "IMAGE TO SHARE: ");
Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
return shareIntent;
}
private void copyPrivateRawResourceToPubliclyAccessibleFile(int photo) {
System.out.println("INT PHOTO: " +photo);
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(photo);
outputStream = openFileOutput(SHARED_FILE_NAME,
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
}
finally {
try {
inputStream.close();
} catch (IOException ioe) {
}
try {
outputStream.close();
} catch (IOException ioe) {
}
}
}
Remove Context.MODE_APPEND so that the file gets overwritten if it already exists.

Categories

Resources