Creating A Sign Up Activity using Parse - android

In my application I am creating a sign up activity using parse database and I used the signUpInBackground() but when I run the code on the emulator the parse is giving me a message that says "unauthorised.
Join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog dialog = new ProgressDialog(SignUp.this);
dialog.setTitle("Please Wait");
dialog.setMessage("Please Wait While Signing Up");
dialog.show();
final ParseUser user =new ParseUser();
user.setUsername(Username.getText().toString().trim());
user.setPassword(Password.getText().toString().trim());
user.setEmail(Email.getText().toString().trim());
user.put("firstName", FirstName.getText().toString().trim());
user.put("lastName", LastName.getText().toString().trim());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
dialog.dismiss();
if(e!=null){
Toast.makeText(SignUp.this,e.getMessage(),Toast.LENGTH_LONG).show();
}else {
Intent i = new Intent(SignUp.this,LogIn.class);
startActivity(i);
}
}
});
}
});

When you initialise Parse in your Application class, are you setting your ACL?
Also are your keys correct when you initialise?
Make sure you follow the Quick Start Guide.

Related

How to store data offline and then upload later in the firebase when app has internet access?

I'm creating an app which takes inputs from the user and upload in the firebase. The app works fine if the app has internet access. But I want to make my app to take inputs and store these data offline if app do not have internet access and then upload in the firebase when app get internet access.
I also use 'Disk Persistence'
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
And 'Keeping Data Fresh'
DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
scoresRef.keepSynced(true);
But this isn't working for me. Maybe I not using it correctly.
My code is
AddDataActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityAddDataBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add Data");
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").keepSynced(true);
progressDialog = new ProgressDialog(AddDataActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setTitle("Adding Data");
progressDialog.setMessage("Please Wait ...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
Intent mintent = getIntent();
String activity = mintent.getStringExtra("activity");
if (activity.equals("list")){
String date = mintent.getStringExtra("date");
String name = mintent.getStringExtra("name");
String weight = mintent.getStringExtra("weight");
String rate = mintent.getStringExtra("rate");
binding.editDate.setText(date);
binding.editName.setText(name);
binding.editWeight.setText(weight);
binding.editRate.setText(rate);
}
binding.btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (binding.editDate.getText().toString().length() == 0) {
Toast.makeText(AddDataActivity.this, "Enter Date", Toast.LENGTH_SHORT).show();
} else if (binding.editName.getText().toString().length() == 0) {
Toast.makeText(AddDataActivity.this, "Enter Name", Toast.LENGTH_SHORT).show();
} else if (binding.editWeight.getText().toString().length() == 0) {
Toast.makeText(AddDataActivity.this, "Enter Weight", Toast.LENGTH_SHORT).show();
} else {
if (notValidDateFormat(binding.editDate.getText().toString(), "yyyy-MM-dd")
|| notValidDateFormat(binding.editDate.getText().toString(), "yyyy/MM/dd")
|| notValidDateFormat(binding.editDate.getText().toString(), "yyyy.MM.dd")){
progressDialog.show();
DataModel data = new DataModel();
int weight = Integer.parseInt(binding.editWeight.getText().toString());
int rate = Integer.parseInt(binding.editRate.getText().toString());
data.setDate(binding.editDate.getText().toString());
data.setName(binding.editName.getText().toString());
data.setWeight(weight);
data.setRate(rate);
data.setAddedBy(FirebaseAuth.getInstance().getUid());
if (!activity.equals("list")) {
data.setAddedTime(new Date().getTime());
data.setSell(true);
String dataId = database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").push().getKey();
data.setDataId(dataId);
database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").child(dataId).setValue(data)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressDialog.dismiss();
Toast.makeText(AddDataActivity.this, "Data Added!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AddDataActivity.this, ItemListActivity.class);
startActivity(intent);
finish();
}
});
} else{
database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").child(mintent.getStringExtra("id")).child("modifiedTime").setValue(new Date().getTime());
database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").child(mintent.getStringExtra("id")).child("date").setValue(binding.editDate.getText().toString());
database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").child(mintent.getStringExtra("id")).child("name").setValue(binding.editName.getText().toString());
database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").child(mintent.getStringExtra("id")).child("weight").setValue(weight);
database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").child(mintent.getStringExtra("id")).child("rate").setValue(rate)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressDialog.dismiss();
Toast.makeText(AddDataActivity.this, "Data Modified!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AddDataActivity.this, ItemListActivity.class);
startActivity(intent);
finish();
}
});
}
} else {
Toast.makeText(AddDataActivity.this, "Invalid Date Format! ",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
For Disk Persistence,I create new java class named same as project name
public class PhoNote extends Application {
#Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
}
Thanks!!
Firebase doesn't treat the lack of an internet connection as an error condition when writing to the database. Instead, it keeps the data in memory in that situation (and also on disk if you enabled disk persistence) and synchronizes it to the server when the connection is reestablished.
When you attach a completion listener or a success listener to the write operation, that only fires once the operation is committed or rejected on the server. There are cases where this may be important, but in most cases you actually don't need
This means that in most cases you don't need a completion listener, or even a progress dialog, on write operation to Firebase. Instead you should treat them as if they're local, instantaneous and are completed by the time the setValue() call has executed.
So:
database.getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("data_added_by_user").child(dataId).setValue(data);
Toast.makeText(AddDataActivity.this, "Data Added!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AddDataActivity.this, ItemListActivity.class);
startActivity(intent);
finish();

Login failed condition not working properly

I have an app in which user authentication is done sending a request and if response is successful the app navigated to next activity.If username password is correct it navigates but if it is incorrect the dialog box pops up and does not close and in my logs I get
java.io.IOException: HTTP/1.1 401 The username or password you entered is incorrect.
I have handled it in my code that if response is not successful display a toast message Login failed and dismiss dialog box.if I enter incorrect credentials it is not showing it.That part of the code is unreachable I checked using breakpoint.
My code:
buttonlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
}
else
{
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Logging in..Please wait");
progressDialog.setIndeterminate(true);
progressDialog.show();
new Thread(new Runnable()
{
public void run()
{
try
{
restApi = new RallyRestApi(new URI("https://rally1.rallydev.com"),etemail.getText().toString(),etpass.getText().toString());
restApi.setApplicationName("BMC-AndroidforRally");
qtestset = new QueryRequest("Users");
qtestset.setLimit(1);
response=restApi.query(qtestset);
if(!response.wasSuccessful())
{
parent.runOnUiThread(new Runnable() {
#Override
public void run()
{
Toast.makeText(getApplicationContext(),"Login Failed..incorrect Username/Password",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
else
{
progressDialog.dismiss();
//Toast.makeText(getApplicationContext(),"Login Successful.....Logged in as :"+etemail.getText().toString(),Toast.LENGTH_LONG).show();
Intent mainintent = new Intent(MainActivity.this,FirstPage.class);
mainintent.putExtra("username",etemail.getText().toString());
mainintent.putExtra("password",etpass.getText().toString());
startActivity(mainintent);
}
}
catch (URISyntaxException | IOException e)
{
e.printStackTrace();
}
}
}).start();
}
}
});
Also i have created a new thread for faster execution.
In this concepts no need to implement runnable thread.
Remove Thread in OnClickListener it will work correctly.Because of thread only its showing old message(still that running). Best remove thread in OnClickListener or stop thread when condition going to false statement.

Can not login through Facebook app in Android

I am creating a Facebook login method for my Android app. I am using my custom login button. This works fine when Facebook app is not installed and I have to manually login through the interface that appears after touching login button. The problem I am facing is, this method does not work properly when Facebook app is installed. In this case, when I touch login button, it starts that black and white circular loader with caption "Loading" and that loader continues forever. No login takes place. How do I go about solving it? Following is the code implemented.
Inside onCreate method
callbackManager=CallbackManager.Factory.create();
loginButton= (LoginButton)findViewById(R.id.login_button);
btnFBLogin= (TextView) findViewById(R.id.btnFBLogin);
btnFBLogin.setSelected(true);
btnFBLogin.startAnimation(animationButtonFadeIn);
btnFBLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
loginButton.performClick();
loginButton.setPressed(true);
loginButton.invalidate();
loginButton.registerCallback(callbackManager, mCallBack);
loginButton.setPressed(false);
loginButton.invalidate();
}
});
Inside Remaining Methods
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progressDialog.dismiss();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
btnFBLogin.setVisibility(View.GONE);
user = new User();
facebook_id = object.getString("id").toString();
user.uniqueID = facebook_id;
full_name = object.getString("name").toString();
user.name = full_name;
try{
email = object.getString("email").toString();
}catch (Exception e){
email = "email_not_provided";
}finally {
user.email = email;
}
PrefUtils.setCurrentUser(user, LoginActivity.this);
userRecord(facebook_id, full_name, email, "fb", null);
}catch (Exception e){
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
}
};
That means you have not entered your key hash properly.
See this issue : Android facebook login not working with installed Facebook app

