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
}
}
}
Related
I am using following method to encrypt and decrypt the files. File is getting decrypted properly but I am unable to view Image or video in application. File is opening in gallery and I can view image and watch video clearly. The same I am unable to do in application using Imageview and Videoview
Below is my code :
public void run() {
boolean successful = true;
operationInProgress = true;
lastUpdateAtByteNumber = 0;
totalBytesRead = 0;
timeOperationStarted = System.currentTimeMillis();
if (operationType == OPERATION_TYPE_ENCRYPTION) {
completedMessageStringId = R.string.encryption_completed;
} else {
completedMessageStringId = R.string.decryption_completed;
}
InputStream inputStream = null;
OutputStream outputStream = null;
//get the input stream
try {
inputStream = new FileInputStream(inputFileName);
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
//get the output stream
try {
outputStream = new FileOutputStream(outputFileName);
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
if (inputStream != null && outputStream != null) {
//call AESCrypt
try {
fileSize = inputStream.available();
AESCrypt aesCrypt = new AESCrypt(password);
if (operationType == OPERATION_TYPE_ENCRYPTION) {
//Encrypt
aesCrypt.encrypt(version, inputStream, outputStream);
} else {
//Decrypt
aesCrypt.decrypt(fileSize, inputStream, outputStream);
}
} catch (GeneralSecurityException gse) {
successful = false;
gse.printStackTrace();
} catch (UnsupportedEncodingException uee) {
successful = false;
uee.printStackTrace();
} catch (IOException ioe) {
successful = false;
} catch (NullPointerException npe) {
successful = false;
}
}
//close the streams
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException ioe) {
successful = false;
}
}
operationInProgress = false;
}
The reference code is https://www.aescrypt.com/download/
AndroidCrypt (AES Crypt compatible) for Android phones (source code)
File getting encrypted and decrypted properly. When I am trying to open the load the file using Imageview for image and videoview for video.
I am using below code to view image
File url1 = new File(path to my file);
Bitmap bmp = BitmapFactory.decodeFile(url1.getAbsolutePath());
objImageView.setImageBitmap(bmp);
It gives error **"libjpeg error 105 < Ss=0, Se=63, Ah=0, Al=0> from Incomplete image data"** . or **Failed to create image decoder with message 'unimplemented'**
For Video I am using below code
getPackageName is name of package
FileProvider I have declared in manifest and also in xml I have menioned fielpath
File url1 = new File(path to video file)
videoView.setVideoURI(FileProvider.getUriForFile(
this, getPackageName(),url1));
The same image and video is clearly visible in Gallery application.
Please help me.
Thanks
I have saved some text files in asset folder of android apk , whenever user opens the app which is having list of filenames ,if he clicks on a filename corresponding file opens from asset folder ,
Now I want to let user save that file in text or pdf format to his local directory so that he can transfer it or use it or modify it according to his choice
EDIT : I just want to know the api needed ,not the whole code
Use this function to copy something from assets to storage
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
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);
}
}
Reference : Move file using Java
I have noticed in the android device monitor when I try to access the data folder so I can pull the sql file of my application that is running on my physical phone it does not work but when accessing the application through an emulator it does work. Obviously running the application on the emulator is much more time consuming and I need to present this sqlite data in a timed viva so I can't really be waiting for an emulator.
I was wondering why this is happening as I have allowed debugging and while it does not ask for any more checks on security the device monitor will not open the data folder, when clicked the arrowhead next to the folder disappears then reappears after a few seconds but I can still access every other folder with a drop-down arrow next to it.
If your device is not rooted, you cannot access your app's data file. Try to use following code snippet in any of your Activity to copy the file to sdcard.
public static void copyDataFile() {
File dataDir = getFilesDir().getParentFile();
File target = new File(dataDir, "/* relative path to your sql file */");
File out = new File(Environment.getExternalStorageDirectory(), "/* new file name */");
copyFile(target, out);
}
public static void copyFile(File in, File out) {
if (in.exists()) {
if (!out.exists()) {
try {
out.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream(in);
os = new FileOutputStream(out);
byte[] buf = new byte[4096];
int l = 0;
while ((l = is.read(buf)) > 0) {
os.write(buf, 0, l);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I am trying firstly to download the file and its content from Dropbox in Android app using Dropbox Core API but when i execute the following code the app crushes.
EDIT: I have used two functions downloadDropboxFile and copy functions. The problem is that i am getting blank data when i read the local file which is supposed to contain the dropbox file data.
Here is the code where i call the function
downloadDropboxFile("/userandpass.txt");
if (mDBApi.getSession().isLinked())
{
InputStream instream = new FileInputStream(String.valueOf(getExternalCacheDir()) + "/userandpass.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
mTestOutput.setText(buffreader.readLine());
}
Here is the functions
private boolean downloadDropboxFile(String fileSelected) {
File dir = new File(String.valueOf(getExternalCacheDir()));
if (!dir.exists())
dir.mkdirs();
try {
File localFile = new File(dir + fileSelected);
if (!localFile.exists()) {
localFile.createNewFile();
copy(fileSelected, localFile);
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private void copy(final String dbPath, final File localFile) {
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
DropboxAPI.DropboxInputStream fd = mDBApi.getFileStream(dbPath,null);
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}). start();
}
Dropbox Core API Implementation on Android Studio:
On app/libs i have the:
dropbox-android-sdk-1.6.3.jar
httpmime--4.0.3.jar
json_simple-1.1.jar
Your issue is here :
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
The exception is :
java.io.IOException: open failed: EROFS (Read-only file system)
This means you're trying to create a File on a location that is read only in the phone's memory, I'm guessing the internal storage. Have a look at this excellent answer by Mark Murphy on creating a File based on locations that can be written to.
Hoping this has been of some help, happy coding ;-)
In my Android app I should store the data from user in simple text-file, that I created in the raw directory. After this, I'm trying to write file in APPEND MODE by using simple code from the Google's examples:
try
{
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);
fos.write((nameArticle+"|"+indexArticle).getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
But nothing happens: no exceptions, but I can see nothing in my FILE_NAME, besides the single record, which was added by me.
What am I doing wrong ? Is it possible at common to write to file in emulator ?
openFileOutput will only allow you to open a private file associated with this Context's application package for writing. I'm not sure where the file you're trying to write to is located. I mean full path. You can use the code below to write to a file located anywhere (as long as you have perms). The example is using the external storage, but you should be able to modify it to write anywhere:
public Uri writeToExternalStoragePublic() {
final String filename = mToolbar.GetTitle() + ".html";
final String packageName = this.getPackageName();
final String folderpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files/";
File folder = new File(folderpath);
File file = null;
FileOutputStream fOut = null;
try {
try {
if (folder != null) {
boolean exists = folder.exists();
if (!exists)
folder.mkdirs();
file = new File(folder.toString(), filename);
if (file != null) {
fOut = new FileOutputStream(file, false);
if (fOut != null) {
fOut.write(mCurrentReportHtml.getBytes());
}
}
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return Uri.fromFile(file);
} finally {
if (fOut != null) {
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
In the example you have given, try catching 'I0Exception`, I have a feeling you do not have permission where you are trying to write.
Have a Happy New Year.