upload file(image) into quickblox custom object - java

How do I upload file (image) that I have his Uri, into custom object?
I've tried this:
public void onClick(View v) {
HashMap<String, Object> fields = new HashMap<String, Object>();
File newImage = new File(imageUri.toString());
fields.put("image", newImage);
fields.put("bla", "bla");
QBCustomObject qbCustomObject = new QBCustomObject();
qbCustomObject.setClassName("imageClass"); // your Class name
qbCustomObject.setFields(fields);
QBCustomObjects.createObject(qbCustomObject, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBCustomObjectResult qbCustomObjectResult = (QBCustomObjectResult) result;
QBCustomObject qbCustomObject = qbCustomObjectResult.getCustomObject();
// Log.d("New record: ",newCustomObject.toString());
} else {
Log.e("Errors",result.getErrors().toString());
}
}
});
And I get just the string ("bla") and the image get - null
Thank you

Currently this feature is in development brunch. Will be in master in a couple of days
But you can use it already - Download SDK from development brunch
https://github.com/QuickBlox/quickblox-android-sdk/tree/development
Here are lots of snippets, especially for Custom Objects module
https://github.com/QuickBlox/quickblox-android-sdk/blob/development/snippets/src/com/quickblox/snippets/modules/SnippetsCustomObjects.java
Upload file
QBCustomObject qbCustomObject = new QBCustomObject(CLASS_NAME, NOTE1_ID);
QBCustomObjectsFiles.uploadFile(file1, qbCustomObject, AVATAR_FIELD, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBCustomObjectFileField customObjectFileField = ((QBCOFileUploadResult) result).getCustomObjectFileField();
Log.i(TAG, ">>>upload response:" + customObjectFileField.getFileName() + " " + customObjectFileField.getFileId() + " " +
customObjectFileField.getContentType());
} else {
handleErrors(result);
}
}
});
Download file
QBCustomObject qbCustomObject = new QBCustomObject(CLASS_NAME, NOTE1_ID);
QBCustomObjectsFiles.downloadFile(qbCustomObject, AVATAR_FIELD, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
QBFileDownloadResult downloadResult = (QBFileDownloadResult) result;
if (result.isSuccess()) {
byte[] content = downloadResult.getContent(); // that's downloaded file content
InputStream is = downloadResult.getContentStream(); // that's downloaded file content
Log.i(TAG, ">>> file downloaded successfully" + getContentFromFile(is));
if(is!=null){
try{
is.close();
}catch(IOException e){
e.printStackTrace();
}
}
} else {
handleErrors(result);
}
}
});
Delete file
QBCustomObject qbCustomObject = new QBCustomObject(CLASS_NAME, NOTE1_ID);
QBCustomObjectsFiles.deleteFile(qbCustomObject, AVATAR_FIELD, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
Log.i(TAG, ">>> file deleted successfully");
} else {
handleErrors(result);
}
}
});

Related

Android Error: FFMPEG No such file or directory error

