Unable to encode an unsaved parse file, working with ParseUser - android

I'm trying to make a signUp activity with a profile picture, but i get an error stating: Unable to encode an unsaved parse file. I have the same code in another Class and it doesn't have any problems.
I think that the problem could be using ParseUser instead of ParseObject. Please help me, here's my code.
public class SignUpActivityStep3 extends ActionBarActivity {
public static final String YOUR_APPLICATION_ID = "kuN8ihs88AYhRR1jIWT9psCGUXxSOveJPqVVsBnq";
public static final String YOUR_CLIENT_KEY = "vC4eA9CqulpgkxJ7sTPtoPSANkMxFeiFlYXwODYK";
byte[] Image;
ParseFile photo = null;
String User, Pass, Email, Description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signupstep3);
Parse.initialize(this, YOUR_APPLICATION_ID, YOUR_CLIENT_KEY);
EditText Desc = (EditText) findViewById(R.id.txtDesc);
Button Finish = (Button) findViewById(R.id.btnFinish);
Intent intent = getIntent();
User = intent.getStringExtra("User");
Pass = intent.getStringExtra("Pass");
Email = intent.getStringExtra("Email");
Image = intent.getByteArrayExtra("Image");
photo = new ParseFile("userpicture.png", Image);
photo.saveInBackground();
savetoParse();
}
private void savetoParse() {
ParseUser user = new ParseUser();
user.setUsername(User.toString());
user.setPassword(Pass.toString());
user.put("Profile", photo);
user.setEmail(Email.toString());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(getApplicationContext(),
"Saving user failed." + e.getMessage(), Toast.LENGTH_SHORT).show();
if (e.getCode() == 202) {
Toast.makeText(
getApplicationContext(),
"Username already taken. \n Please choose another username.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "User Saved",
Toast.LENGTH_SHORT).show();
/*Do some things here if you want to.*/
}
}
});
}
}

You need to wait for the Parse file to finish saving before attempting to sign up the user. You need to do something like this:
photo = new ParseFile("userpicture.png", Image);
file.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// If successful add file to user and signUpInBackground
if(null == e)
savetoParse();
}
});

I was having this same issue but then I figured that for the image to be saved we need to login first, so either login with a user and password using ParseUser.LogInBackGround method or use Parse.enableLocalDatastore(this); to enable automatic user creation and logging in.

Related

Multiple requests when signing up with file on parse

I am trying to build an android application using parse to store user data.
In the user table, I am storing username password, status, and a profile picture.
I am trying to create a signup page, and to do that I am using file.saveInBackground to upload the image file and then user.signUpInBackground to sign up the user.
It is working fine, but every time a user sign's up it makes multiple requests (around 30).
Is there any particular reason why this is happening?
private void addUser(String username, String role, String password) {
final ParseFile file = new ParseFile(photoFile);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
User user = new User();
user.setUsername(username);
user.setRole(role);
user.setPassword(password);
user.setProfileImage(file);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(getContext(), "Error while signing up!", Toast.LENGTH_SHORT).show();
}
goMainActivity();
}
});
}
}
});
}

Login using Json with shared Preferences

