I'm attempting to create a simple android/aws project and I'm receiving an error and I don't know where to look. Note sure if it matters but i'm attempting to connect my app to an identity pool to have users log in with an email address.
public class MainActivity extends AppCompatActivity {
//AWS Housekeeping
public static PinpointManager pinpointManager;
private DynamoDBMapper dynamoDBMapper;
private final String POOL_ID = "xxxxxxxx";
private final String USER_POOL = "xxxxxxxxx";
private AWSCredentialsProvider awsCredentialsProvider;
private AWSConfiguration awsConfiguration;
private Button loginBtm;
private Button createUserBtm;
private EditText emailField;
private EditText passwordField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createUserBtm = findViewById(R.id.createButton);
loginBtm = findViewById(R.id.loginButton);
emailField = findViewById(R.id.usernameField);
passwordField = findViewById(R.id.passwordField);
final Intent newUserIntent = new Intent(this, NewUserActivity.class);
final Intent signInIntent = new Intent(this, HomeActivity.class);
AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() {
#Override
public void onComplete(AWSStartupResult awsStartupResult) {
// Obtain the reference to the AWSCredentialsProvider and AWSConfiguration objects
awsCredentialsProvider = AWSMobileClient.getInstance().getCredentialsProvider();
awsConfiguration = AWSMobileClient.getInstance().getConfiguration();
// Use IdentityManager #getUserID to fetch the identity id.
IdentityManager.getDefaultIdentityManager().getUserID(new IdentityHandler() {
#Override
public void onIdentityId(String identityId) {
Log.d("YourMainActivity", "Identity ID = " + identityId);
// Use IdentityManager#getCachedUserID to
// fetch the locally cached identity id.
final String cachedIdentityId =
IdentityManager.getDefaultIdentityManager().getCachedUserID();
}
#Override
public void handleError(Exception exception) {
Log.d("YourMainActivity", "Error in retrieving the identity: " + exception);
}
});
}
}).execute();
createUserBtm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(newUserIntent);
}
});
loginBtm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(emailField.getText().toString() != null && passwordField.getText().toString() != null){
CognitoUserPool userPool = new CognitoUserPool(getApplicationContext(), POOL_ID, USER_POOL, null, Regions.US_EAST_1);
CognitoUser cognitoUser = userPool.getUser();
cognitoUser.getSessionInBackground(authenticationHandler);
startActivity(signInIntent);
}
}
});
}
class loginUser extends AsyncTask<Void, Void, Void>{
DynamoDBMapper dynamoDBMapper;
String username;
String password;
#Override
protected void onPreExecute(){
username = emailField.getText().toString();
password = passwordField.getText().toString();
}
#Override
protected Void doInBackground(Void... voids) {
//Instantiate an AmazonBynamoDBMapperClient
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
this.dynamoDBMapper = DynamoDBMapper.builder()
.dynamoDBClient(dynamoDBClient)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.build();
return null;
}
}
final AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
Log.i("Success: ", userSession.getAccessToken().getJWTToken());
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(emailField.toString(), passwordField.toString(), null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
}
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
}
#Override
public void onFailure(Exception exception) {
Log.i("ERROR:", exception.getMessage().toString());
}
};
}
04-15 18:32:09.618 5880-5880/com.ronone.securesender I/ERROR:: Unable to verify secret hash for client xxxxxxxxxxx (Service: AmazonCognitoIdentityProvider; Status Code: 400; Error Code: NotAuthorizedException; Request ID: 4eca8202-40db-11e8-a05e-217eccab3af8)
Where can I locate this secret hash key? Thanks for any help in advance.
Refer to this link. Secret hash needs to be calculated using username, clientId and clientSecretId. The python implementation is provided in the link. Translate it your preferred language.
https://aws.amazon.com/premiumsupport/knowledge-center/cognito-unable-to-verify-secret-hash/
Related
I am developing an app in java in the android studio IDE, the idea is that after logging in with my username and password, I can be redirected to a new view where a user profile is shown with the name, email and profile image. Currently I can log in and after that it redirects to the user profile but I don't know how to get the name, email and profile image.Then I leave you my code in case you have the time to help me, thank you very much for reading:
loggin.class
public class loggin extends AppCompatActivity {
//variable twitter
Button twitterButton;
//TwitterLoginButton login;
private static final String TAG = "Twitter4j";
private static Twitter twitter;
private static final String APIConsumerKey = "xxxx";
private static final String APIConsumerSecretKey = "xxxx";
private static final String CALLBACK_URL = "http://myurl";
private static RequestToken twitterRequestToken;
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initializeTwitter(loggin.this);
}
});
}
private static void initializeTwitter(final Activity activity) {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(APIConsumerKey);
configurationBuilder.setOAuthConsumerSecret(APIConsumerSecretKey);
twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
new Thread(new Runnable() {
#Override
public void run() {
User user;
try {
twitterRequestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
Log.i("LoginActivity", String.valueOf(twitterRequestToken));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Open Dialog for authentication.
Intent intent = new Intent(activity, TwitterAuthActivity.class);
if (twitterRequestToken != null) {
intent.putExtra("TwitterReqTokenUrl", twitterRequestToken.getAuthenticationURL());
activity.startActivity(intent);
}
}
});
} catch (Exception e) {
Log.e(TAG, "Exception " + e.getMessage());
}
}
}).start();
}
}
twitterAuthActivity
public class TwitterAuthActivity extends AppCompatActivity {
private static final String TAG = "Twitter4j";
private static final String TWITTER_CALLBACK_URL = "http://www.stackoverflow.com"; //"x-oauthflow-twitter://twitterlogin";
private ProgressDialog progressDialog;
private String twitterRequesTokenUrl;
private WebView twitterWebView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_twitter);
twitterWebView = findViewById(R.id.TwitterWebView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
twitterRequesTokenUrl = extras.getString("TwitterReqTokenUrl");
}
progressDialog = new ProgressDialog(this);
progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
progressDialog.setMessage("Loading...");
//Setup WebView
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
twitterWebView.setVerticalScrollBarEnabled(false);
twitterWebView.setHorizontalScrollBarEnabled(false);
twitterWebView.setWebViewClient(new TwitterWebViewClient());
WebSettings webSettings = twitterWebView.getSettings();
webSettings.setSupportZoom(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);
twitterWebView.loadUrl(twitterRequesTokenUrl);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
int[] l = new int[2];
twitterWebView.getLocationOnScreen(l);
Rect rect = new Rect(l[0], l[1], l[0] + twitterWebView.getWidth(), l[1] + twitterWebView.getHeight());
if (!rect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
finish();
}
}
return super.dispatchTouchEvent(ev);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean response = false;
if (url.contains(TWITTER_CALLBACK_URL)) {
Uri uri = Uri.parse(url);
//This uri could be saved as access token.
Log.i(TAG, "shouldOverrideUrlLoading() uri " + uri.getPath());
Intent intent=new Intent(TwitterAuthActivity.this,MainActivity.class);
startActivity(intent);
finish();
response = true;
}
return response;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(TwitterAuthActivity.this, "Upps! something happened, retry later!.", Toast.LENGTH_LONG).show();
finish();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(progressDialog.isShowing() && !isFinishing() && !isDestroyed()) {
progressDialog.dismiss();
}
twitterWebView.setVisibility(View.VISIBLE);
}
}
}
I'm writing a class with requests to rest API (Yandex disk). I use volley, but I do have some problems with getting a response from it. You can check the rest API here.
I use volley and I can get a response in the debugger, but not in my Activity.
Here is my Requests class
class Requests {
private String response_of_server, token;
private String url = "https://cloud-api.yandex.net/v1/disk";
private Context context;
Requests (String token, Context context) {
this.token = token;
this.context = context;
}
private void set_response_of_server(String response) {
this.response_of_server = response;
}
String get_response() {
return response_of_server;
}
void get_metadata_of_user() {
try {
/*Request*/
RequestQueue queue = Volley.newRequestQueue(this.context);
Response.ErrorListener error_listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
Response.Listener<String> response_listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
set_response_of_server(response);
}
};
StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Host", "cloud-api.yandex.net");
params.put("Authorization", token);
return params;
}
};
queue.add(getRequest);
/*Request end*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the MainActivity where I want my response.
public class MainActivity extends AppCompatActivity {
private final String ID_OF_APP = "Your token of app";
private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=token&client_id=" + ID_OF_APP;
private String SAVED_TOKEN = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_get_code = findViewById(R.id.btn_get_code); // send to get code page (yandex)
btn_get_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(URL_FOR_CODE_QUERY));
startActivity(i);
}
});
Button btn_sign_in = findViewById(R.id.btn_sign_in);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText code_field = findViewById(R.id.code_field);
String token = code_field.getText().toString();
save_token(token);
try {
if(check_token()) {
//Toast.makeText(MainActivity.this, "You are successfully signed in", Toast.LENGTH_SHORT).show();
// TODO change activity
}
else {}
} catch (InterruptedException e) {
e.printStackTrace();
}
//Toast.makeText(MainActivity.this, "Something went wrong. Please, check your connection and try again later", Toast.LENGTH_SHORT).show();
}
});
}
private void save_token(String token) {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TOKEN, token);
ed.apply();
}
private String load_token() {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
return sPref.getString(SAVED_TOKEN, "");
}
private boolean check_token() throws InterruptedException {
String token = load_token();
String result;
Requests request = new Requests(token, this);
request.get_metadata_of_user();
result = request.get_response();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
return !(result.equals("-1"));
}
}
check_token() function at the moment should just make a toast with a response of the server. However, I cannot get the Toast or any response coming back from the server.
You have a Requests class which has the function to call the server API which is Asynchronous. Hence, you will not get the result immediately after calling the request.get_metadata_of_user(); in your check_token() function.
Hence I would like to suggest you modify your Request class like the following.
public class Requests {
private String response_of_server, token;
private String url = "https://cloud-api.yandex.net/v1/disk";
private Context context;
private HttpListener listener; // Add a listener to get the callback functionality
Requests (String token, Context context, HttpListener listener) {
this.token = token;
this.context = context;
this.listener = listener; // initialize the listener here
}
private void set_response_of_server(String response) {
this.response_of_server = response;
listener.onResponseReceived(response); // Send the response back to the calling class
}
String get_response() {
return response_of_server;
}
void get_metadata_of_user() {
try {
RequestQueue queue = Volley.newRequestQueue(this.context);
Response.ErrorListener error_listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
Response.Listener<String> response_listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
set_response_of_server(response);
}
};
StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Host", "cloud-api.yandex.net");
params.put("Authorization", token);
return params;
}
};
queue.add(getRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now the HttpListener class might look like the following. Create HttpListener.java and add the following code to create this as an interface.
public interface HttpListener {
public void onResponseReceived();
}
Hence you need to implement this interface in your MainActivity like the following.
public class MainActivity extends AppCompatActivity implements HttpListener {
private final String ID_OF_APP = "Your token of app";
// I fixed this part too. Please change if that is not useful
private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=" + SAVED_TOKEN + "&client_id=" + ID_OF_APP;
private String SAVED_TOKEN = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ... I omitted some code
Button btn_sign_in = findViewById(R.id.btn_sign_in);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText code_field = findViewById(R.id.code_field);
String token = code_field.getText().toString();
save_token(token);
try {
// if(check_token()) {
// The check_token function call is Async. This will not return immediately. Hence you might consider removing this if part. Simply just call the function and listen to the callback function when the response is received
// }
check_token(); // Simply call the function here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void save_token(String token) {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TOKEN, token);
ed.apply();
}
private String load_token() {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
return sPref.getString(SAVED_TOKEN, "");
}
// I changed the return type as this is not returning anything.
private void check_token() throws InterruptedException {
String token = load_token();
String result;
Requests request = new Requests(token, this);
request.get_metadata_of_user();
// You will not get the response immediately here. So omit these codes.
// result = request.get_response();
// Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
// return !(result.equals("-1"));
}
#Override
public void onResponseReceived(String response) {
// Here is your response. Now you can use your response
// and can perform the next action here.
}
}
Please note that, the code is not tested. Please modify as per your requirement. I hope that helps you to understand the problem.
How can I call the method "loginprep" of the LoginActivityClass from the FingerPrintClass?
See in the code...I wrote in where I want to call the loginprep with: "//Here I need the method loginprep() from the LoginActivity class"
FingerprintHandler.java
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
// Constructor
public FingerprintHandler(Context mContext) {
context = mContext;
}
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
Toast.makeText((Activity)context, "Fingerprint Authentication error.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
Toast.makeText((Activity)context, "Fingerprint Authentication help.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationFailed() {
Toast.makeText((Activity)context, "Fingerprint Authentication failed.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
//Here I need the method loginprep() from the LoginActivity class
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
public void loginprep() {
SharedPreferences sharedPreferencesF = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPreferencesF.getString("username", "");
String pwd = sharedPreferencesF.getString("password", "");
loginUser(urn, pwd);
}
private void launchHomeScreen() {
Intent homeActivity = new Intent (LoginActivity.this,HomeActivity.class);
LoginActivity.this.startActivity(homeActivity);
finish();
}
public void loginUser(final String urn, final String pwd){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
System.out.println("JSON RESPONSE: " + jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
launchHomeScreen();
pd.dismiss();
Toast.makeText(LoginActivity.this,"Welcome back " + urn,Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("loginDatas", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", urn);
editor.putString("password", pwd);
editor.apply();
}
else {
loginButton.setBackgroundColor(0x73000000);
Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
catch (JSONException e) {
loginButton.setBackgroundColor(0x73000000);
e.printStackTrace();
pd.dismiss();
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loginButton.setBackgroundColor(0x73000000);
pd.dismiss();
System.out.println("Error: " + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put(KEY_USERNAME,urn);
params.put(KEY_PASSWORD,pwd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Following:
MainActivity mActivity = new MainActivity();
this is not the way Android is expecting you to create new instances of an activity, normally you wait the onCreate callback as described in the activity lifeCycle...
no following that approach you will need another way to communicate 2 different activities, what way must be taken depends on the specific arch of your application... the most commonly implemented could be using self defined interfaces and implement you custom callbacks...
You're writing a FingerPrint callback class, which means there is some onAuthenticationSucceeded method that is called when the "authentication succeeds."
How about you implement your own callback to pass back into the LoginActivity?
In other words, you'd
1) Write an interface
public interface LoginListener {
void onLoginSuccess();
void onLoginFailed();
}
2) Have the Activity implements LoginListener and have the Activity method of onLogin do your non-static stuff with the SharedPreferences,
public class LoginActivity extends AppCompatActivity
implements LoginListener {
public static final String KEY_USERNAME = "username";
public static final String KEY_PASS = "password";
private FingerprintHandler fingerprintHandler;
#Override
public void onLoginFailed() { }
#Override
public void onLoginSuccess() {
SharedPreferences sharedPrefs = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPrefs.getString(KEY_USERNAME, "");
String pwd = sharedPrefs.getString(KEY_PASS, "");
loginUser(urn, pwd);
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_login);
fingerprintHandler = new FingerprintHandler(this);
}
// public void loginUser(final String urn, final String pwd){ }
}
3) Expect to pass in a LoginListener as a parameter to that separate class.
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private final Context mContext;
private LoginListener mListener;
// Constructor
public FingerprintHandler(Context context) {
mContext = context;
if (context instanceof LoginListener) {
this.mListener = (LoginListener) context;
} else {
throw new ClassCastException("FingerprintHandler: context must implement LoginListener!");
}
}
4) And you do then can use your callback from the other callback.
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
if (mListener != null) {
mListener.onLoginSuccess();
}
}
I have created two activities. Activity Main has button and on click on this button i m calling method of another class which is extended to AppCompActivity. The method name is mailconfig as shown below. Confidential Information has deleted from parameters.
public class ButtonActionFrontPage extends AppCompatActivity{
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
}
public void mailconfig(String message) throws EmailException {
String username = "";
String password = "";
String from = "";
String replyto = "";
String mailto = "";
String subject = "";
Email email = new SimpleEmail();
email.setSSLOnConnect(true);
email.isStartTLSEnabled();
email.setHostName("");
email.setSmtpPort(26);
email.setSubject(subject);
email.addReplyTo(replyto);
email.setFrom(from);
email.setAuthenticator(new DefaultAuthenticator(username, password));
email.setMsg(message);
email.addTo(mailto);
email.send();
Toast.makeText(ButtonActionFrontPage.this,"Thanks for submitting ",Toast.LENGTH_SHORT).show();
System.out.println("Sent");
}
}
I a using below code to call above method.
feedbackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
ButtonActionFrontPage buttonActionFrontPage = new ButtonActionFrontPage();
String message = quickfbet.getText().toString();
buttonActionFrontPage.mailconfig(message);
} catch (EmailException e) {
e.printStackTrace();
}
}
});
What wrong in this code, why not executing.
Java classes are different with respect to Android Activity. As Android Activity has something called life cycle.
If some functionality has to be implemented, you don't even create an Activity. Just a plain Java class is enough.
Activity can be used when there is an user interaction (infact which is not always true, but purely depends on the business logic). Inorder to initiate an Activity, Intent is used. Which will initiate the activity with memory allocation and other related features.
For your case, the initiation of button should be done in onCreate of ButtonActionFrontPage and through click listener as shown below
Button feedbackbtn;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
feedbackbtn=(Button)findViewById(R.id.button_ID);
feedbackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new PlainJavaClass().mailconfig("msg",ButtonActionFrontPage.class);
}
});
}
For the business logic just use PlainJavaClass with method and context if you have to show any Toast/Dialog/ProgressBar
class PlainJavaClass{
public void mailconfig(String message, Context context) {
Log.v("TAG","mailconfig with message="+message);
//Your logic
Toast.makeText(context,"Thanks for submitting ",Toast.LENGTH_SHORT).show();
}
}
Class would be like this
public class ButtonActionFrontPage {
public void mailconfig(Context context,String message) throws EmailException {
String username = "";
String password = "";
String from = "";
String replyto = "";
String mailto = "";
String subject = "";
Email email = new SimpleEmail();
email.setSSLOnConnect(true);
email.isStartTLSEnabled();
email.setHostName("");
email.setSmtpPort(26);
email.setSubject(subject);
email.addReplyTo(replyto);
email.setFrom(from);
email.setAuthenticator(new DefaultAuthenticator(username, password));
email.setMsg(message);
email.addTo(mailto);
email.send();
Toast.makeText(context,"Thanks for submitting ",Toast.LENGTH_SHORT).show();
System.out.println("Sent");
}
}
And Calling function like this
feedbackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
ButtonActionFrontPage buttonActionFrontPage = new ButtonActionFrontPage();
String message = quickfbet.getText().toString();
buttonActionFrontPage.mailconfig(getApplicationContext(),message);
} catch (EmailException e) {
e.printStackTrace();
}
}
});
public class ButtonActionFrontPage extends AppCompatActivity{
static ButtonActionFrontPage instance;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
instance = this;
}
public static ButtonActionFrontPage getInstance() {
return instance;
}
#Override
protected void onDestroy() {
super.onDestroy();
instance = null;
}
}
and calling the function:
feedbackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
ButtonActionFrontPage buttonActionFrontPage = ButtonActionFrontPage.getInstance(); String message = quickfbet.getText().toString();
buttonActionFrontPage.mailconfig(message);
} catch (EmailException e) {
e.printStackTrace();
}
}
});
I try the same method of initial&update using in Thermostat object to SmokeCOAlarm object but not work.
Does anyone know how to initial&update SmokeCOAlarm object?
or Nest hasn't opened for access SmokeCOAlarm object?!
Following is my code:
public class COSmokeAlarm extends Activity implements
NestAPI.AuthenticationListener, Listener.SmokeCOAlarmListener, Listener.ThermostatListener {
private Listener mUpdateListener;
private NestAPI mNestApi;
private SmokeCOAlarm mSmokeCOAlarm;
private Thermostat mThermostat;
private AccessToken mToken;
TextView txvBattery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_co_smoke_alarm);
txvBattery = (TextView)findViewById(R.id.txvBattery);
mNestApi = NestAPI.getInstance();//Initial NestAPI, connect Firebase
mToken = Settings.loadAuthToken(this);//Loade AccessToken
authenticate(mToken);
}
private void updateBatteryTextView() {
if (mSmokeCOAlarm != null) {
txvBattery.setText(mSmokeCOAlarm.getBatteryHealth());
}
}
private void authenticate(AccessToken token) {
Log.v("COSmokeAlarm", "Authenticating...");
NestAPI.getInstance().authenticate(token, this);
}
#Override
public void onAuthenticationSuccess() {
Log.v("COSmokeAlarm", "Authentication succeeded.");
fetchData();
}
#Override
public void onAuthenticationFailure(int errorCode) {
Log.v("COSmokeAlarm", "Authentication failed with error: " + errorCode);
}
private void fetchData() {
Log.v("COSmokeAlarm", "Fetching data...");
mUpdateListener = new Listener.Builder()
.setSmokeCOAlarmListener(this)
.setThermostatListener(this)
.build();
mNestApi.addUpdateListener(mUpdateListener);
Toast.makeText(COSmokeAlarm.this, "Success fetching data.", Toast.LENGTH_SHORT).show();
}
#Override
public void onSmokeCOAlarmUpdated(#NonNull SmokeCOAlarm smokeCOAlarm) {
Log.v("COSmokeAlarm", String.format("COSmoke Alarm (%s) updated.", smokeCOAlarm.getDeviceID()));
this.mSmokeCOAlarm = smokeCOAlarm;
updateBatteryTextView();
}
#Override
public void onThermostatUpdated(#NonNull Thermostat thermostat) {
Log.v("COSmokeAlarm", String.format("Thermostat (%s) updated.", thermostat.getDeviceID()));
mThermostat = thermostat;
}
}
Go to Nest account and add permission "Smoke+CO alarm read v4"
then we can access SmokeCOAlarm information.