I want to make the login button to dispatch into 2 different activities using the flag column on the database??
if the tenant logged in it will redirect to the tenant activity
and when the landlord is logged in it will redirect to the other activity?
public void onResponse(String response) {
Log.e(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String id = jObj.getString(TAG_ID);
Log.e("Successfully Login!", jObj.toString());
Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_USERNAME, username);
editor.commit();
// go to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
Inside the onClickListener() method of your log in button,you can put a if() statement.
Steps To Do this
1. Get the data from the username and password field and use that in your query to retrieve the data from the database
2. Store the data you retrieved in a String like below because you will get only one row:
String flag = cursor.getString(7); //skipping the cursor and other database part
3. Now you can put the if() statement in the onClickListener of login button after getting the String flag value like:
if(flag.equals(landlord)){
Intent intent = new Intent(this,Landlord.class);
startActivity(intent);
}
else{
Intent intent = new Intent(this,Tenant.class);
startActivity(intent);
}
Anyhow you will be querying to verify username & password, at the same time you could also fetch the flag information and store it in locally(reduces the database calls).
Store those data in a map with key as username (Assumption username will be unique) and flag as value.
Map<String,String> mapToRouting = new Map<String,String>();
Now for routing different activities, inside the button click method try like
public static void buttonClickMethod(){
//textFieldUserName is the username of user trying to login
if(isLanlord(textFieldUserName)){
//this means user is Landlord & put code to redirect to corresponding screen
}
else{
//put code to which redirects to tenants screen!
}
}
Method to find whether the user is landlor or not.
public static void isLandlord(String userName){
boolean result = false;
if(mapToRouting.get(userName).equalsIgnorecase("Landlord"))
result = true;
return result;
}
Hope this will be helpful.
Related
I have created an application that has a registration activity. When I click on the register button on the application, the user's details are inserted into the database but the activity will not change. For the login on the application, the activity changes from the login activity to the home activity as intended, but not for the register activity.
Here is the code:
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Toast.makeText(register.this, response, Toast.LENGTH_SHORT).show();
if (response.equals("success")) {
Toast.makeText(register.this, response, Toast.LENGTH_LONG).show();
btnRegister.setClickable(false);
Intent intent = new Intent(register.this, MainActivity.class);
startActivity(intent);
finish();
} else if (response.equals("failure")) {
tvStatus.setText("Registration unsuccesful!");
Toast.makeText(register.this, response, Toast.LENGTH_SHORT).show();
}
}
}
It seems likely to me that your response isn't what you expect, I haven't used the Listener you used but by looking at some other questions I found this:
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
So please check if this works for you, instead of
if (response.equals("success")) {
this:
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
}else{
}
You might need to add a try/catch around that.
This question already has answers here:
One time login in app - FirebaseAuth
(3 answers)
Closed 1 year ago.
Before you remove my question from stackoverflow, please hear me out.
I know that problem is very common but none that i tried helped me. i already saw available solutions on stackoverflow and other websites but they didn't resolved my issue.
So even if you choose to remove my question from this forum please help me resolve my question first, atleast mail me.
button1.setOnClickListener(view -> {
login();
});
}
public void login() {
Intent intent = new Intent(this, IndexActivity.class);
String mail = et1.getText().toString();
String password = et2.getText().toString();
if (mail.isEmpty()) {
error.setText(e1);
} else if (password.isEmpty()) {
error.setText(e2);
} else if (password.length() < 6) {
error.setText("Invalid Password Length!!");
et2.setError("Password length must be at least 6!!");
} else {
mAuth.signInWithEmailAndPassword(mail, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Welcome Back",Toast.LENGTH_LONG).show();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
error.setText("");
et1.setText("");
et2.setText("");
}
else {
Toast.makeText(MainActivity.this, " "+ Objects.requireNonNull(task.getException()).getMessage(),Toast.LENGTH_LONG).show();
error.setText(e3);
}
});
}
if (error.getText().toString().isEmpty()) {
error.setVisibility(View.INVISIBLE);
} else {
error.setVisibility(View.VISIBLE);
}
}
}
This above is my login page
and below is my child activity
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mAuth.getCurrentUser() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
mAuth.signOut();
startActivity(intent);
finish();
}
else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
});
i have tried everything on internet. sharedPreferences, onBackPressed override, onSaveInstanceState, onRestoreInstanceState, onStart and onResume override, but i don't know what exactly to use.
check if user is already logged in or not by
if (auth.getCurrentUser() != null)
//user logged in already, do your work here for logged in user
else
//user is not logged in, let user login
The back button most likely does not log the user out, but rather the UI elements have not updated with the user information.
If you suspect the user is being logged out, this would be an Auth refresh, which will trigger an onAuthStateChanged() event if you have one registered.
Otherwise, checking the current auth for the current user with auth().currentUser should yield null or a user object
Get current user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
} else {
// No user is signed in
}
Auth State Listener
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
} else {
// User is signed out
}
Log.d("LOG_Login", "onAuthStateChanged:signed_out");
}
}
};
mAuth.addAuthStateListener(mAuthListener);
I need to open external links directly in my in-app browser (Chrome custom tab) without getting prompt to select the browser in my android webview app.
Right now if I am clicking on external links in my app then it prompts me and ask me to select any browser (Chrome, Opera, Edge). If I am clicking on chrome then link opens in Chrome custom tab inside the app, but I want that the prompt should not come and link should directly open in Chrome custom tab (like it happens on Instagram, FB, etc.)
/*--- actions based on URL structure ---*/
public boolean url_actions(WebView view, String url){
boolean a = true;
// show toast error if not connected to the network
if (!ASWP_OFFLINE && !DetectConnection.isInternetAvailable(MainActivity.this)) {
Toast.makeText(getApplicationContext(), getString(R.string.check_connection), Toast.LENGTH_SHORT).show();
// use this in a hyperlink to redirect back to default URL :: href="refresh:android"
} else if (url.startsWith("refresh:")) {
String ref_sch = (Uri.parse(url).toString()).replace("refresh:","");
if(ref_sch.matches("URL")){
CURR_URL = ASWV_URL;
}
pull_fresh();
// use this in a hyperlink to launch default phone dialer for specific number :: href="tel:+919876543210"
} else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
// use this to open your apps page on google play store app :: href="rate:android"
} else if (url.startsWith("rate:")) {
final String app_package = getPackageName(); //requesting app package name from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + app_package)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + app_package)));
}
// sharing content from your webview to external apps :: href="share:URL" and remember to place the URL you want to share after share:___
} else if (url.startsWith("share:")) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, view.getTitle());
intent.putExtra(Intent.EXTRA_TEXT, view.getTitle()+"\nVisit: "+(Uri.parse(url).toString()).replace("share:",""));
startActivity(Intent.createChooser(intent, getString(R.string.share_w_friends)));
// use this in a hyperlink to exit your app :: href="exit:android"
} else if (url.startsWith("exit:")) {
aswm_exit();
// getting location for offline files
} else if (url.startsWith("offloc:")) {
String offloc = ASWV_URL+"?loc="+get_location();
aswm_view(offloc,false, asw_error_counter);
Log.d("OFFLINE LOC REQ",offloc);
// creating firebase notification for offline files
} else if (url.startsWith("fcm:")) {
String fcm = ASWV_URL+"?fcm="+fcm_token();
aswm_view(fcm,false, asw_error_counter);
Log.d("OFFLINE_FCM_TOKEN",fcm);
// opening external URLs in android default web browser
} else if (ASWP_EXTURL && !aswm_host(url).equals(ASWV_HOST) && !url.contains("oauth")) {
aswm_view(url,true, asw_error_counter);
// else return false for no special action
} else {
a = false;
}
return a;
}
//Opening URLs inside webview with request
void aswm_view(String url, Boolean tab, int error_counter) {
if(error_counter > 2){
asw_error_counter = 0;
aswm_exit();
}else {
if(tab){
if(ASWP_TAB) {
CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
intentBuilder.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary));
intentBuilder.setSecondaryToolbarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
intentBuilder.setStartAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
intentBuilder.setExitAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
CustomTabsIntent customTabsIntent = intentBuilder.build();
try {
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(url));
} catch (ActivityNotFoundException e) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
}else{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
} else {
if (url.contains("?")) { // check to see whether the url already has query parameters and handle appropriately.
url += "&";
} else {
url += "?";
}
url += "rid=" + random_id();
asw_view.loadUrl(url);
}
}
}
If I am entering False in "aswm_view(url,true, asw_error_counter);" then the external links open in webview which I don't want to happen.
Thanks in advance, and if required I can share more code.
EDIT: I have added the aswm_view method as per the request
By Viewing your aswm_view method, either ASWP_TAB is going false or MainActivity is not found.
Please check both carefully in aswm_view method.
I'm trying to use the Update Method in Firebase realtime database. Please someone help me figure out how to work it right?
Update Advertisement Method:-
private void UpdateAdvertisement(String tuitionimage, String tuitioname)
{
HashMap userMap = new HashMap();
userMap.put("adstuitionimage", tuitionimage);
userMap.put("adstuitioname", tuitioname);
updateAdvertisement.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if (task.isSuccessful())
{
SendUserToViewAdsActivity();
Toast.makeText(EditAdsActivity.this, "Advertisement has been updated successfully!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(EditAdsActivity.this, "Error occured: Failed to save the updating advertisement data. Please try again.", Toast.LENGTH_LONG).show();
}
}
});
}
For this, we can make use of Intent class:
in your first activity where the data is already present,
ex: String data = edit_text.getText().toString();
So you can write:
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("your_key", "" + data); // Collected from EditText or any other source
...........
........... (You can have similar putExtras as many as you want)
startActivity(i);
then, in your Second Activity class,
in onCreate() method, write
Intent i = getIntent();
String data = i.getStringExtra("your_key"); // This key must be the same as from previous activity
............. (Similarly you can do for all)
Finally, use that data wherever you wish to update in firebase.
Hopefully it should work.
I'm using TextToSpeech to send an sms to someone in my contacts. I use a very ugly way to do it because i need say the all expression "send message to contact text message is hello" in one way. It would be better something like "Send message" and the app ask me to who and go on in this way.. So i can interact with the application like google now in dinamically way. The code i use so far is this one:
if(resultList.getText().toString().toLowerCase().contains(getResources().getString(R.string.messaggio))) //invio sms
{
splitMessage = message.split(getResources().getString(R.string.destinatario), 2);
if(splitMessage.length>1){
if((splitMessage[0].trim()).equalsIgnoreCase(getResources().getString(R.string.inviamessaggio)))
{
splitMessage[0] = "message";
splitMessage[1] = splitMessage[1].trim();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
splitMessageWithNameAndBody = splitMessage[1].split(getResources().getString(R.string.testomessaggio), 2);
if(splitMessageWithNameAndBody.length>1)
{
splitMessage[0] = "text message";
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
splitMessage[1] = splitMessageWithNameAndBody[0].trim();
splitMessageWithNameAndBody[1] = splitMessageWithNameAndBody[1].trim();
if(Name.compareToIgnoreCase(splitMessage[1])== 0)
{
nameMatchFound = true;
flag=1;
String url = "sms:"+Number;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra("sms_body", splitMessageWithNameAndBody[1]);
startActivity(intent);
}
}
if(!nameMatchFound)
{
Toast.makeText(getApplicationContext(), "Contatto non trovato o ci sono piĆ¹ corrispondenze", Toast.LENGTH_SHORT).show();
DialogFragment df=new DialogTrial();
df.show(getSupportFragmentManager(), "MyDialog");
}
} else {
//Toast.makeText(getApplicationContext(), "Please say contact name followed by call or message keyword", Toast.LENGTH_LONG).show();
while (phones.moveToNext()){
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(Name.compareToIgnoreCase(splitMessage[1]) == 0){
nameMatchFound = true;
String url = "sms:"+Number;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra("sms_body", splitMessageWithNameAndBody[1]);
startActivity(intent);
}
}
}
}
else
{
Toast.makeText(getApplicationContext(), "Please say contact name followed by call keyword", Toast.LENGTH_LONG).show();
}
}
//break;
}
if it doesn't find any corrispondance it ask me to search in my contacts the right name. By the way, is what i want do possible? Thanks
Is it possible? Sure. I have an app I wrote that does something similar- it reads out a text, asks if you want to respond, then asks for the response (if yes), then reads it and asks for confirmation before sending. Besically you need to make a state machine so you know how to process a response when it comes in and what to speak out for the next input.