I have to integrate twitter in my own android application.
I have run the app and the login page is displayed and if I enter the correct login detail it has to write the status page.
I have written the some code. The click on the submit button pops the toast message that review has been posted but when I check the twitter wall that message isn't there. What's wrong in my code? Please check it and how can I resolve this problem?
I have following code:
public class TestPost extends Activity {
private TwitterApp mTwitter;
private CheckBox mTwitterBtn;
private String username = "";
String review;
private boolean postToTwitter = false;
private static final String twitter_consumer_key = "xxx";
private static final String twitter_secret_key = "xxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
Button postBtn = (Button) findViewById(R.id.button1);
final EditText reviewEdit = (EditText) findViewById(R.id.revieew);
postBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String review = reviewEdit.getText().toString();
if (review.equals("")) return;
postReview(review);
if (postToTwitter) postToTwitter(review);
}
});
mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
mTwitter.setListener(mTwLoginDialogListener);
mTwitterBtn = (CheckBox) findViewById(R.id.twitterCheck);
mTwitterBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mTwitter.hasAccessToken()) {
postToTwitter = mTwitterBtn.isChecked();
} else {
mTwitterBtn.setChecked(false);
mTwitter.authorize();
}
}
});
if (mTwitter.hasAccessToken()) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
mTwitterBtn.setText(" Twitter (" + username + ")");
}
}
private void postReview(String review) {
//post to server
Toast.makeText(this, "Review posted", Toast.LENGTH_SHORT).show();
}
private void postToTwitter(final String review) {
new Thread() {
#Override
public void run() {
int what = 0;
try {
mTwitter.updateStatus(review);
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (msg.what == 0) ? "Posted to Twitter" : "Post to Twitter failed";
//String text = "Ve a Good Day";
Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
}
};
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
#Override
public void onComplete(String value) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
mTwitterBtn.setText(" Twitter (" + username + ")");
mTwitterBtn.setChecked(true);
postToTwitter = true;
Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
}
#Override
public void onError(String value) {
mTwitterBtn.setChecked(false);
Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
}
Related
i made an app using java language, Retrofit2 and REST API for server side. in me API class i have login and register parameters like
public interface ApiInterface {
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email, #Field("password") String password, Callback<LoginResult> cb);
public static class LoginResult
{
public int status;
public String user_api_hash;
}
#GET("/registration_status")
void registrationStatus(#Query("lang") String lang, Callback<RegistrationStatusResult> cb);
public static class RegistrationStatusResult
{
public int status;
}
#GET("/get_user_data")
void getMyAccountData(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, Callback<GetMyAccountDataResult> cb);
public static class GetMyAccountDataResult
{
public String email, expiration_date, plan;
public int days_left, devices_limit;
}
my login class is working properly i can login and register any time. when logged in i receive api_kay then it's saved and use in all the app for requests DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); my loginActivity looks like :
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "EditObjectActivity";
#Bind(R.id.username)
EditText username;
#Bind(R.id.password)
EditText password;
#Bind(R.id.signin)
Button signin;
#Bind(R.id.register)
Button pwreset;
private String UrlPrefix;
private String customServerAddress="https://voila_voila_mon_url.com/";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork == null) {
Intent intent = new Intent(LoginActivity.this, NoInternetActivity.class);
startActivity(intent);
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
progressDialog = new ProgressDialog(this);
signin = (Button) findViewById(R.id.signin);
pwreset = (Button) findViewById(R.id.register);
password = findViewById(R.id.password);
username = findViewById(R.id.username);
String ip = getResources().getString(R.string.ip);
String httpsOn = getResources().getString(R.string.https_on);
String server_base = customServerAddress;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
if (ip.isEmpty()) {
enableRegistration();
}
else {
API.getApiInterface(LoginActivity.this).registrationStatus("en", new Callback<ApiInterface.RegistrationStatusResult>()
{
#Override
public void success(ApiInterface.RegistrationStatusResult result, Response response)
{
if (result.status == 1) {
enableRegistration();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, "failure: retrofitError" + retrofitError.getMessage());
Toast.makeText(LoginActivity.this, getString(R.string.errorHappened), Toast.LENGTH_SHORT).show();
}
});
}
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(customServerAddress != null) {
String server_base = customServerAddress;
server_base = UrlPrefix + server_base;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
}
API.getApiInterface(LoginActivity.this).login(username.getText().toString(), password.getText().toString(), new Callback<ApiInterface.LoginResult>()
{
#Override
public void success(ApiInterface.LoginResult loginResult, Response response)
{ // progress dialogue
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Connexion au serveur"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
//end progress dialogue
DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash);
Log.d("LoginActivity", "api_key: " + loginResult.user_api_hash);
if(customServerAddress == null)
{
String url = "https://voila_voila_mon_url.com/";
DataSaver.getInstance(LoginActivity.this).save("server_base", url);
DataSaver.getInstance(LoginActivity.this).save("server", url + "api/");
}
Intent intent = new Intent(LoginActivity.this, MapActivity.class);
startActivity(intent);
finish();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(LoginActivity.this, getString(R.string.wrongLogin), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
now the thing is i'd look to log out in my mean activity. in my reseachs i have been told that once logged out the api_key in DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); should be null like api_key =null.also when i open the app it show that i am logged. i want to log out.here is my example on my_logout button i did this :
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String log_out = null;
if(DataSaver.getInstance(this).load("api_key") != null){
DataSaver.getInstance(this).load("api_key") == log_out;
finish();
}else{
//Toast.......(Toast with message ->>>>unable to log out).
}
});
This DataSaver.getInstance(this).load("api_key") is used in all the app when requesting for GET method when fetching users datas. the api_key saved in the app allow me to make some requests as said before. but when this is null it's impossible to make requests. i want to destroy the session when logged in by loggin out. if you understand what i say and can help please.
my account activity after logged in
public class MyAccountActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.expandable_list) ExpandableListView expandable_list;
#Bind(R.id.loading_layout) View loading_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
ButterKnife.bind(this);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getMyAccountData((String) DataSaver.getInstance(this).load("api_key"), getResources().getString(R.string.lang), new Callback<ApiInterface.GetMyAccountDataResult>() {
#Override
public void success(ApiInterface.GetMyAccountDataResult dataResult, Response response)
{
MyAccountAdapter adapter = new MyAccountAdapter(MyAccountActivity.this, dataResult);
expandable_list.setAdapter(adapter);
Utils.setGroupClickListenerToNotify(expandable_list, adapter);
loading_layout.setVisibility(View.GONE);
expandable_list.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MyAccountActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
i did this but it's not enough to log out #Syed Ibrahim
like this
but not working this is juste to stay connected not to log out
if (DataSaver.getInstance(this).load("api_key") == null)
{
startActivity(new Intent(MapActivity.this, LoginActivity.class));
finish();
return;
}
what i need is to set this api_key null whatever the app is running or not.
I am currently using Email/Password in sign in and sign up .
I want to add Phone number in sign up (with vérification of otp )
and will be sign in with (Email or Phone (EditText)+ password (EditText)).
the problem is if i can do it ? or not ?
if i can there is my code what will i add
This activity of Sign in :
private TextInputLayout mEmail,mPass;
private Button mLogin,mCallRegister ;
private ProgressDialog mProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener fbAutLis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_login);
//progress bar
mProgress =new ProgressDialog(this);
String titleId="Signing in...";
mProgress.setTitle(titleId);
mProgress.setMessage("Please Wait...");
mAuth= FirebaseAuth.getInstance();
fbAutLis= new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
mProgress.dismiss();
Intent inte =new Intent(ClientLoginAct.this,ClientMapAct.class);
startActivity(inte);
finish();
return ;
}
}
};
mEmail =(TextInputLayout)findViewById(R.id.email);
mPass =(TextInputLayout)findViewById(R.id.pass);
mLogin =(Button)findViewById(R.id.login);
mCallRegister =(Button) findViewById(R.id.callRegister);
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if( !validateEmail()|!validatePassword()){
return;
}
mProgress.show();
final String email=mEmail.getEditText().getText().toString();
final String password=mPass.getEditText().getText().toString();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(ClientLoginAct.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
mProgress.dismiss();
Snackbar.make(v, "Email or Password incorrect", Snackbar.LENGTH_LONG).show();
//Toast.makeText(ClientLoginAct.this,"Email or Password incorrect ",Toast.LENGTH_SHORT).show();
}
}
});
}
});
mCallRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ClientLoginAct.this,ClientRegAct.class);
startActivity(intent);
}
});
}
private Boolean validateEmail() {
String val = mEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
mEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
mEmail.setError("Invalid email address");
return false;
} else {
mEmail.setError(null);
mEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = mPass.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
//"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=.*[a-zA-Z0-9])" + //any letter
"(?=\\S+$)" + //no white spaces
".{6,}" + //at least 6 characters
"$";
if (val.isEmpty()) {
mPass.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
mPass.setError("Password is too weak(at least 6 characters & no white spaces)");
return false;
} else {
mPass.setError(null);
mPass.setErrorEnabled(false);
return true;
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(fbAutLis);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(fbAutLis);
}
}
This is activity of Sign up :
private TextInputLayout mEmail,mPass;
private Button mRegister,mCallLogin;
private ProgressDialog mProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener fbAutLis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_reg);
//progress bar
mProgress =new ProgressDialog(this);
String titleId="Signing up...";
mProgress.setTitle(titleId);
mProgress.setMessage("Please Wait...");
mAuth= FirebaseAuth.getInstance();
fbAutLis= new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
mProgress.dismiss();
Intent inte =new Intent(ClientRegAct.this,ClientMapAct.class);
startActivity(inte);
finish();
return ;
}
}
};
mEmail =(TextInputLayout)findViewById(R.id.email);
mPass =(TextInputLayout)findViewById(R.id.pass);
// mPhone =(TextInputLayout)findViewById(R.id.phone);
mRegister =(Button)findViewById(R.id.register);
mCallLogin =(Button) findViewById(R.id.callLogin);
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if( !validateEmail()|!validatePassword()){
return;
}
mProgress.show();
final String email=mEmail.getEditText().getText().toString();
final String password=mPass.getEditText().getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(ClientRegAct.this,new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task){
if (!task.isSuccessful()){
mProgress.dismiss();
Snackbar.make(v, "This email is already exist", Snackbar.LENGTH_LONG).show();
//Toast.makeText(ClientRegAct.this,"This email is already exist",Toast.LENGTH_SHORT).show();
}else{
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Clients").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
mCallLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
private Boolean validateEmail() {
String val = mEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
mEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
mEmail.setError("Invalid email address");
return false;
} else {
mEmail.setError(null);
mEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = mPass.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
//"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=.*[a-zA-Z0-9])" + //any letter
"(?=\\S+$)" + //no white spaces
".{6,}" + //at least 6 characters
"$";
if (val.isEmpty()) {
mPass.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
mPass.setError("Password is too weak(at least 6 characters & no white spaces)");
return false;
} else {
mPass.setError(null);
mPass.setErrorEnabled(false);
return true;
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(fbAutLis);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(fbAutLis);
}
}
This code of activity Vérify_Otp but i dont know how to link with other activity :
String verificationCodeBySystem;
private Button mVerify;
private EditText mCode;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_verify);
mVerify = findViewById(R.id.verify_btn);
mCode = findViewById(R.id.verification_code_entered_by_user);
mProgressBar = findViewById(R.id.progress_bar);
String phoneNo = getIntent().getStringExtra("phoneNo");
sendVerificationCodeToUser(phoneNo);
mVerify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = mCode.getText().toString();
if (code.isEmpty() || code.length() < 6) {
mCode.setError("Wrong OTP...");
mCode.requestFocus();
return;
}
mProgressBar.setVisibility(View.VISIBLE);
verifycode(code);
}
});
}
private void sendVerificationCodeToUser(String phoneNo) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+213" + phoneNo, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
TaskExecutors.MAIN_THREAD, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s ;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if(code!=null){
mProgressBar.setVisibility(View.VISIBLE);
verifycode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(OtpVerify.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
};
private void verifycode (String codeByUser){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem,codeByUser);
signInTheUserByCredentials(credential);
}
private void signInTheUserByCredentials(PhoneAuthCredential credential){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(OtpVerify.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(OtpVerify.this, "Your Account has been created successfully!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(OtpVerify.this,ClientMapAct.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(intent);
}else{
Toast.makeText(OtpVerify.this,task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
So please what i change to got what i ask in first lines ...
I have an app that send sms templates with firebase user login.
I want to save sms logs for each user on firbase database so I will be able to see what messages each user sent. I have no idea how to make it probably ..
my code
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private ProgressBar spinner;
EditText EMAIL, PASSWORD;
Button SIGNIN;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
EMAIL = (EditText) findViewById(R.id.email);
PASSWORD = (EditText) findViewById(R.id.password);
SIGNIN = (Button) findViewById(R.id.login);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.setVisibility(View.GONE);
SIGNIN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((TextUtils.isEmpty(EMAIL.getText().toString())) && (TextUtils.isEmpty(PASSWORD.getText().toString()))) {
Toast.makeText(getApplicationContext(), "make sure that you enter full ogin info ", Toast.LENGTH_SHORT).show();
}else if (!isEmailValid(EMAIL.getText().toString())){
Toast.makeText(getApplicationContext(), "enter a valid mail", Toast.LENGTH_SHORT).show();
} else {
SignIn(EMAIL.getText().toString(), PASSWORD.getText().toString());
}
}
});
SIGNIN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pass = PASSWORD.getText().toString();
if(TextUtils.isEmpty(pass)) {
PASSWORD.setError("kindly enter password ");
return;
}
if ((TextUtils.isEmpty(EMAIL.getText().toString())) && (TextUtils.isEmpty(PASSWORD.getText().toString()))) {
Toast.makeText(getApplicationContext(), "wrong info", Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
} else {
spinner.setVisibility(View.VISIBLE);
SignIn(EMAIL.getText().toString(), PASSWORD.getText().toString());
}
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
};
mAuth.addAuthStateListener(mAuthListener);
}
private void SignIn(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
finish();
Toast.makeText(getApplicationContext(), "login done",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
Toast.makeText(getApplicationContext(), "Error username",
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
}
});
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
}
sms.java
public class Harsh extends AppCompatActivity {
RadioButton lo, hi, mid;
String sense;
Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.harsh_layout);
lo = (RadioButton) findViewById(R.id.lo_btn);
hi = (RadioButton) findViewById(R.id.hi_btn);
mid = (RadioButton) findViewById(R.id.mid_btn);
submit = (Button) findViewById(R.id.submitButton);
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
final String num = prefs.getString("nameKey", "0");
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lo.isChecked()) {
sendSMS( num, " message one");
} else if (hi.isChecked()) {
sendSMS( num, " message 2");
// for example save this message for current logged user
} else if (mid.isChecked()) {
sendSMS( num, " message 3");
}
Toast.makeText(getApplicationContext(), "Command Sent", Toast.LENGTH_LONG).show(); // print the value of selected super star
}
});
}
public void sendSMS(String phoneNo, String msg) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, msg, null, null);
Toast.makeText(getApplicationContext(), "Command Sent",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
}
after alot of researches i found that set and get class and i modify my code as below
public class Post {
private String message;
private String number;
private String user;
private String date;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
then in activity that i need to Post data to firbase database i add that simple code
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference posts = database.getReference("Messages:");
//this code for keep posts even app offline until the app online again
posts.keepSynced(true);
Post post = new Post();
post.setMessage("Messsage");
post.setUser(name);
post.setNumber(num);
post.setDate(s);
posts.push().setValue(post);
I keep getting this error while attempting to sign up on an emulator and on my device.
Authentication failed.com.google.firebase.FirebaseException: An internal error has occured. [ OPERATION_NOT_ALLOWED ]
I have enabled email under authentication providers in the console as was suggested in a different question but I'm still having trouble. Any ideas?
I have the play services dependencies set to higher than 9.0.0 and both the emulator and my test device satisfy this requirement
Here's my SignupActivity code
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "SignupActivity" ;
private Button btnSignUp,btnLinkToLogIn;
private ProgressBar progressBar;
private FirebaseAuth auth;
private EditText signupInputEmail, signupInputPassword;
private TextInputLayout signupInputLayoutEmail, signupInputLayoutPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
auth = FirebaseAuth.getInstance();
signupInputLayoutEmail = (TextInputLayout) findViewById(R.id.signup_input_layout_email);
signupInputLayoutPassword = (TextInputLayout) findViewById(R.id.signup_input_layout_password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkToLogIn = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
});
btnLinkToLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
/**
* Validating form
*/
private void submitForm() {
String email = signupInputEmail.getText().toString().trim();
String password = signupInputPassword.getText().toString().trim();
if(!checkEmail()) {
return;
}
if(!checkPassword()) {
return;
}
signupInputLayoutEmail.setErrorEnabled(false);
signupInputLayoutPassword.setErrorEnabled(false);
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG,"createUserWithEmail:onComplete:" + task.isSuccessful());
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
Log.d(TAG,"Authentication failed." + task.getException());
} else {
startActivity(new Intent(SignupActivity.this, UserActivity.class));
finish();
}
}
});
Toast.makeText(getApplicationContext(), "You are successfully Registered !!", Toast.LENGTH_SHORT).show();
}
private boolean checkEmail() {
String email = signupInputEmail.getText().toString().trim();
if (email.isEmpty() || !isEmailValid(email)) {
signupInputLayoutEmail.setErrorEnabled(true);
signupInputLayoutEmail.setError(getString(R.string.err_msg_email));
signupInputEmail.setError(getString(R.string.err_msg_required));
requestFocus(signupInputEmail);
return false;
}
signupInputLayoutEmail.setErrorEnabled(false);
return true;
}
private boolean checkPassword() {
String password = signupInputPassword.getText().toString().trim();
if (password.isEmpty() || !isPasswordValid(password)) {
signupInputLayoutPassword.setError(getString(R.string.err_msg_password));
signupInputPassword.setError(getString(R.string.err_msg_required));
requestFocus(signupInputPassword);
return false;
}
signupInputLayoutPassword.setErrorEnabled(false);
return true;
}
private static boolean isEmailValid(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private static boolean isPasswordValid(String password){
return (password.length() >= 6);
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
}
Please check the if authentication method enabled in the console Firebase or not.
If you did not enabled Google authentication, you will got the same exception, just without [OPERATION_NOT_ALLOWED].
For more information you can check solution in the forum post https://groups.google.com/forum/#!topic/firebase-talk/JTaIlD-tNxw
Please check the Firebase Auth documentation for more information.
I have same problem. I got the solution in above forum post.
Hi in the below code when clicking the report button not going to login activity even though it's not happening anything.
In login activity first of all I am checking the login username and password using session object.
if the username and password working fine and then want to move to next activity.
Can any one help me from this issue.
Mainactivity.java
report1=(TextView)findViewById(R.id.report1);
report=(ImageView)findViewById(R.id.report);
report1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
In the below when I am putting comment for session then it's moving but after entering the username and password it was showing logcat Admin user found but not going to next activity.it was staying in same activity itself.
update Login
public class Login extends Activity {
ImageButton login;
private static final Pattern USERNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PASSWORD_PATTERN = Pattern
.compile("[a-zA-Z0-9+_.]{4,16}");
EditText usname,pword,ustype;
TextView tv,tv1;
Boolean isInternetPresent = false;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String queryString;
String data="";
int i;
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
SessionManager session;
private ProgressDialog progressDialog;
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
// session = new SessionManager(getApplicationContext());
// session.checkLogin();
// final HashMap<String, String> user = session.getUserDetails();
login = (ImageButton)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
ustype= (EditText)findViewById(R.id.usertype);
tv = (TextView)findViewById(R.id.tv);
tv1 = (TextView)findViewById(R.id.tv1);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
cd = new ConnectionDetector(getApplicationContext());
mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
String username = usname.getText().toString();
String password = pword.getText().toString();
// String name = user.get(SessionManager.KEY_USERNAME);
if (username.equals("")) {
Toast.makeText(Login.this, "ENTER USERNAME",
Toast.LENGTH_LONG).show();
}
if (password.equals("")) {
Toast.makeText(Login.this, "ENTER PASSWORD",
Toast.LENGTH_LONG).show();
}
else if (!CheckUsername(username) && !CheckPassword(password)){
Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
Toast.LENGTH_LONG).show();
}
else{
queryString = "username=" + username + "&password="
+ password ;
String usertype = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.print(usertype);
if(usertype.equalsIgnoreCase("Admin user Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Login.this, "Login Sucess",
Toast.LENGTH_LONG).show();
}
});
Intent in=new Intent(Login.this, Reports.class);
startActivity(in);
}
else if(usertype.equalsIgnoreCase("No User Found")){
runOnUiThread(new Runnable() {
public void run() {
tv1.setText("InValid UserName and Password");
}
});
}
}
}
});
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Do not use the application's context, use the context the view currently be presented.
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(v.getContext(), Login.class);
startActivity(i);
}
});