storing multiple ParseFile objects in single ParseObject - android

ANDROID
This is how I store ParseFile List into ParseObject
ParseObject pObject = new ParseObject();
ArrayList<ParseFile> pFileList = new ArrayList<ParseFile>();
for (String thumbPath : thumbList) {
byte[] imgData = convertFileToByteArray(thumbPath);
ParseFile pFile = new ParseFile("mediaFiles",imgData);
pFileList.add(pFile);
}
pObject.addAll("mediaFiles", pFileList);
pObject.saveEventually();
after this call it does not show the inserted row in data browser, although it shows rowcount of 1 in table
This is how i retrieve it and get the first image from the list
List<ParseFile> pFileList = (ArrayList<ParseFile>) pObject.get("mediaFiles");
if (!pFileList.isEmpty()) {
ParseFile pFile = pFileList.get(0);
byte[] bitmapdata = pFile.getData(); // here it throws error
bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
}
I am able to retrieve all String columns , but for "mediaFiles" column while doing getData() I get thisexception.
com.parse.ParseException: Target host must not be null, or set in parameters.
I observed that in ParseFile, data and url is null.
Can somebody please show me the code on how to store and retrieve multiple ParseFile objects into single ParseObject?

Try uploading the ParseFiles using the save method before associating them with the Parse Object.

Try to do this thing as upload image one after another,
public void UploadImageToParse(String img_path, final String filedName, String Filename) {
//String img_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "P200913_1908.jpg";
final File file = new File(img_path);
try {
FileInputStream fileInputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] image_array = baos.toByteArray();
final ParseFile parsefile = new ParseFile(Filename, image_array);
parsefile.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
} else {
frameInfo.put(filedName, parsefile);
frameInfo.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
DebugLog.e("" + e);
} else {
fileUploadStatusUpdater.onFailure();
DebugLog.e("File Upload Fail");
}
}
});
/*ParseUser user = ParseUser.getCurrentUser();
user.put(filedName, parsefile);
user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Log.e("", "" + e);
}
});*/
}
}
}, new ProgressCallback() {
#Override
public void done(Integer integer) {
if (integer == 100) {
DebugLog.e("File Upload Completed");
fileUploadStatusUpdater.onSuccess();
}
}
});
} catch (Exception e) {
DebugLog.e("Fis" + e);
fileUploadStatusUpdater.onFailure();
}

Cover the
byte[] bitmapdata = pFile.getData();
line of code under try catch. It worked for me!

final ParseFile parseFile1 = new ParseFile("poll_image1.jpg",scaleImage("poll_image1",imageList.get(contestImage1.getId())));
final ParseFile parseFile2 = new ParseFile("poll_image2.jpg",scaleImage("poll_image2",imageList.get(contestImage2.getId())));
parseFile1.save(); parseFile2.save();
List<ParseFile> listOfFiles = new ArrayList<ParseFile>();
listOfFiles.add(parseFile1);
listOfFiles.add(parseFile2);
ParseObject jobApplication = new ParseObject("Poll");
jobApplication.put("poll_question", contestQuestion.getText().toString());
jobApplication.put("poll_type_id", 1);
ParseUser currentUser = ParseUser.getCurrentUser();
jobApplication.put("user", currentUser);
jobApplication.put("parseFile", listOfFiles);
jobApplication.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException arg0) {
}
});
Above code does multi upload, but ParseObject called only after Two save() method. Because of two save method UI getting Stuck. How to fix it!

Related

How to upload multiple images using multi-part in Volley in Android

