I want to make an application that allows me to choose a file from SDcard (.apk file), then send it by HTTP Post to a web service.
The problem is that even if I can choose the file, I can't convert it in a byte array because my application is looking for it in its private folders, not in SDcard.
I used Intent to access to FileManager and choose a file from storage. Then, a toast notification shows me its path.
public class MainActivity extends AppCompatActivity {
Button button1;
Intent intent;
String PathHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
PathHolder = data.getData().getPath();
File file = new File(PathHolder);
String FileName = file.getName();
Toast.makeText(MainActivity.this, PathHolder, Toast.LENGTH_LONG).show();
try {
byte[] bArray = new byte[(int) file.length()];
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(bArray);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
}
After
FileInputStream inputStream = new FileInputStream(f);
My application throws an Exception and the response is :
File Not Found
The variable f, on which you are constructing the FileInputStream of is never assigned or am I wrong? I think you should change f to file.
Related
I have an app that opens up a file picker and it outputs the path of that file in a Toast Message.
But I would like to change it such that the file that I pick is passed as a parameter to a function.
My activity looks like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.btn_picker);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 7);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
String PathHolder = data.getData().getPath();
Toast.makeText(MainActivity.this, "The Files path is: "+ PathHolder, Toast.LENGTH_LONG).show();
}
break;
}
}
}
And it does what it is supposed to do but instead of outputting the file path, I would like to call the function
importToFile()
From the manage class.
I would like to do something like this:
manage.importToFile(File1)
Where File1 is the file I selected from the file picker.
How can I do that.
Thanks in advance.
You can use File class in android to work with files. Create an instance of File using the path of the selected file and pass it to that method of yours. Something like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
// as #Taseer Ahmad said its not a good way to get path of the file.
//String PathHolder = data.getData().getPath();
String PathHolder = getPath(this, data.getData());
if (!TextUtils.isEmpty(PathHolder)) {
File file = new File(PathHolder);
manager.importToFile(file);
Toast.makeText(MainActivity.this, "The Files path is: "+ PathHolder, Toast.LENGTH_LONG).show();
}
}
break;
}
}
EDIT
As #Taseer Ahmad said, data.getData().getPath() is not a safe way to get path of the selected file. This code is copied from here.
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
New in Android and
Working on an app like This
At the end got the problem java.io.FileNotFoundException: /document/86: open failed: ENOENT (No such file or directory)
Now I'm working on the solution that
"That how to use ContentResolver and openInputStream()"
Anyone help me how to do this, please
if you trying to make an app that read a file from Phone
Try This
Try this may help
private InputStream getResources(String s) {
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent, 7);
Log.v("###", "parent " + getParent());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri PathHolder = data.getData();
Log.v("###", "yo " + PathHolder);
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
setContentView(R.layout.activity_main);
try {
InputStream inputStream = getContentResolver().openInputStream(PathHolder);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String mLine;
while ((mLine = r.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have a method that takes a picture and then in the onActivityResult passes to another activity for subsequent analysis of the picture. So far so good.
My problem is that when I use a handler to repeat the process every 10 sec, the method is called but it will only take photos automatically without passing to the other activity. My guess is that when the method is called again automatically the onActivityResult is never called. Does anybody have a clue of which could may be be the problem?
takePhotoBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
TakePhoto();
}
});
private void TakePhoto() {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagepath = new File(getFilesDir(), "images");
File newFile = new File(imagepath, ".jpg");
if (newFile.exists()) {
newFile.delete();
}else {
newFile.getParentFile().mkdir();
}
selectedPhotoPath = getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", newFile);
startActivityForResult(captureIntent, TAKE_PHOTO_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST_CODE && resultCode == RESULT_OK) {
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(selectedPhotoPath);
bundle = new Bundle();
bundle.putParcelable(KEY_BITMAP, selectedPhotoPath);
}catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
Intent intent = new Intent(this, Activity.class);
intent.putExtras(bundle);
startActivity(intent);
handler.postDelayed(new Runnable() {
#Override
public void run() {
TakePhoto();
handler.postDelayed(this, 10000);
}
},10000);
}
Any kind of help will be highly appreciated!!! Thanks
So I'm completely new to Android programming and I'm starting off by trying to make an app that allows users to edit audio files. Here is my code so far, which makes a user upload an audio file and play it:
public class MainActivity extends Activity {
final int ACTIVITY_CHOOSE_FILE = 1;
public String filePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.uploadbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("audio/mpeg");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
});
Button playButton = (Button)findViewById(R.id.playbutton);
playButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(getApplicationContext(), Uri.parse(filePath));
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
filePath = uri.getPath();
getFilePath(filePath);
TextView URI_Text = (TextView)findViewById(R.id.file_URI);
URI_Text.setText(filePath);
}
}
}
}
public String getFilePath (String filePath) {
return filePath;
}
}
However, I'm getting the error code E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab756e00
What am I doing wrong?
That error is not related to any of your code from your question. However, you are going wrong in other places.
getPath() is useless. The Uri should be treated as an opaque handle. Calling getPath() on a Uri, and expecting a file to be at that path, is akin to expecting there to be a /questions/33843271/error-when-trying-to-play-audio-file-from-uri path on your computer's hard drive, just because your browser happens to be showing a URL with that path.
Also, your access to the data represented by that Uri is short-lived. This is reminiscent of Web development, where you might be able to stream data from some URL for a while, but eventually your session times out. Saving the Uri is pointless. Either consume the data now (via a ContentResolver and openInputStream()), or don't bother with the data at all.
I am trying to add in my App a function to use the camera to store photos in my device.
At the beginning i use the camera like this:
mButtonCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
String file = dir+prova+".jpg";
File newFile = new File(file);
try {
newFile.createNewFile();
}catch (IOException e){}
Uri outputFileUri = Uri.fromFile(newFile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);
Log.v("CameraDemo", "Pic savedNO");
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
And then for the OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.v("CameraDemo", "Pic saved");
Log.v("Salva Foto", dir+prova+".jpg");
myDBHandler.addPhoto(prova,dir+prova+".jpg");
}
}
Until here evrything is ok but when I try to retrieve the photo using this:
InputStream URLcontent = null;
try {
URLcontent = (InputStream) new URL(fotoSI).getContent();
} catch (IOException e) {
e.printStackTrace();
}
Drawable image = Drawable.createFromStream(URLcontent, fotoSI);
mImageCamera.setImageDrawable(image);
It doesn´t return any photo that is what the Log says me:
java.net.MalformedURLException: Protocol not found: /storage/emulated/0/Pictures/
I am trying everything but without results.