we have one requirement, to display primary Gmail account in edittext. But i am getting all email(Gmail) accounts which are logged in my mobile.
I am using below code.
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(MainActivity.this).getAccountsByType("com.google");
if(accounts.length>1){
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
Log.d("email::","email::"+possibleEmail+"----"+account.type);
}
}
}else{
Log.d("email::","email::no mails found");
}
Please help me to find out the primary email id.
Thanks
Try This:-
private String getEmailID() {
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();
for (Account account : list) {
if (account.type.equalsIgnoreCase("com.google")) {
gmail = account.name;
break;
}
}
mStr_email = gmail;
Log.d(KEY_TAG, "EMAIL" + mStr_email);
return mStr_email;
}
Code to Check whether Internet Connection is On:-
InternetConnection ic = new InternetConnection(getApplicationContext());
isInternetPresent = ic.isConnectingToInternet();
if (!isInternetPresent) {
Utilities.showToast(SplashActivity.this,
"Switch on Internet Connection");
startActivity(new Intent(Settings.ACTION_SETTINGS));
} else {
Log.d(KEY_TAG, "Check attendane ");
}
Related
I am developing an API for reset/ forgot password. I have created an API for send otp to registered user only. In this, I am storing generated OTP in database too.
Below is my SenOTP model:
public class SendOTP {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long sendotpid;
private int otp;
private String phone;
private static final long OTP_VALID_DURATION = 5 * 60 * 1000; // 5 minutes
#Column(name="otp_Requested_Time")
private Date otpRequestedTime;
public boolean isOTPRequired() {
if(this.getOtp() == 0) {
return false;
}
long currentTimeInMillis = System.currentTimeMillis();
long otpRequestedTimeMillis = this.otpRequestedTime.getTime();
if(otpRequestedTimeMillis + OTP_VALID_DURATION < currentTimeInMillis) {
// otp expires
return false;
}
return true;
}
}
Below is send otp to regsitered phone number API:
public int getOTP() {
Random r = new Random();
int min = 1000;
int max = 9999;
int uid = r.nextInt(max-min) + min;
return uid;
}
public ResponseEntity<?> sendotptoregisteredphone(HttpServletRequest request, #RequestParam("phone") String phone) {
CustomResponse = ResponseFactory.getResponse(request);
phone = phone.replace(" 1", "").replace("NA", "").replace(" 1NA", "").replace(",", "").replace("-", "").replace("(", "").replace(")", "").replace(" ", "");
User registeredUser = userDao.findByPhoneAndPhoneverify(phone,1);
if(registeredUser != null) {
if(phone.equals(registeredUser.getPhone())) {
int otp = getOTP();
SendOTP s = new SendOTP();
s.setOtp(otp);
s.setPhone(phone);
s.setOtpRequestedTime(new Date());
SendOTP sotp = sendOtpDao.save(s);
// Here is my Twilio implementation to send message to entered phone number
CustomResponse.setResponse(sotp);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
CustomResponse.setResponseMessage(CustomStatus.SuccessMsg);
}
}else {
CustomResponse.setResponse("Sorry ! Phone number is not registered with us.");
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
Below API is to verify entered OTP:
public ResponseEntity<?> verifyotp(HttpServletRequest request, #RequestParam("otp") String otp) {
CustomResponse = ResponseFactory.getResponse(request);
int flag = checkapikey(apikey);
SendOTP otpByUser;
try {
if(otp != null || otp != "" || otp.equalsIgnoreCase("NA")) {
int otpValue = Integer.parseInt(otp);
otpByUser = sendOtpDao.findByOtp(otpValue);
// What next, I am bit confuse here.
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse("Error occurred! please try again");
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
Now, next I want to verify or validate OTP that user will enter and check whether the OTP is expired or not. If OTP is not expired then forgot/reset password API should work.
Please suggest me any solution or answer.
I'm creating an app with two activities, LoginActivity and MainActivity. In the first activity, I authenticate the user and put its uid in an Intent. In the second activity, I get the uid, using the following line of code:
String uid = getIntent().getStringExtra("uid"); //Works fine
When I first sign-up and try to use the following lines of code in onCreate:
DocumentReference uidRef = rootRef.collection("users").document(uid);
uidRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
User user = document.toObject(User.class);
if (user != null) {
String name = user.getName();
textView.setText(name);
}
} else {
Log.d(TAG, "document doesn't exist!");
}
}
});
I get in the logcat: document doesn't exist! even if I see at that location (users -> uid), the document exists. If I close the app and start it again, everything works fine. How to get the name displayed from the first time?
Edit: And this is how I add the user to the database:
String uid = firebaseUser.getUid();
String userName = firebaseUser.getDisplayName();
User user = new User(userName);
DocumentReference ref = db.collection("users").document(uid);
ref.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot snapshot = task.getResult();
if (!snapshot.exists()) {
ref.set(user);
}
}
});
Edit:
public class User {
private String name;
public User() {}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Database:
For some reason is returning null when tries to get results, somebody has seen this?
When debuging, he goes to the exception on main method, right when he reads this line :
printResults(getResults(analytics, profile));
He does reach the profile ID, although its not working on the method results, my google analytics account is working just fine
I get this in console:
First Profile Id: 166128559
java.lang.NullPointerException at HelloAnalytics.printResults(HelloAnalytics.java:99)
at HelloAnalytics.main(HelloAnalytics.java:33)
Code :
public class HelloAnalytics {
private static final String APPLICATION_NAME = "Hello Analytics";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String KEY_FILE_LOCATION = "C:/Users/Shell/workspace/relatorio-analytics/src/main/java/client_secrets.p12";
private static final String SERVICE_ACCOUNT_EMAIL = "shell-121#projeto-analytics-188712.iam.gserviceaccount.com";
public static void main(String[] args) {
try {
Analytics analytics = initializeAnalytics();
String profile = getFirstProfileId(analytics);
System.out.println("First Profile Id: " + profile);
printResults(getResults(analytics, profile));
} catch (Exception e) {
e.printStackTrace();
}
}
private static Analytics initializeAnalytics() throws Exception {
// Initializes an authorized analytics service object.
// Construct a GoogleCredential object with the service account email
// and p12 file downloaded from the developer console.
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY).setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
.setServiceAccountScopes(AnalyticsScopes.all()).build();
// Construct the Analytics service object.
return new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
.build();
}
private static String getFirstProfileId(Analytics analytics) throws IOException {
// Get the first view (profile) ID for the authorized user.
String profileId = null;
// Query for the list of all accounts associated with the service account.
Accounts accounts = analytics.management().accounts().list().execute();
if (accounts.getItems().isEmpty()) {
System.err.println("No accounts found");
} else {
String firstAccountId = accounts.getItems().get(0).getId();
// Query for the list of properties associated with the first account.
Webproperties properties = analytics.management().webproperties().list(firstAccountId).execute();
if (properties.getItems().isEmpty()) {
System.err.println("No Webproperties found");
} else {
String firstWebpropertyId = properties.getItems().get(0).getId();
// Query for the list views (profiles) associated with the property.
Profiles profiles = analytics.management().profiles().list(firstAccountId, firstWebpropertyId)
.execute();
if (profiles.getItems().isEmpty()) {
System.err.println("No views (profiles) found");
} else {
// Return the first (view) profile associated with the property.
profileId = profiles.getItems().get(0).getId();
}
}
}
return profileId;
}
private static GaData getResults(Analytics analytics, String profileId) throws IOException {
// Query the Core Reporting API for the number of sessions
// in the past seven days.
return analytics.data().ga().get("ga:" + profileId, "7daysAgo", "today", "ga:sessions").execute();
}
private static void printResults(GaData results) {
// Parse the response from the Core Reporting API for
// the profile name and number of sessions.
if (results != null && !results.getRows().isEmpty()) {
System.out.println("View (Profile) Name: " + results.getProfileInfo().getProfileName());
System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
} else {
System.out.println("No results found");
}
}
I am developing an android app, in which I am taking contacts from contact list and showing in listview, when I display mobile number if user has two mobile number saved in a contact, then in listview his name is repeated and second mobile number is shown below his first name, so if two mobile number is saved for a particular number I need to select only first number, so what change I need to do in following code, if anybody know please help.
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
ArrayList<Contact> contacts = new ArrayList<Contact>();
while (c.moveToNext())
{
int type = c.getInt(c.getColumnIndex(Phone.TYPE));
if (type == Phone.TYPE_MOBILE)
{
Contact con = new Contact(c.getString(c
.getColumnIndex(Contacts.DISPLAY_NAME)), c.getString(c
.getColumnIndex(Phone.NUMBER)));
contacts.add(con);
}
}
public void readContacts() {
Cursor contactsCursor =getActivity().getContentResolver().query(ContactsContract
.Contacts.CONTENT_URI, null, null, null,ContactsContract.Contacts.DISPLAY_NAME);
mContactsMetaDataList = new ArrayList<>();
try {
Set<String> idSet = new HashSet<>();
if (contactsCursor.getCount() > 0) {
while (contactsCursor.moveToNext()) {
String id =contactsCursor.getString(contactsCursor.getColumnIndex
(ContactsContract.Contacts._ID));
String name =contactsCursor.getString(contactsCursor.getColumnIndex
(ContactsContract.Contacts.DISPLAY_NAME));
if(Integer.parseInt(contactsCursor.getString(contactsCursor.getColumnIndex
(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
idSet.add(name);
if (!idSet.contains(name)){
//add contact to your list here
}
}
}
}
}finally {
if (contactsCursor != null) {
contactsCursor.close();
}
}
}
in my team's Android application I have a service running from boot which communicates with a server to perform operations such as logging in, registering, chatting between phones and updating the phone database.
I need to make my service communicate with the activity bi-directionally: for example I am working on the login activity at the moment and the username and passwords are Strings taken from a text field on the app screen and I have been able to pass them to the service for it to send an authorisation command to the server.
public void loginPressed(View v){
usernameStr = usernameField.getText().toString();
passwordStr = passwordField.getText().toString();
if (!bound) return;
Bundle b = new Bundle();
Message msg = Message.obtain(null, ChatService.LOGIN);
try {
b.putString("username", usernameStr);
b.putString("password", passwordStr);
msg.setData(b);
messenger.send(msg);
}
catch (RemoteException e) {
}
This works as I would have expected. When the server responds with a message saying whether or not the login was sucessful, I need it to pass a message back to the activity so that I can start the main activity if succesful or prompt for re-entry if not.
I tried to use the msg.replyTo field to get the return messenger to send the information back, but when I run the app it force closes with a null pointer exception and I have no idea why this is happening. Here is the code that seems to be the culprit:
private class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case LOGIN:
Bundle b = msg.getData();
String username = b.getString("username");
String password = b.getString("password");
String loginMessage = TCPCall.login(username, password);
connection.sendMessage(loginMessage);
String loginReturn = connection.retrieveMessage();
Message m;
Scanner s = new Scanner(loginReturn);
s.useDelimiter(",");
String c = s.next();
String status = s.next();
String message = s.next();
if (status.equals("OK")) {
m = Message.obtain(null, LoginActivity.OK);
try {
msg.replyTo.send(m);
} catch (RemoteException e) {}
}
else {
m = Message.obtain(null, LoginActivity.ERR);
try {
msg.replyTo.send(m);
} catch (RemoteException e) {}
}
break;
The null pointer seems to be coming from the
msg.replyTo.send(m);
line of code in both cases (login succesful and login failed)
Any help to fix this problem would be greatly appreciated :)
As Gregg points out in the comments. You need to set msg.replyTo = messenger; int he place where you send the original message.
An example can be found here: http://www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger.html
I think you forgot to send response to Login Activity by bundle from Service.
So, i made some changes in Messenger Service
define one global variable and made some changes in Incoming Handler
static final int LOGIN_STATUS = 1;
private class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case LOGIN:
Bundle b = msg.getData();
String username = b.getString("username");
String password = b.getString("password");
String loginMessage = TCPCall.login(username, password);
connection.sendMessage(loginMessage);
String loginReturn = connection.retrieveMessage();
Message m = Message.obtain(null, LOGIN_STATUS);
Scanner s = new Scanner(loginReturn);
s.useDelimiter(",");
String c = s.next();
String status = s.next();
String message = s.next();
if (status.equals("OK")) {
b.putString("responseC",c);
b.putString("responseStatus",status);
b.putString("responseMessage",message)
m.setData(b);
try {
msg.replyTo.send(m);
} catch (RemoteException e) {}
}
else {
/*if something is wrong with username and password you can put
a toast*/
}
break;
Now we have to catch this response in our LoginActivity and
take IncomingHandler in Login Activity also
class IncomingHandler extends Handler{
#Override
public void handleMessage(Message msg) {
switch (msg.what){
case ChatService.LOGIN_STATUS:
String C = msg.getData().getString("responseC");
String Status = msg.getData().getString("responseStatus");
String Message = msg.getData().getString("responseMessage");
//Here is your response in LoginActivity, enjoy!!!
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mMessenger = new Messenger(new IncomingHandler());
public void loginPressed(View v){
usernameStr = usernameField.getText().toString();
passwordStr = passwordField.getText().toString();
if (!bound) return;
Bundle b = new Bundle();
Message msg = Message.obtain(null, ChatService.LOGIN_SATUS,0,0);
try {
b.putString("username", usernameStr);
b.putString("password", passwordStr);
msg.setData(b);
msg.replyTo = mMessenger;
messenger.send(msg);
}
catch (RemoteException e) {
// In this case the service has crashed before we could even
// do anything with it; we can count on soon being
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
}
This code is working perfectly, hope it will help you,
Thanks