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();
}
}
});
Related
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.
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/
I am creating an android app chatbot using google's dialog flow (API.AI). The problem is, If I am sending text input for my intents,it is giving right response, whereas if same thing I am sending using voice input, am getting wrong response. I am not able to understand what is the problem.
Here is my code :-
public class MyChatActivity extends AppCompatActivity implements View.OnClickListener, AIListener {
public String TAG = this.getClass().getSimpleName();
private List<ChatMessageBean> chatList = new ArrayList<>();
private String CLIENT_ACCESS_TOKEN = "My dialog flow agent's client access token";
AIConfiguration config;
AIService aiService;
AIRequest aiRequest;
AIDataService aiDataService;
TextToSpeech textToSpeech;
RecyclerView chatRecyclerView,menuRecyclerView;
ChatMessageListAdapter chatMessageListAdapter;
FloatingActionButton sendMessageButton,recordMessageButton;
EditText enterMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_chat_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initializeVariables();
setListeners();
}
public void initializeVariables() {
config = new AIConfiguration(CLIENT_ACCESS_TOKEN, AIConfiguration.SupportedLanguages.English, AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(getApplicationContext(), config);
aiRequest = new AIRequest();
aiDataService = new AIDataService(getApplicationContext(), config);
chatRecyclerView = (RecyclerView) findViewById(R.id.chat_list_recycler_view);
setMenuRecyclerView();
enterMessage = (EditText) findViewById(R.id.enter_text_message);
sendMessageButton = (FloatingActionButton) findViewById(R.id.send_message_button);
recordMessageButton =(FloatingActionButton) findViewById(R.id.record_message_button);
textToSpeech = new TextToSpeech(getApplicationContext(),new TextToSpeech.OnInitListener(){
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.US);
}
}
});
}
public void setListeners() {
sendMessageButton.setOnClickListener(this);
aiService.setListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.record_message_button:
aiService.startListening();
break;
case R.id.send_message_button:
String message = enterMessage.getText().toString().trim();
enterMessage.setText("");
sendMessage(message);//sending message with text input
break;
}
}
private boolean validateMessage(String message) {
if ((message.equals("")) || (message.isEmpty()) || (message.length() == 0))
return false;
return true;
}
public void sendMessage(String message) {
// In this method i am sending the message to dialog flow
if (validateMessage(message)) {
ChatMessageBean chatMessageBean = new ChatMessageBean(message); // this is the bean I am using for chatbot app's messages
chatList.add(chatMessageBean);
chatMessageListAdapter = new ChatMessageListAdapter(chatList);// this is the adapter for recycler view that I am using for app's messages
chatRecyclerView.setAdapter(chatMessageListAdapter);
chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
aiRequest.setQuery(message);
new AsyncTask<AIRequest, Void, AIResponse>() {
#Override
protected AIResponse doInBackground(AIRequest... aiRequests) {
final AIRequest request = aiRequests[0];
try {
final AIResponse response = aiDataService.request(aiRequest);
return response;
} catch (AIServiceException e) {
}
return null;
}
#Override
protected void onPostExecute(AIResponse response) {
if (response != null) {
Result result = response.getResult();
String reply = result.getFulfillment().getSpeech();
ChatMessageBean chatMessageBean = new ChatMessageBean(reply.trim());
chatList.add(chatMessageBean);
chatMessageListAdapter = new ChatMessageListAdapter(chatList);
chatRecyclerView.setLayoutManager(new LinearLayoutManager(PersonaAssistantChatActivity.this));
chatRecyclerView.setAdapter(chatMessageListAdapter);
textToSpeech.speak(reply,TextToSpeech.QUEUE_FLUSH,null);
if(reply.trim().equalsIgnoreCase(API_ACCESS_STRING)){ //API_ACCESS_STRING is the string after which I have to get response from my own defined intents. So I am cheking if the reply is equal to API_ACCESS_STRING
String intentName=result.getMetadata().getIntentName();
switch(intentName){
case "AvailableEmployees":
Log.d(TAG, "CallIntents: AvailableEmployees:"+intentName);
String jobName=result.getStringParameter("JobName");
String date = result.getStringParameter("Date");
Log.d(TAG,"JobName:"+jobName+"date: "+date); // When I send voice input here I get jobName="AvailableEmployees" automatically, and dialog flow doesnot ask for jobName, where as with text input I get everything right.
}
}
}
}
}.execute(aiRequest);
} else {
Toast.makeText(getApplicationContext(), "Please enter some text first or record your message", Toast.LENGTH_LONG).show();
}
}
#Override
public void onResult(AIResponse result) {
String message= result.getResult().getResolvedQuery().toString().trim();
sendMessage(message);//sending message with voice input
}
#Override
public void onError(AIError error) {
Log.i(TAG, ": onError" + error);
}
#Override
public void onAudioLevel(float level) {
Log.i(TAG, ": onAudioLevel:" + level);
}
#Override
public void onListeningStarted() {
Log.i(TAG, ": onListeningStarted");
}
#Override
public void onListeningCanceled() {
Log.i(TAG, ": onListeningCanceled");
}
#Override
public void onListeningFinished() {
Log.i(TAG, ": onListeningFinished");
}
}
You can not call sendMessage(message);//sending message with voice input in the onResult method. This method is called when aiService finishes listening and has already sent a request to Dialogflow and you get the response. When you call aiService.startListening(); the service detect what the user is saying and sends it to Dialogflow.
If you want to know the text "aiService" is sending to Dialogflow you have to use PartialResultsListener and implement it:
#Override
public void onPartialResults(final List<String> partialResults) {
if (!partialResults.isEmpty()) {
String partialResult = partialResults.get(0);
}
}
That way you will get what the user says, but be aware as the method will be called BEFORE onListeningFinished() ends.
Best of luck playing with Handler.postDelayed() :)
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'm creating an app in Android using Socket.IO. I am stuck at the Login itself. Here is my code for Login
public class MainActivity extends AppCompatActivity {
EditText uname_et, pwd_et;
Button log;
String username, password;
private Socket mSocket;
private Emitter.Listener onLogin = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(args[0].toString(), "data");
Log.w("yes ", "in evtLogin");
// JSONObject data = (JSONObject) args[0];
}
};
{
try {
String URL = "http://MYIP:8081";
mSocket = IO.socket(URL);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname_et = (EditText) findViewById(R.id.username_input);
pwd_et = (EditText) findViewById(R.id.pwd);
log = (Button) findViewById(R.id.sign_in_button);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i("Make Emit", "Emit");
Log.w(mSocket.connected() + " - ", "Connection status");
}
});
mSocket.on("evtLogin", onLogin);
mSocket.connect();
}
private void signin() {
username = uname_et.getText().toString();
password = pwd_et.getText().toString();
mSocket.emit("userName", username);
mSocket.emit("Password", password);
}
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.off("evtLogin", onLogin);
}
}
I'm not sure that socket is even connected or not, I'm gettong logs from Socket.EVENT_CONNECT
08-31 12:22:22.062 13399-13441/com.fis.kotsocket I/Make Emit﹕ Emit
08-31 12:22:22.063 13399-13441/com.fis.kotsocket W/true -﹕ Connection status
But onLogin listener is not called.
As a newbie I am not sure what to do exactly.
js code
//code for login event
socket.on('evtLogin', function (loginData) {
console.log('loged');
User.findOne({'login.userName':loginData.userName,'login.password':loginData.password},function(err,user){
if(err){throw err;}
else {if(!user){
console.log('not a authenticated user');
}
else
{
var userType;
User.find({'login.userName':loginData.userName,'login.password':loginData.password},function(err,rslt){
if(err){throw err;}
else
{
userType = JSON.stringify(rslt[0]['userType'].userId);
socket.emit('evtUserType',userType);
}
})
}
}
});
console.log('done');
});
Your socket is not getting initialized.
Try this initialization:
private Socket mSocket;
{
try {
mSocket = IO.socket("enter url here");
} catch (URISyntaxException e) {}
}
Or it might be that you are not emitting the evtLogin event from your javascript code.