Using android generated LoginActivity with Parse.com

I am attempting to use the android built in login view and parse together.
code
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
ParseUser newUser = new ParseUser();
newUser.setEmail(mEmail);
newUser.setPassword(mPassword);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Success!
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
// Oops!
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage().toUpperCase())
.setTitle("Oops!")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
return true;
}
When I run it, I type in my email / password and the application fails.
Have look at this code:
public class LoginActivity extends PlanndActivity
{
public EditText emailField;
public EditText passwordField;
public Button loginButton;
public View.OnClickListener loginButtonListener;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
PushService.setDefaultPushCallback(getApplicationContext(), PlanndActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground(
new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!= null)
Log.e(Constants.TAG, "ERROR adding callback", e);
}
}
);
emailField = (EditText) findViewById(R.id.email_login);
passwordField = (EditText) findViewById(R.id.password_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.setEnabled(false);
String email = ((EditText) findViewById(R.id.email_login)).getText().toString().trim();
String password = ((EditText) findViewById(R.id.password_login)).getText().toString().trim();
ParseUser.logInInBackground(email, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if(parseUser != null)
{
// User is valid and is now logged in
Log.i(Constants.TAG, "Successful login for user " + parseUser.getUsername());
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
PushService.subscribe(getApplicationContext(), "user_" + ParseUser.getCurrentUser().getObjectId(), PlanndActivity.class);
}
else
{
loginButton.setEnabled(true);
Log.i(Constants.TAG, "Unsuccessful login for user");
// sign up failed and the problems
// needs to go and do the sign up activity
}
}
});
}
});
((Button)findViewById(R.id.register_button)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
}
});
((Button)findViewById(R.id.fake_login)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
emailField.setText("rberidon#gmail.com");
passwordField.setText("test");
}
});
}
}
Source: plannd
Try implement this with animation of view like use inline progress bar when user clicks sign in, switch the content and progress bar depending on your logic!
The problem is that your are executing signUpInBackground() inside AsyncTask.doInBackground(). doInBackground is already using a background thread. Just use newUser.signUp()

Android: dialogbox according to logcat response for webservices

I am accessing .net web services through my Android Application. If the user is successfully registered then log cat will show 1 as the response. If not it will show 0 and If some field is missing then it will show -1 as response. so is it possible to show a dialog box according to the log cat response?
If response is 1 then "successfully registered"
If response is 0 then "Try Again"
How can we do this?
Log.v("TAG", String.valueOf(resultsRequestSOAP)); with this I am getting the response in logcat
Help is always appreciated....Thanks!
In this piece of code,I want to add the required code to show the dialog box.
Button signin = (Button) findViewById(R.id.regsubmitbtn);
signin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(0);
t = new Thread() {
public void run() {
register();
try {
Thread.sleep(5000);
removeDialog(0);
// I want to show the dialog box like registered successfully after removing this dialog//
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
});
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0: {
dialog = new ProgressDialog(this);
dialog.setMessage("Registering...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
}
return null;
}
Write a method that will create dialogs according to a parameter. Then you just have to call this method with a right parameter to create a right dialog depending on the server's response.

Categories

Resources