Reputation: 35
I made a desktop version for encrypting and decrypting files, my boss was very excited so he gave me the task to make an app out of it.
Activity A has two buttons on it, one for encryption and one for decryption. When the user presses one of the buttons an "pickfile" intent comes up:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*.*");
startActivityForResult(intent, PICKFILE_RESULT_CODE);
Then I have the Result Method:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK)
{
Pfad = data.getData().getPath();
}
}
}
My hope was that I can use the "Pfad" variable directly after calling startActivityForResult(intent, PICKFILE_RESULT_CODE);
but the compiler shows me an error that "Pfad" is NULL. I also noticed that the app executes the code which comes after the startActivityForResult() directly, but also the pickfile dialog comes up for a sec?
Can some one help me out here? Thank you a lot!
EDIT I forgot to set the variables, but now a new error appears... after I call "startAcitivityForResult()" I directly call my method "setVariables(..)" which trims the path I got from the result Method... heres my method:
private void setVariables(int i, String fullFileName)
{
String tmp = "";
if(i == 1) //verschlüsseln
{
ext = fullFileName.substring(fullFileName.lastIndexOf(".")).toLowerCase();
tmp = fullFileName.substring(0, fullFileName.toLowerCase().lastIndexOf(ext));
}
else if(i == 2) //entschlüsseln
{
ext = fullFileName.substring(fullFileName.lastIndexOf(".")).toLowerCase();
if(ext.equals(encryptExt))
{
tmp = fullFileName.substring(0, fullFileName.toLowerCase().lastIndexOf(encryptExt));
ext = tmp.substring(tmp.lastIndexOf("."));
tmp = fullFileName.substring(0, fullFileName.toLowerCase().lastIndexOf(ext + encryptExt));
}
}
Path = tmp.substring(0, tmp.lastIndexOf("\\")+1);
fileNameOrig = tmp.substring(Path.length(), tmp.length());
fileNameEncrypt = fileNameOrig;
}
The debugger fires me an error that the lenght of my variable "Pfad" (which stands for path, I have no idea why I made it german xD) is 0.
As I said, it seems that the "startActivityForResult" dosent pause my main activity, because I can´t choose any file, it directly goes to the "setVariables" method?
Btw. the button event handlers are inside the onCreate() Method of the main activity, maybe this causes the error?
Upvotes: 0
Views: 2352
Reputation: 1537
startActivityForResult
is of course starting another Activity. So the Activity you are working on should normally get paused. You then get a File-Picker.
After you chose a File, you will get into onActivityResult
which is more or less a Callback-Function.
So your variable Pfad will get defined inside of the Callback, but not previously, so it is null.
If you don't understand my answer, just read the Android Documentation.
Upvotes: 4