Android new folder issues - android

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" />

Related

Android: Load text file located in app/src/main/

I'm attempting to use some code to load a basic changelog from a text file into an alert dialog. The only issue is that I am having trouble getting my code to find the location of my changelog file. The file "changelog" is located in app/src/main/. Here is a sample of my code.
private void displayChangelogDialog() {
Context context = this;
try {
new AlertDialog.Builder(this)
.setTitle("Changelog")
.setMessage(readFile(getApplicationContext().getFilesDir().getAbsolutePath() + "/app/src/main/changelog"))
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
I am not very familiar with getFilesDir() or getAbsolutePath(), so I'd imagine this would be a good learning experience if anyone can help me figure out what I'm doing wrong. I'm sure the problem resides in the path I have entered, but I am a bit stumped at the moment. Thanks in advance.
getFilesDir documentation:
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
Typically, openFileOutput access to /data/data, which is completly different from your application install path.
If you want to access a file, put it in the assets folder the check the assets related functions (see AssetManaget)

Set ImageView from Bitmap (null pointer exception)

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.

Android Delete Image from SD Card with OnClick

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();
}

Correct way of invoking a phone call from within the app in android

I have a small piece of code which is basically supposed to make a phone call when a button is pushed. I looked it up online and all the sources basically gave the same code. But for some reason this code doesn't work. It makes the app crash but the LogCat doesn't display anything (meaning the log is completely blank). I should also mention that in my manifest file I did add the following permission
<uses-permission android:name = "andriod.permission.CALL_PHONE" />
The code I have is as follows. Any help would be greatly appreciated!
phoneButton.setOnClickListener(new OnClickListener () {
public void onClick(View v) {
try {
final Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:232131232"));
ContactUs.this.startActivity(callIntent);
}catch (ActivityNotFoundException e){
Log.e("Dialing", "call Failed!", e);
}
}
});
You spelt android wrong the second time...
Sounds like you need to add the user-permission for making a phone call. I believe the permission is:
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
in your manifest file.
This is a snippet from an Activity class I am currently testing on my HTC Desire -
okButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + getPhoneNumber()));
startActivity(intent);
}
});
I suggest changing ContactUs.this.startActivity(callIntent); to startActivity(callIntent); and testing it again.

why Geocoder.getFromLocationName(...) returns an empty list?

I'm using the android.location.Geocoder for the first time. The Idea is: I have a Listener on a button which takes input from an EditText and resolve the location. Up to now it's debugging phase, so I have no handler taking messages from the thread, only geocoding and write to logcat.
Q: Why this method always returns an empty list of Address objects?
private View.OnClickListener checkLocation = new View.OnClickListener() {
#Override
public void onClick(View v) {
location = ((EditText)findViewById(R.id.getLocation)).getText().toString();
Thread thr = new Thread(){
public void run (){
Log.d("Looking for", location);
Geocoder gc = new Geocoder(ctx,Locale.ITALY);
try {
fa= gc.getFromLocationName(location, 3);
if (fa.isEmpty())Log.d("getFromLocationName", "NothingFound");
else
{
int size= fa.size();
for (int i = 0; i<size ;i++)
Log.d("getFromLocationName.at("+ String.valueOf(i) +")", fa.get(i).getAddressLine(0)+", "+fa.get(0).getAddressLine(1));
}
} catch (IOException e) {
Log.e("IOException", e.getMessage());
}
}
};
thr.start();
}
};
manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Somebody knows why? (btw I am using 1.6 sdk) Input tried
the project wasn't targeting the correct AVD. To use geolocation you have to make it point an avd implementing the google APIs. Once I changed it everything worked just fine. Sorry for bothering
Because it doesn't recognize the address you are putting in or it can't reach the service.
What address are you putting in? Try something as simple as a zip code or city or state name.

Categories

Resources