How to upload multiple images on Parse? - android

I need help with Parse Android API and images uploading/updating. User in my app can create event that has 1 or more images related to that event. So, this images are stored as array object that have parse files.
User can edit images that he added for that event. So, user might want to delete image or to add a new image. So, there I have problem, how I can edit array to delete specific image.
My idea was to download all images on the phone, and when user add/delete image update it locally and then upload again all images to Parse and update that array of images, but it seems that is not working properly, since I get only one image uploaded.
How I can solve this problem, any idea is appreciated.
for (int i = 0; i < ImagesSingleton.getInstance().getBytesList().size(); i++) {
String fileName = FileHelper.getFileName(getActivity(), ImagesSingleton.getInstance().getUrisList().get(i), "image");
byte[] b = ImagesSingleton.getInstance().getBytesList().get(i);
final ParseFile imgFile = new ParseFile(fileName, ImagesSingleton.getInstance().getBytesList().get(i));
imgFile.saveInBackground(new SaveCallback() {
#Override
public void done(com.parse.ParseException e) {
if (e == null) {
listOfFiles.add(imgFile);
if (listOfFiles.size() == ImagesSingleton.getInstance().getUrisList().size()) {
offer.put(ParseConstants.OFFER_PICTURES, listOfFiles);
offer.saveInBackground(new SaveCallback() {
#Override
public void done(com.parse.ParseException e) {
if (e == null) {
mProgressDialog.dismiss();
Toast.makeText(getActivity(), "Sucess saving", Toast.LENGTH_SHORT).show();
ImagesSingleton.getInstance().reset();
transferToRadar();
} else {
mProgressDialog.dismiss();
Toast.makeText(getActivity(), getResources().getString(R.string.error) + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
});
}

I think it is quite clear in documentation how to delete an element(s) from an Array column in Parse. You simply have to send the list of the files you want to be removed from the Array like this:
offer.removeAll(ParseConstants.OFFER_PICTURES, listOfFilesToRemove);
offer.saveInBackground();

Related

java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 error

Can anyone help me? I debugg app many more time but I can not found what exact issue going in my android app. In my android app, My cases are describe below.
cases 1: Insert data into database It is perfectly worked fine.
case 2: That data display in to recycler view ok. It will display fine.
It will work with only single user login. When another user will login in to app and try to add data then It will get this exception. Or when I will refresh first user login view at that time it have same exception.
Or when I remove second user from database then I refresh first login user view at that time it will work perfectly . Now what to do? Please any one help me out of this issue. I attached screen shot of my error log please refer it.
Retrive data.java
private void makeJsonArrayRequest(final String email) {
String cancel_req_tag = "list";
JsonArrayRequest req = new JsonArrayRequest(URL_FOR_SELECT,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("OnResponse", response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
ListMobileModal objMobileModal = new ListMobileModal();
if (jsonObject.getString("email").equals(email)) {
objMobileModal.email = jsonObject.getString("email");
if (!jsonObject.isNull("name")) {
objMobileModal.lname = jsonObject.getString("name"); //here we can fetch webservice field
}
if (!jsonObject.isNull("title")) {
objMobileModal.title = jsonObject.getString("title"); //here we can fetch webservice field
}
if (!jsonObject.isNull("eimage")) {
objMobileModal.eimage = jsonObject.getString("eimage");
}
if (!jsonObject.isNull("eid")) {
objMobileModal.eid = jsonObject.getString("eid");
}
if (!jsonObject.isNull("ename")) {
objMobileModal.ename = jsonObject.getString("ename");
}
if (!jsonObject.isNull("edescription")) {
objMobileModal.edescription = jsonObject.getString("edescription");
}
if (!jsonObject.isNull("evlocation")) {
objMobileModal.elocation = jsonObject.getString("elocation");
}
lstListMobile.add(i, objMobileModal);
}
}
objMobileAdapter = new ListMobileAdapter(SavedPhoneBottomActivity.this, lstListMobile);
objEmptyRecyclerViewAdapter = new EmptyRecyclerViewAdapter("No selected list!");
if (lstListMobile == null || lstListMobile.size() == 0) {
rvDisplay.setAdapter(objEmptyRecyclerViewAdapter);
rvDisplay.setVisibility(View.VISIBLE);
} else {
rvDisplay.setAdapter(objMobileAdapter);
rvDisplay.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SavedPhoneBottomActivity.this,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("VolleyError", "Error: " + error.getMessage());
Toast.makeText(SavedPhoneBottomActivity.this,
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(req, cancel_req_tag);
}
List exception error
try to replace lstListMobile.add(i, objMobileModal); with lstListMobile.add(objMobileModal);
when if (jsonObject.getString("email").equals(email)) condition fails 0 index is not added for that user.
you will get ArrayIndexOutOfBound error on lstListMobile.add(1, objMobileModal); if 0 index is not present
You're inserting lstListMobile.add(i, objMobileModal); maybe you can just add lstListMobile.add(objMobileModal);? Probably whats happening is that when i==0 is does not pass the test if (jsonObject.getString("email").equals(email)) {. So it does not add and the size remains 0. When i==1 it breaks when inserting.
Please check first array is not null
if (response.length > 0) {
// do something
}
else{
//empty array
}

Android - Parse - deleteInBackground, record not being deleted

I'm using Parse with Android in order to sync my data.
I'm trying to delete an object which is stored in the Parse cloud via
The callback returns and there's no exception, the Logcat message is "deleted".
But the object still exists in table when I check the Parse Data.
tastToEdit is an object from Task class (configured locally in my app).
ParseObject parse_task = new ParseObject("Task");
parse_task.put("Description",tastToEdit.getDescription());
parse_task.put("DueDate",tastToEdit.getDueDate());
parse_task.put("Priority",tastToEdit.getPriority().ordinal());
int com_state = (tastToEdit.getCompleted()) ? 1 : 0;
parse_task.put("IsCompleted",com_state);
parse_task.put("Location",0);
parse_task.put("Category",tastToEdit.getTask_catg().ordinal());
parse_task.put("Status", tastToEdit.getTask_sts().ordinal());
//parse_task.deleteInBackground();
parse_task.deleteInBackground(new DeleteCallback() {
public void done(ParseException e) {
if (e == null) {
Log.d("msg","deleted");
} else {
Log.d("msg", "not deleted");
e.printStackTrace();
}
}
});
What might be causing the callback to return as "deleted" but the object still remains?
Thanks in advance.
You are creating a new ParseObject and you try to delete it after but you don't provide an ObjectID.
A better way to do this will be to first do a ParseQuery for that task you are looking and the in the completion delete it.

Parse File Query Not Working

I am attempting to get a file from Parse through a query. Parse is very vague on how to get files from the cloud, but I have managed to create a basic query to attempt to get a file
ParseQuery query = ParseUser.getQuery();
query.getInBackground(objects.get(i).getObjectId(), new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
ParseFile fileObject = (ParseFile) object.get("picture");
fileObject.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
ImageView image = (ImageView) findViewById(R.id.profilePicture);
image.setImageBitmap(bmp);
} else {
Toast.makeText(getApplicationContext(), "Image Not Found", Toast.LENGTH_SHORT).show();
}
}
});
}
});
The code above gives me a NullPointerException on the line:
ParseFile fileObject = (ParseFile) object.get("picture");
Need help getting the file through this method. Or is there an easier way to get a file from the Parse Cloud? All help is appreciated.
In my experience, a null pointer exception on line containing the following:
ParseFile fileObject = (ParseFile) object.get("picture");
tells me that object is null during the attempt to access the get() method. This tells me that your query is either malformed or has no matching objects on the server, more likely the second.
I don't have any information regarding the data structure of your Parse cloud, so let me give you an example instead.
If you have a regular old user, and his Parse ObjectId is xyz123ab and he has a picture file under the key/column profilePicture. You have a User containing a ParseFile containing picture data, or [User [File [PictureData]]].
Here's how you would retrieve the above in code:
String objectIdOfUser = "xyz123ab";
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.getInBackground(objectIdOfUser, new GetCallback<ParseUser>() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
ParseFile picture = parseUser.getParseFile("profilePicture");
if (picture == null) {
// no parseFile in column "profilePicture" in this user.
return; // there will be no data to retrieve
}
picture.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
if (data.length == 0) {
// data found, but nothing to extract. bad image or upload?
return; // failing out
}
// SUCCESS
// convert data and display in an imageview
} else {
// ParseFile contained no data. data not added to ParseFile?
}
}
});
} else {
// no users had this objectId
}
}
});
Change ParseUser to ParseObject in the following if you aren't using a ParseUser. Don't forget to change the string "ObjectName" to your object.
// ... etc
ParseQuery<ParseObject> query = ParseObject.getQuery("ObjectName");
query.getInBackground(objectIdOfObject, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
ParseFile picture = object.getParseFile("profilePicture");
// etc...
Also, be certain that your data is loaded into the server properly. This can be tricky to determine on the web-client for Parse, unfortunately. Uploading an image properly is similar to this but in reverse, and an answer for another day.
Please review your code to get an objectId as shown here:
objects.get(i).getObjectId()
to determine if you are indeed accessing the objectId you thought you were, perhaps with a log or toast or debug breakpoint. That could be were everything starts to break down.
Your code looks fine, you simply need to check if the current row has a file reference in it's picture column. If the column is empty then you will obviously get a null reference when reading it out as a ParseFile.

Error while saving ParseRelation

I'm having some issues while trying to save a ParseRelation. I've tried creating the ParseUser first (I thought that was the problem) but it continued to happen.
Situation: I have 2 tables, one is User (Parse.com default) and a second one called Teams. Inside the latter, there's a ParseRelation to User. After saveInBackground is triggered I check the DataBrowser and I can see that the team was in fact created but the players added not in the relation.
My code:
ParseObject newTeam = new ParseObject(Constants.TABLE_TEAMS);
newTeam.put(Constants.ATTRIB_TEAM_NAME, nombreEquipo);
// FIXME ParseRelation not being saved
ParseRelation<ParseUser> playersRelation = newTeam
.getRelation(Constants.ATTRIB_TEAM_PLAYERS);
// Get Users from ListView
for (int i = 0; i < invitedPlayers.size(); i++) {
ParseUser pu = (ParseUser) viewPlayerList.getItemAtPosition(i);
playersRelation.add(pu);
Log.d(LOG_TAG,
"Player being added: "
+ pu.get(Constants.ATTRIB_USER_NAME));
}
newTeam.put(Constants.ATTRIB_TEAM_PLAYERS, playersRelation);
newTeam.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// setResult(RESULT_OK);
Toast.makeText(getApplicationContext(), "Team created.",
Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(),
"ParseException: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Any ideas ? I've read the docs and also checked a few samples but can't seem to find out what's the problem.
Edit: Using Parse.com v1.5.0 and Android 4.4.2

How to save image with the previous objectid

I have two activities and two ParseObjects respectively. In one activity I'm saving 3 strings and in another activity I'm saving Image to the ImageView. Its getting successfully saved to Parse.com but with different ObjectIds. I want the Image to be saved in other table. and then get the image based on the mobile number. I have searched the documentation referred in the Parse.com but not able to resolve this.
final ParseObject dataObject = new ParseObject("DataObject");
dataObject.put("name", name);
dataObject.put("mobilenumber", mobileNumber);
dataObject.put("occupation", occup);
dataObject.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
// Success!
String objectId = dataObject.getObjectId();
} else {
// Failure!
}
}
});
Toast.makeText(getBaseContext(), "Data successfully saved "+ objectId, Toast.LENGTH_LONG).show();
This is the first activity. In the next activity I'm saving an image. I want the ObjectId but its says NULL everytime. Pls Help.
You can send the mobile number with intent to your next activity like :
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(LoadImg.this, "",
"Saving Image...", true);
try {
image = readInFile(path);
}
catch(Exception e) {
e.printStackTrace();
}
ParseFile file = new ParseFile("picturePath.png", image);
file.saveInBackground();
ParseObject imgupload = new ParseObject("Image");
imgupload.put("ImageFile", file);
imgupload.put("Mobilenumber", mob);
// Create the class and the columns
and in the activity you can fetch the mobile number from the intent like :
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Image");
mobileNumber = mbltxt.getText().toString();
query.whereEqualTo("Mobilenumber", mobileNumber);
ob = query.find();
How about this.
You can send the three strings as a bundle from the first activity to the next(second) activity using intent.putExtras(Bundle) or Intent.putExtra(String, String) and then in the second activity, get the extras and then save the strings and the image together into a ParseObject. This will also reduce the number of API requests to Parse.

Categories

Resources