null object value when query user data from parse.com database
final ParseUser user= ParseUser.getCurrentUser();
if (user!=null){
Email.setText(user.getEmail());
ParseFile file=user.getParseFile("ProfilePicture");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
Bitmap pic= BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Bitmap croped=getCroppedBitmap(pic);
Bitmap scaled=Bitmap.createScaledBitmap(croped, 70, 70, true);
ProfilePicture.setImageBitmap(scaled);
}
});
}else {
Toast.makeText(this,"Please Login",Toast.LENGTH_SHORT).show();
}
my app is showing only bitmap image where obtained email value is null on using log.d("Email:",user.getEmail()+"")
is there any problem in code.
Sounds like either the user did not enter an email, or the code to save the email to parse is incorrect. Check on Parse to see if the value exists in your database for that user. If it does maybe set a breakpoint at the line and inspect the user object you receive.
Related
I am trying to retrieve a new column called "address" I created in Parse User in my android app. But it returns me nullPointerException error and returns me nothing although I filled the address in the table.
This link only shows the way to store your custom field in the user table but I need to retrieve what I stored there.
This is my code:
ParseUser pUser = ParseUser.getCurrentUser();
userAddress.setText(pUser.getString("address").toString());
I tried get("address") as well but still it returns me nothing. Is there something I'm missing here?
Alright, I found the answer on my own. It turns out that Parse caches the ParseUser.getCurrentUser() object locally and the reason I wasn't able to get the data from server was because I changed the data on server and the client cache wasn't updated.
I was able to fix this by fetching the ParseUser object from the server:
ParseUser.getCurrentUser().fetchInBackground();
and then after the object is retrieved from the server I was able to get the address field on my client.
You need to call it using a Query, then display it in a textView/editText. Try the following:
final ParseQuery<ParseObject> address = ParseQuery.getQuery("//Class Name");
address.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject reqAdd, ParseException e) {
if (address != null) {
Log.d("quizOne", "Got it");
//Retrieve Age
String //CreateNewString = reqAdd.getString("//Column name");
TextView //textView Name = (TextView) findViewById(R.id.//textView ID);
//textViewName.setText(//StringName);
Toast.makeText(getApplicationContext(),
"Successfully Recieved Address",
Toast.LENGTH_LONG).show();
} else {
Log.d("//EnterName", "//Enter Error Message");
Toast.makeText(getApplicationContext(),
"Can't receive address", Toast.LENGTH_LONG)
.show();
}
}
});
Short answer: that user probably just doesn't have an address set.
Long answer: your code snippet will throw exceptions often, and you should expect and handle those, or use tests to avoid throwing them.
Read this page: http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException
Key example/excerpt:
Object obj = null;
obj.toString(); // This statement will throw a NullPointerExcept
So pUser.getString("address") appears correct. But calling .toString() on the result requires you to be try/catching the exception. Maybe do
ParseUser pUser = ParseUser.getCurrentUser();
if (pUser.getString("address") != null) {
userAddress.setText(pUser.getString("address"));
}
BTW, I believe the error is "nullPointerException" fyi! :)
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.
Generate dynamically column with file data type in parse.com using android code
ParseObject tableName = new ParseObject("NewTable");
tableName.put("columnOne", "string"); // string
tableName.put("columnTwo", 12); // integer
tableName.put("Filedata", ); <----------Here must be file data type
tableName.saveInBackground();
To store with file data type ---
Get the data in byte[] form and then create a ParseFile with it.
In this example, we'll just use a string:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("filedata.txt", data);
file.saveInBackground();
Finally, after the save completes, you can associate a ParseFile onto a ParseObject just like any other piece of data:
ParseObject tableName = new ParseObject("NewTable");
tableName.put("columnOne", "string"); // string
tableName.put("columnTwo", 12); // integer
tableName.saveInBackground();
tableName.put("Filedata", file);
tableName.saveInBackground();
Retrieving it back involves calling one of the getData variants on the ParseObject. Here we retrieve the Filedata file off another object:
ParseFile applicantFile = (ParseFile)anotherApplication.get("Filedata");
applicantFile.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
// data has the bytes for the resume
} else {
// something went wrong
}
}
});
This is explained more thoroughly at Android Parse Guide.
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.
I want to use the parse database for developing web app, since data will upload from the desktop PC and retreival of the same will be done in parse mobile application.
Is it possible to use the parse database for website backend ?
Since I want to use same parse database for application and desktop version.
Can anyone please help me, by providing some idea how to achieve that?
Thanks in advance.
Is it possible to use the parse database for website backend ?
YES, it is possible: .NET Guide, REST API
Since I want to use same parse database for application and desktop version.
YES, you can use same database for application and desktop version.
for store data using ANDROID create object like:
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.saveInBackground();
above code is create table in parse.com(database is automatically created when you store data using object.) check dashboard: like below image
for fetch data try this way:
ParseQuery query = new ParseQuery("GameScore");
query.getInBackground("xWMyZ4YEGZ", new GetCallback() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
// object will be your game score
} else {
// something went wrong
}
}
});
same way you can use for WEB Application as well Desktop application (REST API)
for create table User i have to create object like:
ParseObject gameScore = new ParseObject("User");
gameScore.put("First Name", "dhaval");
gameScore.put("Last Name", "Sodha");
gameScore.put("Email", "xyz#gmail.com");
gameScore.put("Phone", "9876543210");
gameScore.put("Address", "xyz");
gameScore.put("City", "ahmedabad");
gameScore.put("Country", "India");
gameScore.saveInBackground();
above Object ll create table with fields(ID ,First Name, Last Name, Email, Phone, Address, City, ... time, created...etc )
EDITED:
get data like (SELECT * FROM USER WHERE CITY = 'AHMEDABAD' and COUNTRY = 'INDIA')
ParseQuery lotsOfWins = new ParseQuery("User");
lotsOfWins.whereEqualTo("city", "Ahmedabad");
ParseQuery fewWins = new ParseQuery("User");
fewWins.whereEqualTo("country", "India");
List<ParseQuery> queries = new ArrayList<ParseQuery>();
queries.add(lotsOfWins);
queries.add(fewWins);
ParseQuery mainQuery = ParseQuery.or(queries);
mainQuery.findInBackground(new FindCallback() {
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " scores");
// HERE SIZE is 0 then 'No Data Found!'
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
Here: public void done(List<ParseObject> scoreList, ParseException e) you get result in object
List<ParseObject>: is list of object return by query.
ParseException: is Exception if occur..
So, scoreList.size() give you Total size of all Object return by Query.
How Fetch data:
String username = scoreList.getString("username");
How Save File: (Whatever MIME type like png,jpg,doc,txt....etc)its works for all
Upload File using Below code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
USERIMAGE.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String UsetPhoto = "user"+System.currentTimeMillis()+"image";
ParseFile file = new ParseFile(UsetPhoto, byteArray);
ParseObject gameScore = new ParseObject("UserDetails");
gameScore.put("userName", "" + userName.getText().toString());
gameScore.put("userPhoto", "" + file);
gameScore.saveInBackground();
retrive file from parse API using above object:
ParseFile applicantResume = (ParseFile)gameScore.get("userPhoto");
applicantResume.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
// data has the bytes for the resume
} else {
// something went wrong
}
}
});
Here you get: public void done(byte[] data, ParseException e)
byte[] : byte[] of file(whatever file type - if you have uploaded png then save that byte as png).
ParseException : is Exception if occur..