Android send me twice the same message - java

I am working on a project for school and trying to send SMS to the user phone. The message is sent twice instead of once. How do I fix that problem?
Here is my code:
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =1 ;
EditText textphone;
String message;
String phoneNo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_e_g_i_s_t_e_r);
textphone=findViewById(R.id.phone);
c = findViewById(R.id.create1);
c.setOnClickListener(this);
c.setEnabled(false);
if(!checkPermission(Manifest.permission.SEND_SMS)){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}else{
c.setEnabled(true);
}
}
public void onClick(View v) {
if (v == c) {
sendmessage();}
now the method:
private void sendmessage() {
if(checkPermission(Manifest.permission.SEND_SMS))
{
message="Hello "+ username2.getText().toString()+",welcome to Chatime. Hope you enjoy from our app.";
phoneNo=textphone.getText().toString();
if(phoneNo.length()==0){
return;
}
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo,null,message,null,null);
Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
public boolean checkPermission(String permission){
int check=ContextCompat.checkSelfPermission(this,permission);
return (check==PackageManager.PERMISSION_GRANTED);
}

Related

Register Layout not showing first time

Whenever i verify phone number with OTP then it should go to Register Layout but it returns to login layout. But when i close the app and run it again then it directly jumps to register layout.
I had check the code several times but not able to find the error.
here is the sample video: https://www.youtube.com/watch?v=elfg7bS3Cig
Here is my code
public class SplashScreenActivity extends AppCompatActivity {
private final static int LOGIN_REQUEST_CODE = 6262; //Any number you want
private List<AuthUI.IdpConfig> providers;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener listener;
private Uri filePath;
private ImageView img_drive_proof;
private final int PICK_IMAGE_REQUEST = 22;
#BindView(R.id.progress_bar)
ProgressBar progress_bar;
FirebaseDatabase database;
DatabaseReference driverInfoRef;
#Override
protected void onStart() {
super.onStart();
delaySplashScreen();
}
private void delaySplashScreen() {
progress_bar.setVisibility(View.VISIBLE);
Completable.timer(3, TimeUnit.SECONDS,
AndroidSchedulers.mainThread())
.subscribe(() ->
//After show Splash Screen, ask login if not login
firebaseAuth.addAuthStateListener(listener)
);
}
#Override
protected void onStop() {
if (firebaseAuth != null && listener != null)
firebaseAuth.addAuthStateListener(listener);
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
init();
}
private void init() {
ButterKnife.bind(this);
database = FirebaseDatabase.getInstance();
driverInfoRef = database.getReference(Common.DRIVER_INFO_REFERENCE);
providers = Arrays.asList(
new AuthUI.IdpConfig.PhoneBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()
);
firebaseAuth = FirebaseAuth.getInstance();
listener = myFirebaseAuth -> {
FirebaseUser user = myFirebaseAuth.getCurrentUser();
if (user != null)
{
//Update Token
FirebaseInstanceId.getInstance()
.getInstanceId()
.addOnFailureListener(e -> Toast.makeText(SplashScreenActivity.this, "", Toast.LENGTH_SHORT).show())
.addOnSuccessListener(instanceIdResult -> {
Log.d("TOKEN",instanceIdResult.getToken());
UserUtils.updateToken(SplashScreenActivity.this, instanceIdResult.getToken());
});
checkUserFromFirebase();
}
else {
showLoginLayout();
}
};
}
private void showLoginLayout() {
AuthMethodPickerLayout authMethodPickerLayout = new AuthMethodPickerLayout
.Builder(R.layout.layout_sign_in)
.setPhoneButtonId(R.id.btn_phone_sign_in)
.setGoogleButtonId(R.id.btn_google_sign_in)
.build();
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAuthMethodPickerLayout(authMethodPickerLayout)
.setIsSmartLockEnabled(false)
.setTheme(R.style.LoginTheme)
.setAvailableProviders(providers)
.build(),LOGIN_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == LOGIN_REQUEST_CODE)
{
IdpResponse response = IdpResponse.fromResultIntent(data);
if(resultCode == RESULT_OK)
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
}
else
{
Toast.makeText(this, response.getError().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
private void checkUserFromFirebase() {
driverInfoRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
DriverInfoModel driverInfoModel = dataSnapshot.getValue(DriverInfoModel.class);
goToHomeActivity(driverInfoModel);
}
else
{
showRegisterLayout();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(SplashScreenActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void showRegisterLayout() {
AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.DialogTheme);
View itemView = LayoutInflater.from(this).inflate(R.layout.layout_register,null);
TextInputEditText edt_first_name = (TextInputEditText)itemView.findViewById(R.id.edt_first_name);
TextInputEditText edt_last_name = (TextInputEditText)itemView.findViewById(R.id.edt_last_name);
TextInputEditText edt_phone = (TextInputEditText)itemView.findViewById(R.id.edt_phone_number);
img_drive_proof = (ImageView)itemView.findViewById(R.id.img_drive_proof);
Button btnUpload = (Button) itemView.findViewById(R.id.btnUpload);
Button btn_continue = (Button)itemView.findViewById(R.id.btn_register);
img_drive_proof.setOnClickListener(v -> SelectImage());
btnUpload.setOnClickListener(v -> uploadImage());
//Set data
if (FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber() != null &&
!TextUtils.isEmpty(FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber()))
edt_phone.setText(FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber());
//Set View
builder.setView(itemView);
AlertDialog dialog = builder.create();
dialog.show();
btn_continue.setOnClickListener(v -> {
if (TextUtils.isEmpty(edt_first_name.getText().toString()))
{
Toast.makeText(this, "Please enter first name", Toast.LENGTH_SHORT).show();
return;
}
else if (TextUtils.isEmpty(edt_last_name.getText().toString()))
{
Toast.makeText(this, "Please enter last name", Toast.LENGTH_SHORT).show();
return;
}
else if (TextUtils.isEmpty(edt_phone.getText().toString()))
{
Toast.makeText(this, "Please enter phone number", Toast.LENGTH_SHORT).show();
return;
}
else
{
DriverInfoModel model = new DriverInfoModel();
model.setFirstName(edt_first_name.getText().toString());
model.setLastName(edt_last_name.getText().toString());
model.setPhoneNumber(edt_phone.getText().toString());
model.setRating(0.0);
driverInfoRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(model)
.addOnFailureListener(e ->
{
dialog.dismiss();
Toast.makeText(SplashScreenActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
)
.addOnSuccessListener(aVoid -> {
Toast.makeText(this, "Register Successfully ", Toast.LENGTH_SHORT).show();
dialog.dismiss();
goToHomeActivity(model);
});
}
});
}
private void goToHomeActivity(DriverInfoModel driverInfoModel) {
Common.currentUser = driverInfoModel;
startActivity(new Intent(this,DriverHomeActivity.class));
finish();
}
}
you are probably not clearing your previous activity by providing a flag while firing the intent. pass clear top flag here:
startActivity(new Intent(this,DriverHomeActivity.class));

Login to Firebase using phone returns null pointer

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();
}
};

How to determine why my Android application keeps stopping?

I'm having a problem with my application. The application is supposed to send a message using volume key buttons on the phone. The problem is that it keeps stopping and I do not know if it works. Here is the code, I also added some wake lock in order for my app to stay active even when phone is locked.
public class MainActivity extends Activity {
private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111;
private Button sendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
setContentView(R.layout.activity_main);
sendMessage = findViewById(R.id.send_message);
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
sendMessage.setEnabled(false);
if (checkPermission(Manifest.permission.SEND_SMS)) {
sendMessage.setEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
}
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
sendMessage.setEnabled(true);
return true;
} else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
sendMessage.setEnabled(true);
return true;
} else
return super.onKeyDown(keyCode, event);
}
private boolean checkPermission(String permission) {
int checkPermission = ContextCompat.checkSelfPermission(this, permission);
return checkPermission == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case SEND_SMS_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
sendMessage.setEnabled(true);
}
break;
}
}
}
Right now your code is not sending any messages when you press the volume key nor when you release it. You need to add this to your code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
...
}
Also, you're missing n opening bracket on the final else of your onKeyDown()

