I have done the task on "Inviting users to the app using facebook" in android, used the below codes as a result if i send the invitation, the invite message rarely delivers after many hours and or else not getting delivered, do anybody know the solution for this?
final ImageView facebook1 = (ImageView) findViewById(R.id.facebook1);
facebook1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Facebook mFacebook = new Facebook( APP_ID );
Bundle params = new Bundle();
params.putString("message", "Prova ");
mFacebook.dialog(Singlemenuitem.this, "apprequests", params, new DialogListener() {
public void onComplete(Bundle values) {
Toast toast = Toast.makeText(getApplicationContext(), "Done",
Toast.LENGTH_SHORT);
toast.show();
}
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(),
Toast.LENGTH_SHORT).show();
}
public void onCancel() {
Toast toast = Toast.makeText(getApplicationContext(), "App request cancelled",
Toast.LENGTH_SHORT);
toast.show();
}
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
} });
Related
I am building a bus booking app and in it I am using the Razorpay API. Right now the intent in below code is being run when the payment is not successful as well.Right now if I just click the done button and go back, the intent is called. I only want to call the intent when the payment is successful. How do I run the intent only when the payment is successfully complete?
buttonDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (SeatAL.size()==24) {
Toast.makeText(Book_Bus.this, "Select a minimum of 1 seat to pay", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(Book_Bus.this, "Redirecting...", Toast.LENGTH_SHORT).show();
int amount=count*Integer.valueOf(price)*100;
count=0;
RazorPayAPI(amount);
String FinalSeats="";
for(int i=0;i<SeatsAL.size();i++){
FinalSeats+=SeatsAL.get(i);
if(i!=SeatsAL.size()-1){
FinalSeats+=",";
}
}
if(flag) {
Intent intent = new Intent(Book_Bus.this, Ticket.class);
intent.putExtra("BusID", busRVModel.getBusID());
intent.putExtra("Source", busRVModel.getSrc());
intent.putExtra("Destination", busRVModel.getDest());
intent.putExtra("Timings", busRVModel.getTimings());
intent.putExtra("Seats", FinalSeats);
startActivity(intent);
finish();
}else{
Toast.makeText(Book_Bus.this, "Try again", Toast.LENGTH_SHORT).show();
}
}
}
private void RazorPayAPI(int amount) {
Checkout checkout=new Checkout();
checkout.setKeyID("<keyID>");
JSONObject object=new JSONObject();
try {
object.put("name","<name>");
object.put("Description","Bus Ticket");
object.put("theme.color",bg_yellow);
object.put("currency","INR");
object.put("amount",amount);
object.put("prefill.contact","<phone>");
object.put("prefill.email","<email>");
checkout.open(Book_Bus.this,object);
flag=true;
} catch (JSONException e) {
e.printStackTrace();
flag=false;
}
}
});
}
#Override
public void onPaymentSuccess(String s) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Payment ID");
Toast.makeText(this, "Payment Successful", Toast.LENGTH_SHORT).show();
}
#Override
public void onPaymentError(int i, String s) {
Toast.makeText(getApplicationContext(), "Payment Cancelled", Toast.LENGTH_SHORT).show();
}
}
I solved the above problem by writing that block of code in the onPaymentSucess method and declaring the busRVModel outside the oncreate method and initialising the busRVModel inside the onCreate method
buttonDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (SeatAL.size()==24) {
Toast.makeText(Book_Bus.this, "Select a minimum of 1 seat to pay", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(Book_Bus.this, "Redirecting...", Toast.LENGTH_SHORT).show();
int amount=count*Integer.valueOf(price)*100;
count=0;
razorPayAPI(amount);
}
}
private void razorPayAPI(int amount) {
Checkout checkout=new Checkout();
checkout.setKeyID("<keyID>");
JSONObject object=new JSONObject();
try {
object.put("name","<name>");
object.put("Description","Bus Ticket");
object.put("theme.color",bg_yellow);
object.put("currency","INR");
object.put("amount",amount);
object.put("prefill.contact","<phone>");
object.put("prefill.email","<email>");
checkout.open(Book_Bus.this,object);
flag=true;
} catch (JSONException e) {
e.printStackTrace();
flag=false;
}
}
});
}
#Override
public void onPaymentSuccess(String s) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Payment ID");
Toast.makeText(this, "Payment Successful", Toast.LENGTH_SHORT).show();
String FinalSeats="";
for(int i=0;i<SeatsAL.size();i++){
FinalSeats+=SeatsAL.get(i);
if(i!=SeatsAL.size()-1){
FinalSeats+=",";
}
}
Intent intent = new Intent(Book_Bus.this, Ticket.class);
intent.putExtra("BusID", busRVModel.getBusID());
intent.putExtra("Source", busRVModel.getSrc());
intent.putExtra("Destination", busRVModel.getDest());
intent.putExtra("Timings", busRVModel.getTimings());
intent.putExtra("Seats", FinalSeats);
startActivity(intent);
finish();
}
#Override
public void onPaymentError(int i, String s) {
Toast.makeText(getApplicationContext(), "Payment Cancelled", Toast.LENGTH_SHORT).show();
}
}
NOTE: In my case when I wrote the above block of code I got the error that busRVModel is not available, so be sure to declare the busRVModel object outside the oncreate method and initialise it inside the oncreate method.
I want to Toast a message based on the state of TTS.
For this I used OnUtteranceProgressListener() . But I didn't get the result.
How can I achieve this task ?
Code given below is used to initialize TTS class.
textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
//Check if initialisation is successful
if(i==TextToSpeech.SUCCESS)
{
//set Language
int result=textToSpeech.setLanguage(Locale.ENGLISH);
//Check if language is set successfully or not.
if(result==TextToSpeech.LANG_NOT_SUPPORTED||result==TextToSpeech.LANG_MISSING_DATA)
{
Toast.makeText(MainActivity.this, "Language not supported", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onDone(String s) {
Toast.makeText(MainActivity.this,"Done",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(String s) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
else{
Toast.makeText(MainActivity.this, "Initialisation failed", Toast.LENGTH_SHORT).show();
}
}
});
Code given below is used to trigger the event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speak();
}
});
speak() function definition:
private void speak() {
String text="Good Morning";
float pitch=(float)seekBarPitch.getProgress()/50;
float speed=(float)seekBarSpeed.getProgress()/50;
textToSpeech.setPitch(pitch);
textToSpeech.setSpeechRate(speed);
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,"UTTERANCE_ID");
}
Toast message do not work in background thread.
So we must run it on UI Thread by using runOnUIThread();
I'm trying to follow the tutorial from Firebase to allow users to login using their phone number. I've watched a tutorial video. All my code looks correct, but when I try it on my test device I receive a null pointer error.
at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source)
at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(Unknown Source)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin.CheckPhoneNumber(PhoneLogin.java:92)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin.access$000(PhoneLogin.java:29)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin$1.onClick(PhoneLogin.java:52)
My code for the phone login is as follows:
private EditText et_check_phone_number;
private EditText et_verify_code;
private Button btn_phone;
private Button btn_verify;
private String getPhoneNumber, getVerifactionCode;
private String mVerificationId = "";
private FirebaseAuth mAuth;
private FirebaseDatabase db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mcallBacks;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private ProgressDialog mloading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_login);
mAuth = FirebaseAuth.getInstance();
initVariables();
btn_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPhoneNumber();
}
});
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyPhoneNumber();
}
});
}
private void initVariables() {
et_check_phone_number = findViewById(R.id.et_phonenumber);
et_verify_code = findViewById(R.id.etvarifaction);
btn_phone = findViewById(R.id.btn_phone_login);
btn_verify = findViewById(R.id.btn_phone_verify);
mloading = new ProgressDialog(this);
}
private void CheckPhoneNumber() {
getPhoneNumber = et_check_phone_number.getText().toString();
if (TextUtils.isEmpty(getPhoneNumber))
{
Toast.makeText(this, "Phone Number Field Cant Be Empty...", Toast.LENGTH_SHORT).show();
} else{
mloading.setTitle("Checking Your Phone Number");
mloading.setMessage("It Gonna Take A Second...");
mloading.setCanceledOnTouchOutside(false);
mloading.setIcon(R.mipmap.ic_launcher);
mloading.show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
getPhoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mcallBacks);
}
}
mcallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PhoneLogin.this, "Wrong Or Invalid Phone Number...", Toast.LENGTH_SHORT).show();
btn_phone.setVisibility(View.VISIBLE);
et_check_phone_number.setVisibility(View.VISIBLE);
et_verify_code.setVisibility(View.INVISIBLE);
btn_verify.setVisibility(View.INVISIBLE);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getBaseContext(), "Invalid Request " + e.toString(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getBaseContext(), "The SMS quota for the project has been exceeded " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
Toast.makeText(PhoneLogin.this, "Code Sent Please Check Your SMS...", Toast.LENGTH_SHORT).show();
btn_phone.setVisibility(View.INVISIBLE);
et_check_phone_number.setVisibility(View.INVISIBLE);
et_verify_code.setVisibility(View.VISIBLE);
btn_verify.setVisibility(View.VISIBLE);
}
};
}
private void VerifyPhoneNumber() {
getVerifactionCode = et_verify_code.getText().toString();
if (TextUtils.isEmpty(getVerifactionCode)){
Toast.makeText(this, "Please Enter The Code Sent To Your SMS...", Toast.LENGTH_SHORT).show();
}else{
mloading.setTitle("Checking Your Verification code ");
mloading.setMessage("Ill Be Back In A Jiffy...");
mloading.setCanceledOnTouchOutside(false);
mloading.setIcon(R.mipmap.ic_launcher);
mloading.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, getVerifactionCode);
signInWithPhoneAuthCredential(credential);
}
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
mloading.dismiss();
Toast.makeText(PhoneLogin.this, "Login Successful...", Toast.LENGTH_SHORT).show();
Intent phoneloginIntent =new Intent (getBaseContext(),Home_Screen.class);
phoneloginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(phoneloginIntent);
finish();
} else {
String mesage = task.getException().toString();
Toast.makeText(PhoneLogin.this, "Error: " + mesage, Toast.LENGTH_SHORT).show();
}
}
});
}
The "+44" I added trying to see if I was entering the wrong phone number. I tried it by adding the +44 manually into the edit text of the app first and that gave the same error.
Edit
So I've removed the line inside the Auth provider that asked if the number was larger than 9 digits as it wasn't working. Also I ran a log to see if it capturing the phone number correctly.
Log.i("Verify_Phone_Number",getPhoneNumber);
2019-07-16 14:15:30.585 32055-32055/studios.p9p.chatomatic.chat_o_matic I/Verify_Phone_Number: +447******100 and it returns correctly
Edit 2
So on further testing if I click btn_phone before entering the phone number it works correctly, but if I simply add the phone number to the edit test first then press thebtn_phone it crashes with the above message in logcat.
As per Firebase Docs you have to pass the Number with Country Code :
E.g.
phone number = +919090909090
See Following Picture :
As you can see even testing number needs country code with them.
When your app crashes it means Firebase PhoneAuthProvider.getInstance().verifyPhoneNumber() not getting the number with country code.
You can try this following code before passing to if condition :
if (et_check_phone_number.getText().toString().startsWith("+44"){
getPhoneNumber = et_check_phone_number.getText().toString();
}else{
getPhoneNumber = "+44"+et_check_phone_number.getText().toString();
}
Above Code will check whether user put prefix of your country code or not.
Ok so the way i solved this problem was to move the mcallbacks to the on create section of code. as shown below
setContentView(R.layout.activity_phone__login);
mAuth = FirebaseAuth.getInstance();
InitVariables();
AddPhoneNumberButtons();
mcallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getBaseContext(), "Wrong Or Invalid Phone Number...", Toast.LENGTH_SHORT).show();
AddPhoneNumberButtons();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getBaseContext(), "Invalid Request " + e.toString(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getBaseContext(), "The SMS quota for the project has been exceeded " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
verificationid = verificationId;
mresendtoken = token;
Toast.makeText(getBaseContext(), "Code Sent Please Check Your SMS...", Toast.LENGTH_SHORT).show();
AddVerifyButtons();
}
};
I have the following code, It is for a login application which redirects to a website. I cannot find specific help online to disable the login_btn for a certain time period and then enable again with the attempts_remaining back to the initial 3. Any help much appreciated
public class MainActivity extends AppCompatActivity {
EditText username;
EditText password;
TextView attempt_count;
Button login_btn;
int attempts_remaining = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.editText_user);
password = (EditText) findViewById(R.id.editText_password);
attempt_count = (TextView) findViewById(R.id.textView_attempts_count);
login_btn = (Button) findViewById(R.id.button);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (username.getText().toString().equals("admin") && password.getText().toString().equals("password")) {
Toast.makeText(getApplicationContext(), "Redirecting ...", Toast.LENGTH_SHORT).show();
Intent website = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.co.uk"));
startActivity(website);
} else {
Toast.makeText(getApplicationContext(), "Wrong Username or Password", Toast.LENGTH_SHORT).show();
attempt_count.setVisibility(View.VISIBLE);
attempt_count.setTextColor(Color.RED);
attempts_remaining--;
attempt_count.setText(Integer.toString(attempts_remaining));
if (attempts_remaining == 0) {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Please Wait", Toast.LENGTH_SHORT).show();
login_btn.setEnabled(false);
}
}
}
});
}
}
You can add a simple piece of code below your disable code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
login_btn.setEnabled(true);
attempts_remaining = 3;
}
},10000);
based on this SO question, you could try the following:
if (attempts_remaining == 0) {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Please Wait", Toast.LENGTH_SHORT).show();
login_btn.setEnabled(false);
login_btn.postDelayed(new Runnable() {
#Override
public void run() {
login_btn.setEnabled(true);
attempts_remaining = 3;
}
}, 10 * 1000); // 10 seconds
}
You could try this,
what you need is a handler,
From Android's developers page https://developer.android.com/reference/android/os/Handler.html
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own
change your onClick method to this
#Override
public void onClick(View v) {
if (username.getText().toString().equals("admin") && password.getText().toString().equals("password")) {
Toast.makeText(getApplicationContext(), "Redirecting ...", Toast.LENGTH_SHORT).show();
Intent website = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.co.uk"));
startActivity(website);
} else {
Toast.makeText(getApplicationContext(), "Wrong Username or Password", Toast.LENGTH_SHORT).show();
attempt_count.setVisibility(View.VISIBLE);
attempt_count.setTextColor(Color.RED);
attempts_remaining--;
attempt_count.setText(Integer.toString(attempts_remaining));
if (attempts_remaining == 0) {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Please Wait", Toast.LENGTH_SHORT).show();
login_btn.setEnabled(false);
new Handler().postDelayed(new Runnable()
{
#Override //depending on if you are inheriting from a super class
public void run()
{
login_btn.setEnabled(true);
}
}, 10000 // time in milliseconds, 10000ms = 10s
);
}
}
}
});
}
}
You might have to make some adjustments to fit you code, let me know how that went.
I have this code.. The only working here is the Login... I want to achieve the Publish to wall or feed dialog.. I have here the code for the wall post but It still not working.. Any help will be appreciated... I followed this link for my Login
[a link] http://www.kpbird.com/2013/03/android-login-using-facebook-sdk-30.html
I am trying to embed the post status in this Login..
public class FacebookActivity extends FragmentActivity {
private Button publishButton;
private String TAG = "FacebookActivity";
private TextView lblEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_activity);
lblEmail = (TextView) findViewById(R.id.lblEmail);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
authButton.setOnErrorListener(new OnErrorListener(){
#Override
public void onError(FacebookException error) {
Log.i(TAG, "Error " + error.getMessage());
}
// TODO Auto-generated method stub
});
// set permission list, Don't forget to add email
authButton.setReadPermissions(Arrays.asList("basic_info","email"));
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.i(TAG,"Access Token"+ session.getAccessToken());
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,Response response) {
if (user != null) {
Log.i(TAG,"User ID "+ user.getId());
Log.i(TAG,"Email "+ user.asMap().get("email"));
lblEmail.setText(user.asMap().get("email").toString());
}
}
});
publishButton.setVisibility(View.VISIBLE);
}
else if (state.isClosed()) {
publishButton.setVisibility(View.INVISIBLE);
}
}
});
publishButton = (Button) findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishFeedDialog();
}
});
}
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getActivity().getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
protected ContextWrapper getActivity() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}