my app keep stopping after i click the button send sms and i don't know why.
Can you please help me to fix that.
Can you please help me to fix that? I tried many solutions that I found in this website, but it doesn't work with me. I am totally new to Android Studio, so I don't know how to write my code that it will work the way I want it.
This is ma MainActivity code :
Button button1;
ListView listView;
DbHelper db;
List<ContactModel> list;
CustomAdapter customAdapter;
Button send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// check for runtime permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.READ_CONTACTS}, 100);
}
}
// this is a special permission required only by devices using
// Android Q and above. The Access Background Permission is responsible
// for populating the dialog with "ALLOW ALL THE TIME" option
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 100);
}
button1 = findViewById(R.id.Button1);
listView = (ListView) findViewById(R.id.ListView);
db = new DbHelper(this);
list = db.getAllContacts();
customAdapter = new CustomAdapter(this, list);
listView.setAdapter(customAdapter);
send = findViewById(R.id.send);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calling of getContacts()
if (db.count() != 5) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
} else {
Toast.makeText(MainActivity.this, "Can't Add more than 5 Contacts", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onSuccess(Location location) {
// check if location is null
// for both the cases we will
// create different messages
if (location != null) {
// get the SMSManager
SmsManager smsManager = SmsManager.getDefault();
// get the list of all the contacts in Database
DbHelper db = new DbHelper(MainActivity.this);
List<ContactModel> list = db.getAllContacts();
// send SMS to each contact
for (ContactModel c : list) {
String message = "Hey, " + c.getName() + "I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\n " + "http://maps.google.com/?q=" + location.getLatitude() + "," + location.getLongitude();
smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null);
}
} else {
String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station.";
SmsManager smsManager = SmsManager.getDefault();
DbHelper db = new DbHelper(MainActivity.this);
List<ContactModel> list = db.getAllContacts();
for (ContactModel c : list) {
smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Permissions Denied!\n Can't use the App!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// get the contact from the PhoneBook of device
switch (requestCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String phone = null;
try {
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
phones.moveToFirst();
phone = phones.getString(phones.getColumnIndex("data1"));
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
db.addcontact(new ContactModel(0, name, phone));
list = db.getAllContacts();
customAdapter.refresh(list);
} catch (Exception ex) {
}
}
}
break;
}
}
And this is my xml :
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/send"
android:text="send sms"
android:onClick="onSuccess"
/>
<Button
android:id="#+id/Button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="12dp"
android:background="#0F9D58"
android:text="Add Emergency Contact "
android:textColor="#FFFFFF" />
<ListView
android:id="#+id/ListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
And this the error (logcat) :
Process: com.example.smscontact, PID: 17949
java.lang.IllegalStateException: Could not find method onSuccess(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.button.MaterialButton with id 'send'
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:506)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:464)
at android.view.View.performClick(View.java:7184)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
at android.view.View.performClickInternal(View.java:7157)
at android.view.View.access$3500(View.java:821)
at android.view.View$PerformClick.run(View.java:27660)
at android.os.Handler.handleCallback(Handler.java:914)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:225)
at android.app.ActivityThread.main(ActivityThread.java:7563)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)
Related
I'm a beginner in Android. I tried to do application to send SMS. The applications stops working when I try to send a message on my phone. A message appears in the emulator: "Send sent". I don't understand what the problem is.
Application code:
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
String phoneNo;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editText);
txtMessage = (EditText) findViewById(R.id.editText2);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
phoneNo = "+48" + txtphoneNo.getText().toString();
message = txtMessage.getText().toString();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
}
In AndroidManifest.xml I wrote:
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
Thank you in advance
I'm trying to retrieve the actual image name of the image selected by user in gallery(Ex. IMG_2020).
I tried using getAbsolutePath() and getName() but these 2 methods display something like "image$3A75" instead of the actual image file name.
Other than that, I also tried using some cursor method which I don't know really how it works, but it still doesn't work or maybe it's because I do not know how to use it.
Any help please?
This is my onActivityResult() method
fileName is the textView I want to place my imageName
bitMap object is not used yet because I'm following a tutorial online and I'm halfway copying, I think it will be used later in the tutorial
public class createCharity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
Button uploadButton;
Button createCharityButton;
TextView charityTitle;
TextView fileName;
TextView charityDescription;
Uri charityImage;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_charity);
uploadButton = findViewById(R.id.uploadButton);
charityTitle = findViewById(R.id.charityTitle);
fileName = findViewById(R.id.fileName);
charityDescription = findViewById(R.id.charityDescription);
createCharityButton = findViewById(R.id.createCharityButton);
mStorageRef = FirebaseStorage.getInstance().getReference("charityUploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("charityUploads");
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
System.out.println("----------------------c1");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
charityImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), charityImage);
File file = new File(String.valueOf(charityImage));
System.out.println("Image name: " + file.getName());
fileName.setText(file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Something like:
String projection [] = {
MediaStore.Images.Media.DATA
, MediaStore.Images.Media.DISPLAY_NAME
, MediaStore.Images.Media.SIZE};
Cursor cursor = getContentResolver().query(data.getData(), projection, null, null, null);
if ( cursor==null)
{
Toast.makeText(context, "cursor==null\n\ncould not query content resolver for\n\n" + path, Toast.LENGTH_LONG).show();
return;
}
cursor.moveToFirst();
String data = cursor.getString(0);
String displayName = cursor.getString(1);
String size = cursor.getString(2);
Toast.makeText(context, "getContentResolver().openInputStream() ok\n\n" + path
+ "\n\nDISPLAY_NAME: " + displayName
+ "\nDATA: " + data
+ "\nSIZE: " + size
, Toast.LENGTH_LONG).show();
cursor.close();
DATA not available on Android Q+.
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."
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.
I'm trying to implementAutoCompleteTextView to populate the users email in a log-in activity for a better UX.
To comply with Google's specification to read contacts, this app asks permission from the user at run time using checkSelfPermission() method and that much I do know is working. However, when a user types in their user email, a drop-down list should show after at least two characters are inputted and this isn't happening.
Expected output:
Below is my implementation (attempt). Any feedback with code (correction) example will be greatly appreciated.
build.gradle:
...
compileSdkVersion 25
buildToolsVersion "25.0.2"
...
AndroidManifest.xml:
...
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
...
activity_login.xml:
...
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:textColor="#android:color/white"
/>
</android.support.design.widget.TextInputLayout>
...
LoginActivity.java: (Sorry for showing the entire class but.... just in-case.)
package com.company.product.activity;
import too.many.imports
import com.company.product.R;
import static android.Manifest.permission.READ_CONTACTS;
public class LoginActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
// UI references.
private EditText inputPassword;
private AutoCompleteTextView inputEmail;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// set the content view
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputEmail = (AutoCompleteTextView) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
populateAutoComplete();
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful())
{
// there was an error
if (password.length() < 6)
{
inputPassword.setError(getString(R.string.minimum_password));
}
else
{
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
}
else
{
// Send to check if the user has been verified.
checkIfEmailVerified();
}
}
// Logic for checking if the email is verified or not
private void checkIfEmailVerified()
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified())
{
// user is verified, finish this activity and send to MainActivity.
Toast.makeText(LoginActivity.this, "Successfully logged in: Lets start flying!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
// Email is not verified and prompt a message to the user and restart this activity.
// NOTE: don't forget to log out the user.
FirebaseAuth.getInstance().signOut();
}
}
});
}
});
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getSupportLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(inputEmail, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
inputEmail.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
}
Replace your onCreateLoader() method code with below code.
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
ContactsContract.Data.CONTENT_URI, ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
You can do this
make your adapter as global variable and add textwatcher for input email ,and set your adapter only when text size reaches 2
inputEmail.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() < 2) {
inputEmail.setAdapter(null)
}
else if(s.length()==2){
//this is to make sure adapter not getting set every time if length is greater than 2
inputEmail.setAdapter(adapter)
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
change the condition as you prefer.Hope this helps
You can achieve this as follows:
First create a custom ArrayAdapter instead of
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
inputEmail.setAdapter(adapter);
Let's say we call it AutoCompleteAdapter and let it implement Filterable interface
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
Override the getFilter() and put the char length check to 2 chars for email.