Login using JSON with shared Preferences When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView3);
usr_number = findViewById(R.id.usr_pass);
go = findViewById(R.id.button);
signup = findViewById(R.id.signup_signup);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getjsondata();
String hhh = usr_number.getText().toString();
url = "http://readnow.flatdeal4u.com/Api/Register.aspx?mobile=" + hhh + "&choice=2";
//Toast.makeText(MainActivity.this, ""+hhh, Toast.LENGTH_SHORT).show();
if (usr_number.getText().toString().isEmpty()) {
usr_number.setError("Enter Phone Number");
Toast.makeText(MainActivity.this, "Enter Details", Toast.LENGTH_SHORT).show();
} else {
if (usr_number.getText().toString().equals("" + hhh)) {
Intent intent = new Intent(MainActivity.this, select_your_exams.class);
startActivity(intent);
pref = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
pref.getString("mobilenumber", hhh);
pref.getString("nameofuser", "");
}
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Signup.class);
startActivity(intent);
}
});
}
Here are my JSON method codes:
public void get JSON data) {
final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jobj = new JSONObject(response);
JSONArray array = jobj.getJSONArray("userInfos");
//Toast.makeText(MainActivity.this, "data found"+array, Toast.LENGTH_LONG).show();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
final Phn_modal mo = new Phn_modal();
final String mobile = obj.getString("mobileNumber");
final String name = obj.getString("fullName");
final String email = obj.getString("emailId");
Toast.makeText(MainActivity.this, "Welcome You-" + name, Toast.LENGTH_LONG).show();
mo.setMobile(mobile);
mo.setName(name);
mo.setEmailId(email);
mo.getMobile(mobile);
mo.getMobile(name);
editor.putString("mobilenumber", mobile);
editor.putString("nameofuser", name);
editor.apply();
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
i think your question is , you login first time, and next time you again visit application that time directly go to the activity withouth asking login,
then you can try this.
public void storeString(SharedPreferences sharedPreferences, String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
above function is used to store the specific value in our shared prefrence, with given key.
Now when we hint the login button that time if login is success then store the login success value in our prefrence.
this one is usefull for again visit in your application
storeString(mPreferences, "Login_flag", "true");
-> Now, when we again visit application check the our prefrence is true or false.
if our prefrence is true then user already login, not required to login again
Check like this,
if(mPreferences.getString(PreferenceList.LOGIN_FLAG, "false").equals("true")){
//if alredy login then access this
}else{
//if not login then access this
}
if you want to create a login session in your app then you should create an preference class in your project and save data in that class and match the data where you want to use follow this answer to maintain the login session in your app:- Preventing users to login again after closing the app

What is proper way to verify payload without user login on Android?

I have implemented In-App billing for subscribing to a service. Everything works great but I am at the point where I need to make it secure. Various suggestions that I have ran across suggest to use the account id of the logged in user via the Plus API. Yet how would I get this if the user doesn't log in using their gmail account? My idea was to generate a token created from the user account id and sku combined. Then check with my server to verify the purchase. Is there any way to get the account id of the user? I want to make it possible to use the app across multiple devices with a single purchase. If the user isn't logging in using any social api, is there a way to verify the user across multiple devices?
After many trials and errors and researching, I found a solution. So for anyone else who may have the same need/issue:
First, add this to your build.gradle file:
compile 'com.google.android.gms:play-services-auth:10.2.0'
Then, in the activity that needs to get the users account id add this:
public class MainActivity extends AppCompatActivity{
private static final int REQUEST_CODE_EMAIL = 1;
TextView email, mAcctId;
Button getID;
String accountName;
String TAG = "test";
private static final int REQ_SIGN_IN_REQUIRED = 55664;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = (TextView) findViewById(R.id.email);
mAcctId = (TextView)findViewById(R.id.accountID);
//Shows a popup allowing user to select email if more than one exists
try {
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
new String[] { GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE }, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_EMAIL);
} catch (ActivityNotFoundException e) {
// TODO
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_EMAIL && resultCode == RESULT_OK) {
accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
email.setText(accountName);
//Call async task to get accountID for selected email
new RetrieveAccountID().execute(accountName);
}
}
private class RetrieveAccountID extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String accountName = params[0];
String token = null;
try {
token = GoogleAuthUtil.getAccountId(getApplicationContext(), accountName);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (UserRecoverableAuthException e) {
startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
} catch (GoogleAuthException e) {
Log.e(TAG, e.getMessage());
}
return token;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
((TextView) findViewById(R.id.accountID)).setText("AccountID: " + s);
}
}
}
Running that will give you the users selected email in one TextView and the accountID for that email in another TextView. Which can now be used to create a token/key for the app unique to the users email. This can also be used to verify token/key when user uses app on a different device.

How to get Current User Information using parse.com android