Text message not being sent to a list of numbers but is sent when just one number is specified

I am trying to build an application where the user can send his/her location to the stored phone numbers in a sqlitedatabase. I tested the application where the user can send the location as a text message to just one phone number and it worked but now when I try to create a list of numbers and pass it as a parameter in sendTextMessage method of smsManager the location as a text message is not sent. I have tried out the given code below so far,
Code
public class Gps4Activity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener {
private static final String LOG_TAG = "PlacesAPIActivity";
private static final int GOOGLE_API_CLIENT_ID = 0;
private GoogleApiClient mGoogleApiClient;
private static final int PERMISSION_REQUEST_CODE = 100;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
private TextView display;
private Button location_button,contacts_button;
//String number="xxxxxxxxxx";
ArrayList<String> numbers;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps4);
numbers=new ArrayList<>();
db = new UserDatabase(this).getReadableDatabase();
location_button=(Button)findViewById(R.id.show_button);
contacts_button=(Button)findViewById(R.id.view_button);
display=(TextView)findViewById(R.id.location_textview);
mGoogleApiClient = new GoogleApiClient.Builder(Gps4Activity.this)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.build();
location_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mGoogleApiClient.isConnected()) {
if (ActivityCompat.checkSelfPermission(Gps4Activity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Gps4Activity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_CODE);
ActivityCompat.requestPermissions(Gps4Activity.this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
callPlaceDetectionApi();
}
});
contacts_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Gps4Activity.this,DetailsActivity.class);
startActivity(intent);
}
});
}
public ArrayList<String> getContacts(){
Cursor cursor=db.rawQuery("SELECT * FROM "+UserDatabase.TABLE_NAME,null);
while (cursor.moveToNext()){
String contact=cursor.getString(cursor.getColumnIndex(UserDatabase.NUMBER));
numbers.add(contact);
}
return numbers;
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e(LOG_TAG, "Google Places API connection failed with error code: "
+ connectionResult.getErrorCode());
Toast.makeText(this,
"Google Places API connection failed with error code:" +
connectionResult.getErrorCode(),
Toast.LENGTH_LONG).show();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callPlaceDetectionApi();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
break;
}
}
private void callPlaceDetectionApi() throws SecurityException {
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
Log.i(LOG_TAG, String.format("Place '%s' with " +
"likelihood: %g",
placeLikelihood.getPlace().getName(),
placeLikelihood.getLikelihood()));
display.setText(placeLikelihood.getPlace().getAddress().toString());
messageSending(placeLikelihood.getPlace().getAddress().toString());
break;
}
likelyPlaces.release();
}
});
}
public void messageSending(String message){
SmsManager smsManager = SmsManager.getDefault();
// smsManager.sendTextMessage(number, null, message, null, null);
getContacts();
smsManager.sendTextMessage(String.valueOf(numbers),null,message,null,null);
Toast.makeText(getApplicationContext(), "SMS sent."+String.valueOf(numbers),
Toast.LENGTH_LONG).show();
}
}
The commented lines are the ones when I tried to test the application with just one phone number. Also, suppose initially there is just one phone number in sqlitedatabase , as many times I click the location_button that many times the arraylist grows it's size. For example , initially if the arraylist has elements [xxxxxx] next time I click the location_button the arraylist will now have [xxxxxx,xxxxxx].
Can anyone help me solving this issue?
Since the sendTextMessage() method only can take one number at a time, you need to execute this method for each number in the list.
That being said you should 'loop' through that List. Like this:
for (String number : numbers) {
smsManager.sendTextMessage(numbers, null, message, null, null);
}
What it basically is saying is:
"Allright, let's take number one, sendTextMessage to number one, and I will keep doing this until I am done."