I went through the solution here.
Android FFMpeg No such file or directory error but it doesn't work for me.
The file is present in the location and I am still getting this error.
Here is the code snippet
private void spliceSong(AudioObject audioObject) {
File folder = new File("/sdcard/roboscreen/TempAudio");
if (!folder.exists()) {
folder.mkdir();
}
String fileName = new File(audioObject.path).getName();
File dest = new File(folder, fileName);
Log.d(TAG, "Destination Filename is " + fileName);
if (!dest.exists()){
try {
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
String path = new File(audioObject.path).getPath();
Log.d(TAG, "File created " + dest.getAbsolutePath() + " " + audioObject.endDate + " " + audioObject.startDate);
String[] command = {"-ss", "2", "-i", "root/"+path, dest.toString()};
Log.d(TAG, "spliceSong: " + (this.context==null));
FFmpeg ffmpeg = FFmpeg.getInstance(this.context);
// // to execute "ffmpeg -version" command you just need to pass "-version"
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler(){
#Override
public void onSuccess() {
super.onSuccess();
Log.d(TAG, "onSuccess: bruhhhhh");
}
});
} catch (FFmpegNotSupportedException e) {
// Log.d(TAG, "Kaam Tamaam");
e.printStackTrace();
}
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
#Override
public void onStart() {
Log.d(TAG, "Work Started done");
}
#Override
public void onProgress(String message) {
Log.d(TAG, "Doing some work");
}
#Override
public void onFailure(String message) {
Log.d(TAG, "Conversion failure " + message);
}
#Override
public void onSuccess(String message) {
Log.d(TAG, "Conversion Successful");
}
#Override
public void onFinish() {
Log.d(TAG, "Work Dome");
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
Log.d(TAG, e.toString());
e.printStackTrace();
}
// Log.d(TAG, "spliced");
// return File
}
and the context is coming through a different class
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ScreenRecorder(RoboTutor activity, Context context) throws Exception {
if (isInstantiated){
// raise Error and quit
throw new Exception("One instance already instantiated");
}
this.activity = activity;
this.context = context;
this.isInstantiated = true;
this.videoTimeStamp = new Date();
}
A solution would be really appreciated.
Thanks in advance.
Figured it out. There were no issues with the library. I was referring to the wrong paths.

Downloaded file not visible from the file browser

I download a file from firebase using file like. If I run this code on android emulator then I can see the downloaded file from file browser but in the real phone, it does not display the file.
private void DownloadFromStorage(String fileName) {
// CREATE FOLDER IF NOT EXIST
File dir = new File(DownloadActivity.this.getExternalFilesDir(null), "notes");
if (!dir.exists()) {
boolean b = dir.mkdir();
}
// CREATE FILE
File file = new File(DownloadActivity.this.getExternalFilesDir(null), fileName);
StorageReference storageReference = FirebaseStorage.getInstance().getReference()
.child("note")
.child(fileName);
Log.d("downloadFile: " ,""+ storageReference.getPath());
storageReference.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
if (getBaseContext() != null) {
txtStatus.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
myToast("Download Complete.");
Log.d("downloadFile: " ,"DOWNLOAD COMPLETE");
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (getBaseContext() != null) {
txtStatus.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
myToast("Download Fail");
Log.d("downloadFile: " ,"DOWNLOAD FAIL");
}
}
}).addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull FileDownloadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
#SuppressLint("DefaultLocale") String uc = String.format("Downloading... %.2f ", progress);
if (getBaseContext() != null) txtStatus.setText(uc);
}
});
}
How can I see this file from the file browser?

Save file on google drive

