Unable to attach audio file to Samsung Devices - android

I unable to attach Audio file to Some of the Samsung Devices like Samsung GalaxyS2,Nexus etc.I don't know whats the problem.I am able to attach all other devices.Please someone help me for my this issue.My code is as:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body",
getResources().getText(R.string.Message));
sendIntent.setClassName("com.android.mms",
"com.android.mms.ui.ComposeMessageActivity");
AssetManager mngr = getAssets();
InputStream path = null;
try {
path = mngr.open("*.mp3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(path, 1024);
// get the bytes one by one
int current = 0;
//
try {
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
} catch (IOException e) {
// /TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bitmapdata = baf.toByteArray();
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "*.mp3");
// if (file.exists() == true) {
// } else {
// Log.v("directory is created", "new dir");
// file.mkdir();
// }
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
final File file1 = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
"*.mp3");
Uri uri = Uri.fromFile(file1);
Log.e("Path", "" + uri);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("audio/mp3");
// sendIntent.putExtra(Intent.EXTRA_STREAM, mms_uri.toString());
startActivity(Intent.createChooser(sendIntent, ""));
// startActivity(sendIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}

Don't set the class name explicitly by calling setClassName(). Instead just set the action, type and extra as described here.

You are assuming that there is ExternalStorage i.e. sd card available on the device. Your S2 or Nexus probably does not have the sd card. I have seen this issue before.

Related

Image not showing when passed as an intent extra

I'm trying to pass the screenshot of screen with an explicit intent but the screen shows black screenshot(refer image here). As soon as i click share, a toast appears saying sending failed. Here's the code to capture screenshot and send it to other app:
public void getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
f = new File(this.getFilesDir(), "screenshotFile");
try {
if (!f.exists())
f.createNewFile();
} catch (IOexception e) {
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This code sends the data to whatsapp:
public void shareWhatsapp(View view) {
try {
myVib.vibrate(50);
getScreenShot(view);
//String fileName = "screenshotFile";
//Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
try {
intent.setPackage("com.whatsapp");
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "App not installed", Toast.LENGTH_SHORT).show();
}
//TODO: APP CAN CRASH HERE
if (position > 0) {
try {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f);
} catch (Exception e) {
e.printStackTrace();
} finally {
intent.putExtra(Intent.EXTRA_TEXT, Titles.get(position - 1) + ": " + Links.get(position - 1)); //position problems
}
} else {
try {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f);
} catch (Exception e) {
e.printStackTrace();
} finally {
intent.putExtra(Intent.EXTRA_TEXT, Titles.get(0) + ": " + Links.get(0)); //position problems
}
}
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Can someone help me with this?
First, you are writing the file to internal storage. Third-party apps do not have access to your app's internal storage.
Second, you are using Uri.fromFile(), which is starting to be discontinued.
Your safest long-term course of action is to have a ContentProvider serve your file from its location on internal storage, then use a Uri associated with that ContentProvider.

Directory not exists in Android

I want to write string of data in a file in android . That is why I have the following code :
public String DumpFile(String fileName,String data)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_data");
myDir.mkdirs();
if(myDir.exists())
Toast.makeText(this, "Directory exists" ,Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "directory not exists " ,Toast.LENGTH_LONG).show();
// Random generator = new Random();
String fname = fileName;
// showToastOnUiThread("File Name: "+fname+" and Data: "+data,
// Toast.LENGTH_LONG);
File file = new File(myDir, fname);
Toast.makeText(this, "Link is "+file.getAbsolutePath(),Toast.LENGTH_LONG).show();
// Toast.makeText(this, "Content is "+data,Toast.LENGTH_LONG).show();
OutputStream bos = null;
FileOutputStream out = null;
if (file.exists())
file.delete();
try {
out = new FileOutputStream(file);
bos = new BufferedOutputStream(out);
bos.write(data.getBytes());
bos.flush();
// out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return fname;
}
But when I have run the code , I have got the Toast that directory not exists . Where is the error ? Can you help me ?
Add the permission to your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Write file to sdcard in android

I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}
Here's an example from my code:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And don't forget the:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try like this,
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}
It's pretty easy to create folder and write file on sd card in android
Code snippet
String ext_storage_state = Environment.getExternalStorageState();
File mediaStorage = new File(Environment.getExternalStorageDirectory()
+ "/Folder name");
if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
if (!mediaStorage.exists()) {
mediaStorage.mkdirs();
}
//write file writing code..
try {
FileOutputStream fos=new FileOutputStream(file name);
try {
fos.write(filename.toByteArray());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//Toast message sd card not found..
}
Note: 'getExternalStorageDirectory()'
actually gives you a path to /storage/emulated/0 and not the actual sdcard
'String path = Syst.envr("SECONDARY_STORAGE");' gives you a path to the sd card

Android: action_send put extra_stream from res/drawable folder causes crash

I am creating a game, and trying to allow the user to share their win via text/facebook/etc. I am using the code below to grab an image from my res/drawable folder. I am pretty sure I am doing it right, but my app keeps crashing after I choose the send method (ex. facebook). Any help would be greatly appreciated.
Intent ShareIntent = new Intent(android.content.Intent.ACTION_SEND);
ShareIntent.setType("image/jpeg");
Uri winnerPic = Uri.parse("android.resource://com.poop.pals/" + R.drawable.winnerpic);
ShareIntent.putExtra(Intent.EXTRA_STREAM, winnerPic);
startActivity(ShareIntent);
Android's resources are only accessible to your app via the resource apis, there is no regular file on the filesystem you can open in other ways.
What you can do is to copy the file from the InputStream you can get to a regular file in a place that is accessible to other apps.
// copy R.drawable.winnerpic to /sdcard/winnerpic.png
File file = new File (Environment.getExternalStorageDirectory(), "winnerpic.png");
FileOutputStream output = null;
InputStream input = null;
try {
output = new FileOutputStream(file);
input = context.getResources().openRawResource(R.drawable.winnerpic);
byte[] buffer = new byte[1024];
int copied;
while ((copied = input.read(buffer)) != -1) {
output.write(buffer, 0, copied);
}
} catch (FileNotFoundException e) {
Log.e("OMG", "can't copy", e);
} catch (IOException e) {
Log.e("OMG", "can't copy", e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
// ignore
}
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
// ignore
}
}
}

