Problem with send message using SmsManager - java

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

Related

Cannot discover peers - Wifi Direct-

I want to have a connection between two android devices on the same local network and exchange data between them through my android app.
I used Wifi Direct Api with Broadcast receiver approach in order to get into that purpose, but for some reason the discoverPeers method does not get triggered.
This is the code for my MainActivity:
public class MainActivity extends AppCompatActivity {
private static MainActivity instance;
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, connection_status;
EditText writeMessage;
WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if (!peerList.getDeviceList().equals(peers)) {
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()];
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()];
int index = 0;
for (WifiP2pDevice device : peerList.getDeviceList()) {
deviceNameArray[index] = device.deviceName;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, deviceNameArray);
listView.setAdapter(adapter);
}
if (peers.size() == 0) {
Toast.makeText(getApplicationContext(), "No device Found", Toast.LENGTH_SHORT).show();
return;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialWork();
exqListener();
}
public static MainActivity getInstance() {
return instance;
}
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (wifiManager.isWifiEnabled() == true) {
wifiManager.setWifiEnabled(false);
btnOnOff.setText("Set To OFF ");
} else {
wifiManager.setWifiEnabled(true);
btnOnOff.setText("Set To ON");
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connection_status.setText("Discovery Started");
}
#Override
public void onFailure(int reason) {
connection_status.setText("Discovery Starting Failed");
}
});
}
});
}
private void initialWork() {
btnOnOff = (Button) findViewById(R.id.onOff);
btnDiscover = (Button) findViewById(R.id.discover);
btnSend = (Button) findViewById(R.id.sendButton);
read_msg_box = (TextView) findViewById(R.id.readMsg);
connection_status = (TextView) findViewById(R.id.connectionStatus);
writeMessage = (EditText) findViewById(R.id.writeMsg);
listView = (ListView) findViewById(R.id.peerListView);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WifiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
}
And this is the one of the WifiDirectBroadcatReceiver:
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private AppCompatActivity mActivity;
public WifiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, AppCompatActivity mActivity) {
this.mManager = mManager;
this.mChannel = mChannel;
this.mActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Toast.makeText(context, "Wifi is ON", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Wifi is OFF", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
Toast.makeText(context, "Dkhal hnaya bro", Toast.LENGTH_SHORT).show();
if (mManager != null) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mManager.requestPeers(mChannel, MainActivity.getInstance().peerListListener);
}
} else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Do something
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Do something
}
}
}
And this the permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
According to the code, there is a textView that should change its text once I press on the button btnDiscover, but when I do, nothing happens.
Knowing that I was turning my location service on before running the app, what would the error be ?
Every other approach to tackle the situation will be welcome.
Starting Android 11, certain permissions have to be requested during runtime, regardless of what's defined in your manifest. As the comments in your code point out, you should use requestPermissions to do so in your MainActivity and (optionally) react to the outcome using onRequestPermissionsResult.

Android send me twice the same message

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

i can't read the user storage,

I' am trying to list all the folders and files from user storage, I've declared the READ_EXTERNAL_STORAGE permission in android.manifest file but I don't what's wrong, I can't read the user storage
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(this);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, 123);
} else {
Log.d(TAG, "onCreate: Permission Granted");
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case 123:
if (grantResults != null && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
String path = "/";
File dir = new File(path);
if (dir.isDirectory()) {
Log.d(TAG, "dir: Yes, I am!");
}
if (dir.canRead()) {
Log.d(TAG, "dir: Read me!");
} else {
Log.d(TAG, "dir: you can't read me!");
}
if (dir.canWrite()) {
Log.d(TAG, "dir: use me!");
} else {
Log.d(TAG, "dir: You Can't write me");
}
}
}
}
log cat: D/MainActivity: onCreate: Permission Granted 2020-05-04
07:21:09.680 27634-27634/co.ak.externalstorage D/MainActivity: dir:
Yes, I am! 2020-05-04 07:21:09.680 27634-27634/co.ak.externalstorage
D/MainActivity: dir: you can't read me! 2020-05-04 07:21:09.680
27634-27634/co.ak.externalstorage D/MainActivity: dir: You Can't write
me
The "/" root directory is not readable since Android 7.
Why are you calling that user storage?

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.

Android AutoCompleteTextView with Email Not Populating

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.

Categories