I want to upload multiple images to server using multi-part, I didn't get proper code, anyone please help me to fix solve my problem.If i send as base64 format ,backend team cant able to get my image. Thats' why I go with multipart. Either Volley or Asynctask.
I tried this code from this link
https://www.simplifiedcoding.net/upload-image-to-server/
But multiple images I dont know how to do.
Main.Java
package com.getspot.getspot.imagerestapi;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if everything is ok we will open image chooser
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
try {
//getting bitmap object from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
//displaying selected image to imageview
imageView.setImageBitmap(bitmap);
//calling the method uploadBitmap to upload image
uploadBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
Log.i("AS","--"+byteArrayOutputStream.toByteArray());
return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap(final Bitmap bitmap) {
//getting the tag from the edittext
final String tags = editTextTags.getText().toString().trim();
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, ServerUtils.Gs_Clock_Image,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
JSONObject obj = new JSONObject(new String(response.data));
Log.i("AS","obj--"+obj);
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("AS","error--"+error);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("gs_userId", "6");
return params;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
Log.i("AS","imagename--"+imagename);
Log.i("AS","getFileDataFromDrawable(bitmap)--"+getFileDataFromDrawable(bitmap));
params.put("gs_task_image", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
}
Note:While passing the byte-array in gs_text_image,in that how can i send multiple images.I referred that above link.Please help me
I'll show you how I do it (particular case ofc, but it might give you an idea)
So, first of all you need the method interface which will look like this:
#Multipart
#POST(RestClient.UPLOAD_PICTURES_FOR_ORDER)
Call<YourTypeOfResponse> uploadPictures(#Part("images[]") RequestBody[] file, #Part MultipartBody.Part[] images);
now, you will have to prepare the files(images) that you have, for the request
private void multiparts(){
RequestBody reqFullPicFile;
MultipartBody.Part filepart;
RequestBody filename;
images = new MultipartBody.Part[files.size()];
filenameImages = new RequestBody[files.size()];
for (int file = 0; file < files.size(); file++){
reqFullPicFile = RequestBody.create(MediaType.parse("multipart/form-data"), files.get(file));
filepart = MultipartBody.Part.createFormData("full_picture", files.get(file).getName(), reqFullPicFile);
filename = RequestBody.create(MediaType.parse("text/plain"), files.get(file).getName());
images[file] = filepart;
filenameImages[file] = filename;
}
}
And, in the end, make the request with the created Multiparts (in this case images & filenameImages)
private void uploadPicturesReq(){
if (files != null) {
multiparts();
RestClient.getApi().uploadPictures(filenameImages, images)
.enqueue(new Callback<PicturesResponse>() {
#Override
public void onResponse(Call<PicturesResponse> call, Response<PicturesResponse> response) {
if (response.isSuccessful() && response.code() == 200) {
// here you can handle the response from server
}
}
#Override
public void onFailure(Call<PicturesResponse> call, Throwable t) {
Log.e(TAG, "-=onFailure=- " + t.getMessage(), t);
}
});
}
}

Downloading multiple pictures with Picasso

I'm trying to download multiple pictures using picasso. here's my code:
for(int i=1; i <=20; i++){
String url = img_url + i + "/profile.jpg";
String img_dir = img_dir + i;
Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));
}
Url of the site looks like this:
site.com/img/equipment/1/profile.jpg,
site.com/img/equipment/2/profile.jpg,
site.com/img/equipment/3/profile.jpg
and so on ...
i tried
Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));
without the for loop and it is working. images are not download when i place it inside the loop.
here's my Target
private Target picassoImageTarget(Context context, final String imageDir, final String imageName) {
Log.d("picassoImageTarget", " picassoImageTarget");
ContextWrapper cw = new ContextWrapper(context);
final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
return new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
final File myImageFile = new File(directory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath());
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {}
}
};
}
please help. thanks.
Targets are held in WeakReferences.
You need to hold a reference to the Targets you want to keep to prevent them from being garbage collected.
Maybe your code would look something like:
final class MyLoader {
final ArrayList<Target> targets = new ArrayList<>(20);
void load(...) {
for(...) {
Target target = picassoImageTarget(...);
targets.add(target);
picasso.load(...).into(target); // TODO: Maybe remove from list when complete.
}
}
}

Android : load an imageview from a Parsefile

I'm trying to find a ParseObject by " objectId ", then retrieve the image " ImageFile " and then Load it to the imageview, it doesn't work and i'm getting the USER String, can you help me out with this, it works when i use another query like : query.find()
ParseImageView mealImage = (ParseImageView) findViewById(R.id.icon);
ParseQuery<ParseObject> query1 = ParseQuery.getQuery("Annonces");
query1.getInBackground("ux3Af0cwEx", new GetCallback<ParseObject>() {
public void done(ParseObject Annonces, ParseException e) {
photoFile = (ParseFile) Annonces.get("ImageFile");
text1.setText((CharSequence) Annonces.get("USER"));
}
});
mealImage.setParseFile(photoFile);
mealImage.loadInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
}
});
}
The code for displaying image in imageview:
ParseFile image = (ParseFile) userData.getParseFile("user_image");
then call following function.
loadImages( photoFile, mealImage);
private void loadImages(ParseFile thumbnail, final ImageView img) {
if (thumbnail != null) {
thumbnail.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
img.setImageBitmap(bmp);
} else {
}
}
});
} else {
img.setImageResource(R.drawable.menu);
}
}// load image
If you are using Picasso or Glide for image loading and don't want to change the image loading logic, you can extract image url from ParseFile and load it in background.
Like:
ParseFile thumbnail = parseObject.getParseFile("image");
if(thumbnail != null) {
String imageUrl = thumbnail.getUrl();
Picasso.with(mContext).load(imageUrl).into(imageView);
}
No need to load thumbnail ParseFile data separately.

Retrieving image files from parse - android