Android Read-Only File System Error

Hi I have a gallery in my app which shows the image in an image view when you click on the thumbnail. I am setting up a Long Click Listener for an alert dialog that has 2 buttons one to set as wallpaper and one to share. I have the share intent and the get drawing cache somewhat working. It works in the emulator but not on my phone. I have used many of the examples on this site to get this going but its not working at all. it keeps force closing the app on my phone. any help is appreciated.
alertDialog.setButton2("Share",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
imgView.setDrawingCacheEnabled(true);
Bitmap b = imgView.getDrawingCache();
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + "image.jpg");
try {
file.createNewFile();
OutputStream fos = null;
fos = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Save Example", "Image saved.");
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri phototUri = Uri.parse("file:///sdcard/image.jpg");
shareIntent.setData(phototUri);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
startActivity(Intent.createChooser(shareIntent, "Share Via"));
}
});
alertDialog.show();
return true;
}
});
Update: it seems to be a problem with
b.compress(CompressFormat.JPEG, 95, fos);
it keeps saying null pointer.
Turns out the null pointer is actually a read_only error..So its not actually writing the file i get a ioexception read-only file system. Why is it doing this?
ok here s what i ended up doing to get this to share the pictures in case others need it. It turns out my ImageView was not being rendered as a BitMap so it was make files with nothing in them. So instead i am just calling the drawable from its postion and saving that. Its a lot cleaner code for this simple gallery. I have it in an alert dialog but it can be set to a regular button also.
alertDialog.setButton2("Share",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
long currentTime = System.currentTimeMillis();
imgView.setDrawingCacheEnabled(true);
String newFolder = "/CFW";
String extStorageDirectory = Environment
.getExternalStorageDirectory()
.toString();
File sdCard = new File(extStorageDirectory
+ newFolder);
sdCard.mkdir();
File file = new File(sdCard.getAbsolutePath()
+ "/cfw" + currentTime + ".jpg");
try {
InputStream is = getResources()
.openRawResource(pics[position]);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Save Example", "Image saved.");
Intent shareIntent = new Intent(
Intent.ACTION_SEND);
Uri photoUri = Uri
.parse("file:///sdcard/CFW/cfw"
+ currentTime + ".jpg");
shareIntent.setData(photoUri);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM,
photoUri);
startActivity(Intent.createChooser(shareIntent,
"Share Via"));
}
});
alertDialog.show();
return true;
}
});
}

Categories

Resources