ActivityCompat can't find .checkSelfPermission in eclipse

I have create program which can send message. when I use Activity.checkSelfPermission, it show the error like "The method checkSelfPermission(MainActivity, String) is undefined for the type ActivityCompat". I have import android.support.v4.app.ActivityCompat already. My target API 23 and compile with API 23 also. How to solve it?
Below is the real code
public class MainActivity extends Activity {
public static final int MY_PERMISSION_SEND_SMS = 10;
public EditText edSMS, edPhone;
public Button btnSent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edSMS = (EditText)findViewById(R.id.editText1);
edPhone = (EditText)findViewById(R.id.editText2);
btnSent = (Button)findViewById(R.id.button1);
onCheckPermission();
}
private void onCheckPermission() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.SEND_SMS)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermission(this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSION_SEND_SMS);
}
else {
sentMessage();
}
}
private void sentMessage() {
btnSent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber = edPhone.getText().toString();
String SMS = edSMS.getText().toString();
if(((phoneNumber.length() == 10) || (phoneNumber.length()==9)) && phoneNumber.length()>0){
SmsManager smsText = SmsManager.getDefault();
smsText.sendTextMessage(phoneNumber, null, SMS, null, null);
Toast.makeText(MainActivity.this, "SMS was sent successful", Toast.LENGTH_LONG).show();
edPhone.setText("");
edSMS.setText("");
} else {
Toast.makeText(MainActivity.this, "Please check your " + "phone number again",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode){
case MY_PERMISSION_SEND_SMS:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Read Contacts permission granted", Toast.LENGTH_SHORT).show();
sentMessage();
}else{
Toast.makeText(this, "Read Contacts permission denied", Toast.LENGTH_SHORT).show();
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)){
new AlertDialog.Builder(this).
setTitle("Request Permission SMS").
setMessage(" You must set permission to access this application").show();
}
}
break;
}
}
To solve the method ActivityCompat.checkSelfPermission() not found in Eclipse you can simply add android-support-compat.jar as taken from https://github.com/dandar3/android-support-compat/tree/28.0.0 to the libs folder of your Eclipse project and compile again.
just use support.v7 (import android.support.v7.app.AppCompatActivity;),this is well be rolved
by the way?why do you still use eclipse now?just use Android studio,it's better so much.

Categories