Hey I'm trying do application where i check my current location and save this location in ".txt" files. My application save this location in every "user set time" seconds. And it's work. Also I want add save files to Google drive. But I don't know how. Is there any method by which I can create a folder and save ".txt" files same as i did with local folder?
public class Save extends AppCompatActivity {
boolean sms = false;
int n_seconds, n_minutes, n_sum;
private String path = Environment.getExternalStorageDirectory().toString() + "/Loc/Save";
private Button buttonStartThread;
private Handler mainHandler = new Handler();
private volatile boolean stopThread = false;
NumberPicker edit_text_input_back, edit_text_input_back_2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_background);
buttonStartThread = findViewById(R.id.button_start_thread);
edit_phone_number = findViewById(R.id.edit_phone_number);
edit_mail = findViewById(R.id.edit_email);
edit_text_input_back = (NumberPicker) findViewById(R.id.edit_text_input_back);
edit_text_input_back.setMaxValue(60);
edit_text_input_back.setMinValue(0);
edit_text_input_back.setValue(0);
edit_text_input_back_2 = (NumberPicker) findViewById(R.id.edit_text_input_back_2);
edit_text_input_back_2.setMaxValue(60);
edit_text_input_back_2.setMinValue(0);
edit_text_input_back_2.setValue(0);
edit_text_input_back.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
n_seconds = i1;
}
});
edit_text_input_back_2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
n_minutes = 60 * i1;
}
});
}
public void startThread(View view) {
stopThread = false;
n_sum = n_seconds + n_minutes;
ExampleRunnable runnable = new ExampleRunnable(n_sum);
new Thread(runnable).start();
buttonStartThread.setEnabled(false);
}
public void stopThread(View view) {
stopThread = true;
buttonStartThread.setEnabled(true);
}
class ExampleRunnable implements Runnable {
int seconds;
ExampleRunnable(int seconds) {
this.seconds = seconds;
}
#Override
public void run() {
for (; ; ) {
for (int i = 0; i < seconds; i++) {
if (stopThread)
return;
if (i == n_sum-1) {
runOnUiThread(new Runnable() {
#Override
public void run() {
createDir();
createFile();
}
});
}
Log.d(TAG, "startThread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private void createDir() {
File folder = new File(path);
if(!folder.exists()){
try {
folder.mkdirs();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
private void createFile() {
File file = new File(path+"/"+System.currentTimeMillis()+".txt");
FileOutputStream fileOutputStream;
OutputStreamWriter outputStreamWriter;
try {
Intent intent = getIntent();
Double lat = intent.getDoubleExtra("adres", 0);
Double lon = intent.getDoubleExtra("adres2", 0);
String adr = intent.getStringExtra("adres3");
fileOutputStream = new FileOutputStream(file);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.append("Your adress: " + adr + ". " + "Your latitude: " + lat + ", " + "longtitude: " + lon+".");
outputStreamWriter.close();
fileOutputStream.close();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Thank you in advance
There are ample sources you can check for creating a folder, and uploading a file to Google Drive
Creating Folder
File fileMetadata = new File();
fileMetadata.setName("Invoices");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = driveService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Uploading File
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
For the specific mime type of a txt file, you might need to refer this StackOverflow post (text/plain). For specific Google applications mime types, please see documentation.

AWS TransferManager returning more bytes transferred than file size, causing hang

I'm using AWS's Java SDK to upload some files (>130 MBs) into an S3 bucket.
The issue I'm having is that during the upload process (using TransferManager), the getBytesTransferred() returns a number greater than that of the file size itself.
This is causing my Progress Dialog to hang at 100%.
Am I missing some sort of configuration?
I should point out that this doesn't happen all the time.
public class PutFileTask extends AsyncTask<Void, Long, UploadZipCode> {
#Override
protected UploadZipCode doInBackground(final Void... params) {
// Initialize S3 Client
BasicAWSCredentials credentials = new BasicAWSCredentials(mS3AccessKey, mS3SecretKey);
AmazonS3Client amazonS3Client = new AmazonS3Client(credentials);
mTransferManager = new TransferManager(credentials);
mUploadStart = new Date(System.currentTimeMillis());
Upload myUpload = mTransferManager.upload(mS3UploadBucket, mFile.getName(), mFile);
myUpload.addProgressListener(new ProgressListener() {
long totalBytesTransferred = 0;
#Override
public void progressChanged(ProgressEvent progressEvent) {
totalBytesTransferred += progressEvent.getBytesTransferred();
Log.d(TAG, "Bytes transferred = " + totalBytesTransferred);
onProgressUpdate(totalBytesTransferred);\
if (progressEvent.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE) {
cancel(true);
} else if (progressEvent.getEventCode() == ProgressEvent.FAILED_EVENT_CODE
|| progressEvent.getEventCode() == ProgressEvent.CANCELED_EVENT_CODE) {
Log.e(TAG, "Uploaded erred out with AWS Event Code: " + progressEvent.getEventCode());
cancel(true);
}
Log.d(TAG, "Setting completion code to: " + progressEvent.getEventCode());
}
});
try {
myUpload.waitForCompletion();
} catch (InterruptedException e) {
cancel(true);
e.printStackTrace();
return UploadZipCode.CONNECTION_ERROR;
} catch (Exception e) {
cancel(true);
e.printStackTrace();
return UploadZipCode.AWS_ERROR;
}
return UploadZipCode.UPLOAD_SUCCESS;
}
...
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(mActivity);
mProgressDialog.setTitle("Please wait...");
mProgressDialog.setMessage("Uploading your session zip file...");
mProgressDialog.setProgressStyle(mProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setProgress(0);
mProgressDialog.setMax((int) (mFile.length()));
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
...
#Override
protected void onProgressUpdate(Long... values) {
super.onProgressUpdate(values);
for (long value : values) {
mProgressDialog.setProgress((int) value);
}
}
...
#Override
protected void onPostExecute(UploadZipCode resultCode) {
super.onPostExecute(resultCode);
mProgressDialog.dismiss();
mListener.onUploadFinished(resultCode);
}
...
#Override
protected void onCancelled(UploadZipCode resultCode) {
super.onCancelled(resultCode);
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
mListener.onUploadFinished(resultCode);
}
}

Upload progress listener not fired (Google drive API)

I want to show progress by percent of an uploading file using Google drive API.
My menthod has successful upload a file before but It can't see upload progress.
I've seen and added this FileUploadProgressListener but mediaHttpUploader.getProgress() show only 0.0 (start of progress) and 1.0 (when progress finished). I can't get percent of progress in time.
How to make It work?
Here is my Upload code:
public void UploadFile(final DFile uploadFile) {
if (!isLoggedIn()) {
OnUploadGoogleChecked(FALSE, "Not logged in");
return;
}
AsyncTask<Void, Long, String> task = new AsyncTask<Void, Long, String>() {
java.io.File fileContent;
FileContent mediaContent;
com.google.api.services.drive.model.File body;
com.google.api.services.drive.model.File file;
private ProgressDialog mDialog;
long mFileLen;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mDialog = new ProgressDialog(act);
mDialog.setMax(100);
mDialog.setMessage("Uploading ");
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
mDialog.show();
}
class FileUploadProgressListener implements MediaHttpUploaderProgressListener {
#Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
Log.d("Dolphin got percent", String.valueOf(uploader.getProgress()));
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
System.out.println("Initiation Started");
break;
case INITIATION_COMPLETE:
System.out.println("Initiation Completed");
break;
case MEDIA_IN_PROGRESS:
System.out.println("Upload in progress");
System.out.println("Upload percentage: " + uploader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Upload Completed!");
break;
case NOT_STARTED:
System.out.println("Upload Not Started!");
break;
}
}
}
#Override
protected String doInBackground(Void... arg0) {
try {
java.io.File UPLOAD_FILE = new java.io.File(uploadFile.getNameAndDir());
// File's metadata.
fileContent = new java.io.File(uploadFile.getNameAndDir());
mFileLen = fileContent.length();
InputStreamContent mediaContent2 = new InputStreamContent("image/jpeg", new BufferedInputStream(new FileInputStream(UPLOAD_FILE)));
mediaContent2.setLength(UPLOAD_FILE.length());
body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
String parentId = null;
body.setParents(Arrays.asList(new ParentReference().setId(uploadFile.getFileHostFolderId())));
Drive.Files.Insert mInsert = service.files().insert(body, mediaContent2);
MediaHttpUploader uploader = mInsert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(true);
uploader.setProgressListener(new FileUploadProgressListener());
file = mInsert.execute();
if (file != null) {
}
} catch (UserRecoverableAuthIOException e) {
Log.d("Dolphin got error", "not login " + e);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
mDialog.dismiss();
OnUploadGoogleChecked(TRUE, "Upload complete");
};
};
task.execute();
}
To get progress, you must use uploader.setDirectUploadEnabled(false); (instead of true) and uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE); or any value which must be the multiply of MediaHttpUploader.MINIMUM_CHUNK_SIZE, else it will cause error.

Categories