I'm trying to retrieve images that I have upload from my app:
intent = getIntent();
String id = intent.getStringExtra("id");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Items");
query.getInBackground(id, new GetCallback<ParseObject>()
{
#Override
public void done(ParseObject object, ParseException e)
{
if (e == null)
{
setTitle(object.getString("name"));
textPlatform.setText(object.getString("platform"));
textPrice.setText(String.valueOf(object.getDouble("price")));
textDelivery.setText(String.valueOf(object.getDouble("delivery")));
textLocation.setText(object.getString("location"));
textCondition.setText(object.getString("condition"));
textSeller.setText(object.getString("seller"));
ParseFile applicantResume = (ParseFile) object.get("image");
applicantResume.getDataInBackground(new GetDataCallback()
{
public void done(byte[] data, ParseException e)
{
if (e == null)
{
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
imgItem.setImageBitmap(bmp);
}
else
{
e.printStackTrace();
}
}
});
} else
{
e.printStackTrace();
}
}
});
I can successfully retrieve the other items just not the file (which I know exists and is under the column "image").
Thank You in advanced
This is how i am doing it:
I get the file from parse using getParseFile method:
ParseFile postImage = object.getParseFile(ParseConstants.PARSE_KEY_FILE);
String imageUrl = postImage.getUrl() ;//live url
Uri imageUri = Uri.parse(imageUrl);
and then I use Picasso to display the image:
Picasso.with(context).load(imageUri.toString()).into(mPostImage);
by this you can display the image....
ParseFile image = (ParseFile) userData.getParseFile("user_image");
//call the function
displayImage(image, image_expert);
//and here is the function
private void displayImage(ParseFile thumbnail, final ImageView img) {
if (thumbnail != null) {
thumbnail.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0,
data.length);
if (bmp != null) {
Log.e("parse file ok", " null");
// img.setImageBitmap(Bitmap.createScaledBitmap(bmp,
// (display.getWidth() / 5),
// (display.getWidth() /50), false));
img.setImageBitmap(getRoundedCornerBitmap(bmp, 10));
// img.setPadding(10, 10, 0, 0);
}
} else {
Log.e("paser after downloade", " null");
}
}
});
} else {
Log.e("parse file", " null");
// img.setImageResource(R.drawable.ic_launcher);
img.setPadding(10, 10, 10, 10);
}
}

Read AppFolder file data in android

I want to read the i have written on a file in Appfolder.but i am not able to read that my app is crashes when i try to read that from file.i have created the file in App folder successfully.i am using the below code so please tell if i am doing anything wrong.The error which is coming while i run this code is invalid drive id.i am getting that drive id by this:
result.getDriveFile().getDriveId().encodeToString()
where result is drivefileresult. May I know what is the correct way to achieve my objective?
public class Fifth extends BaseDemoActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
}
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource
Drive.DriveApi.newContents(getGoogleApiClient())
.setResultCallback(contentsCallback);
}
final private ResultCallback<ContentsResult> contentsCallback = new
ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
// Get an output stream for the contents.
OutputStream outputStream = result.getContents().getOutputStream();
// Write the bitmap data from it.
String data="hello world. this is sample";
byte[] bytes = data.getBytes();
// ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
// image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
Log.i("Success", "able to write file contents.");
outputStream.write(bytes);
} catch (IOException e1) {
Log.i("Failier", "Unable to write file contents.");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("appdatafolder.txt")
.setMimeType("text/plain")
.build();
Drive.DriveApi.getAppFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new
ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file in App Folder: "
+ result.getDriveFile().getDriveId());
Log.i("Drioved_ID", result.getDriveFile().getDriveId().encodeToString());
}
};
}
Unfortunately I don't have time to analyze your code but can offer a segment that does essentially the same. Try it.
GoogleApiClient gac = getGoogleApiClient();
DriveFolder dfl = Drive.DriveApi.getAppFolder(gac)
String title = "appdatafolder.txt";
String mime = "text/plain";
byte[] buff = ("hello world. this is sample").getBytes();
createFile(gac, dfl, title, mime, buff);
void createFile(final GoogleApiClient gac, final DriveFolder fldr,
final String name, final String mime, final byte[] buff) {
Thread t = new Thread(new Runnable() {
#Override public void run() {
try {
ContentsResult rslt = Drive.DriveApi.newContents(gac).await();
if (rslt.getStatus().isSuccess()) {
Contents cont = rslt.getContents();
cont.getOutputStream().write(buff);
MetadataChangeSet meta =
new MetadataChangeSet.Builder().setTitle(name).setMimeType(mime).build();
DriveFile df = fldr.createFile(gac, meta, cont).await().getDriveFile();
Log.i("X", ""+ df.getDriveId().encodeToString());
}
} catch (Exception e) {}
}
});
t.start();
}
... and here is how you read it back:
void getFileIs(final GoogleApiClient gac, final DriveId drvId) {
Thread t = new Thread(new Runnable() {
#Override public void run() {
try {
DriveFile df = Drive.DriveApi.getFile(gac, drvId);
ContentsResult rslt = df.openContents(gac, DriveFile.MODE_READ_ONLY, null).await();
if (rslt.getStatus().isSuccess()){
InputStream is = rslt.getContents().getInputStream();
}
} catch (Exception e) {}
}
});
t.start();
}
After days of searching for a good example, I found the Google I/O app on GitHub has excellent utility methods to create, update and read files from Drive. They use the AppFolder as well.

Categories

Resources