I am working on android for parse.com. I have successfully logged in and signed up with my credentials and data is also uploading in my parse.com tables. Code snippet for login is given below:
loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Retrieve the text entered from the EditText
usernametxt = username.getText().toString();
passwordtxt = password.getText().toString();
// Send data to Parse.com for verification
ParseUser.logInInBackground(usernametxt, passwordtxt,
new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// If user exist and authenticated, send user to Welcome.class
Intent intent = new Intent(
LoginSignupActivity.this,
Welcome.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),
"Successfully Logged in",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(
getApplicationContext(),
"No such user exist, please signup",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Now i need to get the information of current user, kindly mention me the method or changing which i have to do to get the information of current user.
Thanks in advance!
Calling things like user.getObjectId(); or user.getString("username"); is how you get information from the ParseObject.
loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Retrieve the text entered from the EditText
usernametxt = username.getText().toString();
passwordtxt = password.getText().toString();
// Send data to Parse.com for verification
ParseUser.logInInBackground(usernametxt, passwordtxt,
new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// If user exist and authenticated, send user to Welcome.class
String username = user.getString("username");
String userId = user.getObjectId();
Intent intent = new Intent(
LoginSignupActivity.this,
Welcome.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),
"Successfully Logged in",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(
getApplicationContext(),
"No such user exist, please signup",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Once the user is authenticated, open up new activity and you can access current user by using the static method getCurrentUser.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// do stuff with the user
} else {
// show the signup or login screen
}
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.getUsername();
newTable.put("user_name",currentUser );
This is how you can get a user information in your other table (newTable).
Let me know if it helps. :)
With this I got the user info.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null){
String email = currentUser.getEmail();
String username = currentUser.getUsername();
String objectID = currentUser.getObjectId();
} else {
Toast.makeText(getApplicationContext(), "the user does not exist!",Toast.LENGTH_SHORT).show();
}
ParseUser currentUser = ParseUser.getCurrentUser();
String currentUserString = String.valueOf(currentUser.getUsername());
newTable.put("user_name",currentUserString);
For some reason I'm not sure about, you need to cast currentUser to String.

Posting a photo on user's facebook wall

Below is my code and I integrated the facebook in my app. I am trying to make the user to be able to post an image on his wall after logging in. But I have been failing to make it for three days. Have seen few posts like this but I don't get any data(just it results in empty data data[]). I am even facing trouble with maintaining sessions too. Can some one please post working code or at least some sources where I can post image on facebook wall? Hope my below code is clear and my explanation is clear on what I have tried with the code below.
Activity's onCreate():-
public class FacebookActivity extends BaseActivity {
private static String APP_ID = "1303786178";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_screen);
btnFbLogin = (Button) findViewById(R.id.fbloginbtn);
btnFbLogout = (Button) findViewById(R.id.fblogoutbtn);
btnPostToWall = (Button) findViewById(R.id.fbpostbtn);
msget = (EditText)findViewById(R.id.fbmsget);
mAsyncRunner = new AsyncFacebookRunner(facebook);
mHandler = new Handler();
String passedpath = getIntent().getStringExtra("imagepath").toString();
imageuri = Uri.parse(passedpath);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
btnFbLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
logoutFromFacebook();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//postToWall(imageuri);
getAlbumId();
}
});
}
Posting on Wall includes two functions in my code one is getAlbumId() and the other is posttowall() which will be called from getAlbumId():-
public void getAlbumId()
{
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
//String wallAlbumID = null;
mAsyncRunner.request("me/albums", new BaseRequestListener(){
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
try{
Log.d("response in album"," "+response);
JSONObject json = Util.parseJson(response);
JSONArray albums = json.getJSONArray("data");
for (int i =0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
if (album.getString("type").equalsIgnoreCase("wall")) {
final String wallAlbumID = album.getString("id");
globalalbid = wallAlbumID;
Log.d("JSON", wallAlbumID);
break;
}
}
dialog.dismiss();
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "id: " + globalalbid, Toast.LENGTH_LONG).show();
if(globalalbid != "")
postToWall(imageuri, globalalbid);
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
});
}
function to post on wall:
public void postToWall(Uri locuri, String wallid) {
if (facebook.isSessionValid()) {
Util.showAlert(this, "Warning", "You must first log in.");
} else {
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
// post on user's wall.
Uri photoUri = locuri;
if (photoUri != null) {
Bundle params = new Bundle();
try {
params.putByteArray("photo",
Utility.scaleImage(getApplicationContext(), photoUri));
} catch (IOException e) {
e.printStackTrace();
}
String imagecaption = msget.getText().toString();
if(imagecaption != "")
params.putString("caption", imagecaption);
mAsyncRunner.request(wallid+"/photos", params, "POST", new PhotoUploadListener(), null);
} else {
Toast.makeText(getApplicationContext(),
"Error from the pic", Toast.LENGTH_SHORT)
.show();
}
}
}
}
I always get album id empty. Is there anything wrong in the way that I try to get album id. Because I have seen on some posts those who try to access album id and then posting the image on album. They seem to be keeping wall as common findout in the album name. If it is so, some new ones contain timeline photos name, then how can we findout the album id. Please suggest.
Note: I want the image to be visible on to the wall not to only album.
Instead of uploading the photo to the user's album, post the image to /me/feed instead. Make sure you are asking the user for the publish_stream permission. This will upload the photo straight to the user's wall instead of going to an album.

Categories

Resources