I am trying to create a folder inside Internal Storage on Button click, but I can't figure out why it's not working.
backUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
File sub = new File(MainActivity.this.getFilesDir(), "new_folder");
if (!sub.exists()){
sub.mkdirs();
Toast.makeText(getApplicationContext(), "Sucess!!",
Toast.LENGTH_LONG).show();
}
}
});
Looks alright, displays the sucess toast but can't see the folder in directory. Even tried refreshing the Directory with:
MediaScannerConnection.scanFile(MainActivity.this, new String[] {sub.toString()}, null, null);
Also provided WRITE_INTERNAL_STORAGE permission in Menifest.
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
You will need permissions, in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
on Button click Context.MODE_PRIVATE is use
File mydir = context.getDir("users", Context.MODE_PRIVATE); //Creating an internal dir;
if (!mydir.exists())
{
mydir.mkdirs();
}
Related
I'm trying to make a service that will run every 10 seconds to check a queue and if there is some data in the queue upload the given uri (uri of a picture just taken from the app) to a certain url.
I have created something along these lines
public QueueProcessor(final Context context){
this.mContext = context.getApplicationContext();
}
/**
* Starts processing the items on a separate thread.
*/
public void process() {
Runnable running = new Runnable() {
#Override
public void run() {
try{
Log.i(RUN_QP_TAG, "Processing queue");
// more here
isRunning = true;
Queue theQ = Queue.getInstance();
if(theQ.getSize() > 0){
WorkQItem itm = theQ.pop();
if(itm.hasImage()){
pushImageUploadToProcess(itm);
}
}
} catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed(this, 10000);
}
}
};
new Thread(running).start();
}
The pushImageUploadToProcess takes the WorkQItem and tries to upload the image from the item (which is saved as String picUri) by opening the uri and writing the bytes. However I get a permissions denied exception when trying to open the picUri location.
MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image%3A531 from pid=795, uid=10327 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
How can I allow this Thread/Runnable to have access to the URI?
Note I have tried the upload directly from a button event and it does work.
I have the following permissions in the manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
You should implement runtime permission, for that use below code
PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
#Override
public void onGranted() {
// Proceed with initialization
}
#Override
public void onDenied(String permission) {
// Notify the user that you need all of the permissions
}
});
add below dependency in your app gradle
compile 'com.anthonycr.grant:permissions:1.0'
It looks like the actual permission error is not the real issue. The real issue was the way I was choosing and picking the image.
I ended up using https://gist.github.com/Mariovc/f06e70ebe8ca52fbbbe2 this picker and it seemed to work without any issues.
I tweaked this code a little bit to suit my needs as any image picked from the camera needed to be saved too so that if there are several images being done and each is needed for later use the relative uri initially will get overwritten therefore you need a fixed one (e.g: to be saved).
Ok, so have 2 Activities in my app, that will do some stuff.
In the mainActivity before I start the second Intent, I want to create the necessary folders for my app to work correctly.
So, my code so far looks like this:
In the main activity I use this code to create my folder on the SD card, before starting the new intent :
// on click of a button
createWholePath(spinner1.getSelectedItem().toString(),"test");
// and the function
public static boolean createWholePath(String mainfolder, String subfolder){
boolean ret= true;
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory()+"/"+mainfolder+"/"+subfolder);
wallpaperDirectory.mkdirs();
return ret;
}
In AndroidManifest I added the permission like:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Now I expect to see a folder created (on the device's SD card) after I click the button
But it does not happen...
What could be wrong?
Why doesn't the folder appear?
I use for debugging a real device *(Samsung Galaxy Note 2)
Thank you
UPDATE
So my problem was part of a bigger project and something went wrong somewhere else apparently. I decided to make a new empty project just to test my code and yes, it works fine outside my original project. I will investigate further. I will award the answer to the guy that tested my code and said that it works
Thank you all.
Are you sure it isn't working? Your code is working for me (after I replaced the spinner value with a constant string). Perhaps the directory is being created, just not where you're expecting it. You can see where the directory will be created using a line like:
Log.v(TAG, "wallpaperDirectory=" + wallpaperDirectory.getAbsolutePath());
try this it could be your method is not called on spinner item selection
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
try{
Object item = parent.getItemAtPosition(pos);
createWholePath(item.toString(),"test");
}catch(Exception e){}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory(),mainfolder+"/"+subfolder);
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
and put these permission to manifiest :-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am developing an android app.In one of the modules I am creating a directory in the external storage to store files using the below code.Things work fine and I am able to create the directory.
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnCreateDir = (Button) findViewById(R.id.createDir);
btnCreateDir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Toast.makeText(getApplicationContext(),"Can't create directory",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"directory created/exists",Toast.LENGTH_LONG).show();
}
} catch (Exception e4) {
e4.printStackTrace();
}
}
});
}
private File getDir() {
File sdDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "GaPopupFile");
}
}
However, when I make this app as a system app(by signing with the system certificates and storing in system/app folder) I see that this same code when executed,returns 'Can't create directory' . How is this possible,what am I missing here ?
Have you added this permission in AndroidManifest.xml file?
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Read permission needed to read file in Android applications.
Write permission needed to write file in Android applications.
So my app has an ActionDialog which contains a blank canvas as the interface with simple cancel and save buttons. What is happening is best demonstrated in a brief illustration
Screen layout before
-(TextView)-(ImageView)-(Button)-
Then when the user presses the button the ActionDialog pops up requesting they sign. Once they sign the captured drawing is saved. Then the drawing is accessed via memory and placed where the original ImageView is with a bitmap. However this is what ends up happening
Screen Layout after
----------nothing--------------
They just disappear and I get an error in my logcat:
05-14 19:06:27.004: E/Error(25274): java.io.FileNotFoundException: /storage/emulated/0signature.png: open failed: EACCES (Permission denied)
05-14 19:06:27.004: E/BitmapFactory(25274): Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0signature.png: open failed: ENOENT (No such file or directory)
java.io.FileNotFoundException: /storage/emulated/0signature.png: open failed: ENOENT (No such file or directory)
It does not crash my program though. Anyways here is the code for the files
action dialog
public class CaptureSignature extends DialogFragment {
Sign sign;
View view;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder capSig = new AlertDialog.Builder(getActivity());
capSig.setView(sign = new Sign(this.getActivity(), null))
.setMessage(R.string.store_question)
.setPositiveButton(R.string.save,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
sign.setDrawingCacheEnabled(true);
sign.getDrawingCache()
.compress(
Bitmap.CompressFormat.PNG,
10,
new FileOutputStream(
new File(
getActivity()
.getExternalFilesDir(
"img"),
"signature.png")));
} catch (Exception e) {
Log.e("Error ", e.toString());
}
File mysig = new File(getActivity()
.getExternalFilesDir("img"),
"signature.png");
ImageView sig = (ImageView) getActivity()
.findViewById(R.id.sig_image);
Bitmap bmp = BitmapFactory.decodeFile(mysig
.getAbsolutePath());
sig.setImageBitmap(bmp);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
// Create the Dialog object and return it
return capSig.create();
}
}
So obviously I've messed this up somewhere. If anyone has any insight I would be grateful. Thanks!
I personally think I am either saving this wrong or I'm not correctly declaring Sign, as in I call it but I don't give it a value, so the drawing cache is not actually being accessed.
Edit
I have declared this in the Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2nd Edit
showing new code and logcat, the error has changed
final edit
Thank you very much Matt Giles and JRowan, this was driving me insane. It works now and the above code is the final version.
The problem is the line:
new File(Environment.getExternalStorageDirectory().getPath() + "signature.png"
The call to getPath() returns a path that doesn't have a trailing '/'. Hence the file path in the error message, /storage/emulated/0signature.png instead of /storage/emulated/0/signature.png.
It would be better to use application-specific storage, instead of putting files in the sdcard root directory. Instead of the new File(...) call you have now, use:
new File(getActivity().getExternalFilesDir("img"), "signature.png")
getExternalFilesDir(name) creates a folder called "name" that's dedicated to your application. This prevents your app from cluttering up the sdcard root directory.
I'm trying to simply delete an image from a simple app. I have it so that when you click on the image, it'll bring up an a dialog with the option to delete it. I thought this would just be something simple, but everything I have been trying doesn't seem to be doing anything. Below is my code. Any ideas would be greatly appreciated.
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = viewIt.getId();
File file = new File("file://" + arrPath[id]+".jpg");
file.delete();
}
});
Have you added permission in manifest file ?
Any app that declares the WRITE_EXTERNAL_STORAGE permission is implicitly granted READ_EXTERNAL_STORAGE permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Get the path of the file required and delete the file
File file= new File(android.os.Environment.getExternalStorageDirectory()+ "/myfolder/myimage.jpg");
if(file.exists())
{
file.delete();
}