Parse: cannot upload file - java

I want to make an app which have upload file function. But the problem is, I unable to find where did I do wrong.
First, choose the file
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
// intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
Log.d(TAG, "Select file");
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
RESULT_LOAD_FILE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(MainActivity.this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
// here
}
I guess there's no problem when choosing the file based on the logcat. But...
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, requestCode+"/"+RESULT_LOAD_FILE+"/"+resultCode+"/"+RESULT_OK);
if (data != null) Log.d(TAG, data.toString());
else Log.d(TAG, "data null");
// get file name
String fileNameSegments[] = filePath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
// convert it to byte
byte[] fileByte = fileName.getBytes();
// Create the ParseFile
ParseFile file = new ParseFile(fileName, fileByte);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject fileupload = new ParseObject("FileUpload");
// Create a column named "ImageName" and set the string
fileupload.put("FileName", fileName);
// Create a column named "ImageFile" and insert the image
fileupload.put("DocFile", file);
// Create the class and the columns
fileupload.saveInBackground();
// Show a simple toast message
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
}
The logcat show requestCode, RESULT_LOAD_FILE, resultCode and RESULT_OK 1, 1, -1 and -1 respectively. And the data is not null, as in logcat: Intent { dat=content://com.android.externalstorage.documents/document/0A09-1112:Download/Contact n Tort.pdf flg=0x1 }
After I click the .pdf file, it triggered the toast Something went wrong but I can't find what the reason.
EDITED:
Throw null pointer exception after convert the file path to byte, when I remove the try catch block

it should be like this
Uri uri = data.getData();
// get path
filePath = uri.getPath();
// get file name
String fileNameSegments[] = filePath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
// convert it to byte
byte[] fileByte = fileName.getBytes();
// Create the ParseFile
ParseFile file = new ParseFile(fileName, fileByte);
// Upload the file into Parse Cloud
file.saveInBackground();
// Create a New Class called "FileUpload" in Parse
ParseObject fileUpload = new ParseObject("FileUpload");
// Create a column named "FileName" and set the string
fileUpload.put("FileName", fileName);
Log.d(TAG, "image file");
// Create a column named "ImageFile" and insert the image
fileUpload.put("DocFile", file);
// Create the class and the columns
fileUpload.saveInBackground();
Log.d(TAG, "toast");
// Show a simple toast message
Toast.makeText(MainActivity.this, "File Uploaded",
Toast.LENGTH_SHORT).show();
though the class not created in parse dashboard but I guess that need another post.

Related

not able to get full real path with name of selected file [duplicate]

This question already has answers here:
Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?
(5 answers)
Android - Get real path of a .txt file selected from the file explorer
(1 answer)
Closed 2 years ago.
I am not geting currect path var name "FilePath" im geting value E/File path: /document/29 but my selected file stored in downloads folder file name is "test.xlsx" i need original path with file name with file extention to pass in FileInputStream().I am not able to fix it ...can anybody give the code
btnimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("*/*");
try {
startActivityForResult(fileintent, requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity can handle picking a file. Showing alternatives.");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String FilePath = data.getData().getPath();
Log.e("File path", FilePath);
if (FilePath.contains("/root_path"))
FilePath = FilePath.replace("/root_path", "");
Log.e("New File path", FilePath);
try {
if (resultCode == RESULT_OK) {
AssetManager am = this.getAssets();
InputStream inStream;
Workbook wb = null;
try {
inStream = new FileInputStream(FilePath);
Log.e("Extension",FilePath.substring(FilePath.lastIndexOf(".")));
if (FilePath.substring(FilePath.lastIndexOf(".")).equals(".xls")) {
Log.e("File Type", "Selected file is XLS");
wb = new HSSFWorkbook(inStream);
}
else if (FilePath.substring(FilePath.lastIndexOf(".")).equals(".xlsx")) {
Log.e("File Type", "Selected file is XLSX");
wb = new XSSFWorkbook(inStream);
}
else {
wb = null;
lbl.setText("Please select a valid Excel file");
return;
}
inStream.close();
i need original path with file name with file extention to pass in FileInputStream().
No you do not need 'a real path' as you better use the obtained uri to open an input stream.
InputStream is = getContentResolver().openInputStream(data.getData());
Use that stream as if it was your wanted stream.

Get real path of a file from URI? [duplicate]

I am trying to fetch a file this way:
final Intent chooseFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
String[] mimetypes = {"application/pdf"};
chooseFileIntent.setType("*/*");
chooseFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
if (chooseFileIntent.resolveActivity(activity
.getApplicationContext().getPackageManager()) != null) {
chooseFileIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
activity.startActivityForResult(chooseFileIntent, Uploader.PDF);
}
Then in onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
According to many threads I'm supposed to fetch the file name from the intent with data.getData().getPath(), the file name I'm expecting is my_file.pdf, but instead I'm getting this :
/document/acc=1;doc=28
So what to do? Thanks for your help.
I am trying to fetch a file
Not with that code. That code is asking the user to pick a piece of content. This may or may not be a file.
According to many threads I'm supposed to fetch the file name from the intent with data.getData().getPath()
That was never correct, though it tended to work on older versions of Android.
So what to do?
Well, that depends.
If you wish to only accept files, integrate a file chooser library instead of using ACTION_GET_CONTENT. (UPDATE 2019-04-06: since Android Q is banning most filesystem access, this solution is no longer practical)
If you are willing to allow the user to pick a piece of content using ACTION_GET_CONTENT, please understand that it does not have to be a file and it does not have to have something that resembles a filename. The closest that you will get:
If getScheme() of the Uri returns file, your original algorithm will work
If getScheme() of the Uri returns content, use DocumentFile.fromSingleUri() to create a DocumentFile, then call getName() on that DocumentFile — this should return a "display name" which should be recognizable to the user
To get the real name and to avoid getting a name that looks like "image: 4431" or even just a number, you can write code as recommended by CommonsWare.
The following is an example of a code that selects a single pdf file, prints its name and path to the log, and then sends the file by email using its uri.
private static final int FILEPICKER_RESULT_CODE = 1;
private static final int SEND_EMAIL_RESULT_CODE = 2;
private Uri fileUri;
private void chooseFile() {
Intent fileChooser = new Intent(Intent.ACTION_GET_CONTENT);
fileChooser.setType("application/pdf");
startActivityForResult(Intent.createChooser(fileChooser, "Choose one pdf file"), FILEPICKER_RESULT_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILEPICKER_RESULT_CODE) {
if (resultCode == RESULT_OK) {
fileUri = data != null ? data.getData() : null;
if (fileUri != null) {
DocumentFile d = DocumentFile.fromSingleUri(this, fileUri);
if (d != null) {
Log.d("TAG", "file name: " + d.getName());
Log.d("TAG", "file path: " + d.getUri().getPath());
sendEmail(fileUri);
}
}
}
}
}
private void sendEmail(Uri path) {
String email = "example#gmail.com";
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("application/octet-stream");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "PDF file");
String[] to = { email };
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.putExtra(Intent.EXTRA_TEXT, "This is the pdf file...");
intent.putExtra(Intent.EXTRA_STREAM, path);
startActivityForResult(Intent.createChooser(intent, "Send mail..."), SEND_EMAIL_RESULT_CODE);
}
hope it helps.

Retrieving file on sdcard with this path: "/document/primary:..."

I'm trying to read contents of a CSS file, which is on my SDCARD.
I'm selecting the file from a action:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/css");
startActivityForResult(intent, 1);
Here I grab the path:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(getActivity().getApplicationContext());
SharedPreferences.Editor editor = sharedPref.edit();
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
Log.d("FilePicker", data.getData().toString());
editor.putString("custom_style_file", data.getData().getPath());
editor.commit();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
I get the following path /document/primary:CustomCSS/myCustom.css
Then i try to read the contents of the file with this function:
public static String readFromSDcard(String path) {
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard, path);
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
Log.d("Read from file", text.toString());
return text.toString();
}
The function returns nothing, and I'm not sure what I'm doing wrong here.
//You'll need to add proper error handling here
If you do so you will see why your function returns nothing.
For instance:
text.append("IOException: " + e.getMessage() + "\n");
Your path:
/document/primary:CustomCSS/myCustom.css
That is not a file syctem path but a content provider path.
So get a content resolver and then let it open an input stream for the file. After that you can use the usual code to read the contents.
Google for getContentResolver().openInputStream().
Make sure you have the the read storage permission in your manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How to get file path of any text file and read it from SD card in Android?

I have got so many links related to image file but didn't get any text related. There is solution for specific text file to open but I need general solution and not hard coded file location on SD card. I'm building an Android app that gets (copyies) the link of the file in TextView and reads the content of that file in another TextView from SD card. One button which is used to open the SD card:
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("text/plain"); //open only for text file
intent.setAction(Intent.ACTION_GET_CONTENT);
//broadcast the supported media to choose for file to open
startActivityForResult(Intent.createChooser(intent, "Select file"), MY_INTENT_CLICK);
}
This is the code for onActivityResult()
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == MY_INTENT_CLICK) {
if (data == null) return;
//String sel_file_path;
String sel_file_path;
Uri sel_file_uri = data.getData();
sel_file_path = FileText.getPath (getApplicationContext(), sel_file_uri);
setTextViews (sel_file_path);
}
}
}
After getting the file path from FileText it views the link and content of text file using this method.
//show the link and display the content of the file
private void setTextViews(String sel_file_path) {
//copy the file link to textview
this.txtpath.setText("File path: " +sel_file_path);
//display the text file
try {
File file1 = new File(sel_file_path);
//System.out.println("Path : " + file1);
FileInputStream fis = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String datatoread = "";
String inBuffer = "";
//Read the line of the file, store it in temporary variable and append it to inBuffer
while ((datatoread = br.readLine()) != null) {
inBuffer += datatoread + "\n";
}
txtdsp.setText(inBuffer);
br.close();
//Toast.makeText(getBaseContext(), "Load file reading", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
Log.d("MainActivity", "File Path: "+sel_file_path);
}
I got the an error while running on a device:
no such file or directory

Take photo, display photo thumbnail in new activity upon success

Right now I've got an app that takes a photo via an intent. After taking the photo, I want the user to be able to confirm it and push the photo to another activity where they can add details. I'm struggling to find the correct way to pass the photo from activity to activity.
Right now, confirming the photo brings the user back to the main activity.
Here's my relevant code:
Main Activity
public void takePhoto(View view) {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Log.d("MySecondApp",fileUri.toString());// create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if (data!=null) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MySecondApp");
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MySecondApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
I would try something like
if(resultCode == Activity.RESULT_OK)
handleCameraPhoto(data);
handle method:
private void handleCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", mImageBitmap);
startActivity(intent);
}
and then, retrieve it in your other activity
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
and assign it to your ImageView
ImageView iv = (ImageView)findViewById(R.id.myImageView);
iv.setImageBitmap(bitmap);
Make a constructor in your new class that takes an intent or even the image:
class newClass {
public newClass(Intent intent){
...
}
...
}
And then just make the intent the size of a thumbnail in this new class where you can do the confirmation in a popup or something similar and then have the information to be filled on the page for this class. This will also be better because if they wanted to retake the picture you could have this class which they are taken to after the picture is taken if not accepted go to take another picture.
Take a look at this blog post I wrote on how to take a full size image and a thumbnail version as well:
Use Camera Activity for Thumbnail and Full Size Image
after you did that you can extract the file path of the saved file from the file instance using getAbsolutePath() method and pass it to the following Activity.

Categories