Why is my gmail login not working through firebase - firebase-authentication

I don't know anything about coding and have been learning as I go along
i cant seem to log in via google even though I do show up as active on firebase
can anyone see if I'm missing something?
//Relate to google login
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
if (account != null) {
String id = account.getId();
String fname = "" + account.getGivenName();
String lname = "" + account.getFamilyName();
// if we do not get the picture of user then we will use default profile picture
String pic_url;
if (account.getPhotoUrl() != null) {
pic_url = account.getPhotoUrl().toString();
} else {
pic_url = "null";
}
if (fname.equals("") || fname.equals("null"))
fname = getResources().getString(R.string.app_name);
if (lname.equals("") || lname.equals("null"))
lname = "User";
Change_Url_to_base64(id, fname, lname, pic_url, "gmail");
}
} catch (ApiException e) {
Log.w("Error message", "signInResult:failed code=" + e.getStatusCode());
}
}
public void Change_Url_to_base64(final String user_id,
final String f_name, final String l_name, String picture, final String singnup_type) {
Functions.show_loader(this, false, true);
Log.d(Variables.tag, picture);
if (picture.equalsIgnoreCase("null")) {
Call_Api_For_Signup(user_id, f_name, l_name, picture, singnup_type);
} else {
Glide.with(this)
.asBitmap()
.load(picture)
.into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
String image_base64 = Functions.bitmap_to_base64(Login_A.this, resource);
Call_Api_For_Signup(user_id, f_name, l_name, image_base64, singnup_type);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
}
}
I'm only righting this part because the website keeps telling me that its mostly code and i need to add more details even though i dont know what else to ask or add

Related

RTC Programmatic Creation of Work Items with Plain Java Client

public class CreateWorkItem {
private static class LoginHandler implements ILoginHandler, ILoginInfo {
private String fUserId;
private String fPassword;
private LoginHandler(String userId, String password) {
fUserId= userId;
fPassword= password;
}
public String getUserId() {
return fUserId;
}
public String getPassword() {
return fPassword;
}
public ILoginInfo challenge(ITeamRepository repository) {
return this;
}
}
private static class WorkItemInitialization extends WorkItemOperation {
private String fSummary;
private ICategoryHandle fCategory;
public WorkItemInitialization(String summary, ICategoryHandle category) {
super("Initializing Work Item");
fSummary= summary;
fCategory= category;
}
#Override
protected void execute(WorkItemWorkingCopy workingCopy, IProgressMonitor monitor) throws TeamRepositoryException {
IWorkItem workItem= workingCopy.getWorkItem();
workItem.setHTMLSummary(XMLString.createFromPlainText(fSummary));
workItem.setCategory(fCategory);
}
}
public static void main(String[] args) {
boolean result;
TeamPlatform.startup();
try {
result= run(args);
} catch (TeamRepositoryException x) {
x.printStackTrace();
result= false;
} finally {
TeamPlatform.shutdown();
}
if (!result)
System.exit(1);
}
private static boolean run(String[] args) throws TeamRepositoryException {
if (args.length != 7) {
System.out.println("Usage: CreateWorkItem <repositoryURI> <userId> <password> <projectArea> <workItemType> <summary> <category>");
return false;
}
String repositoryURI= args[0];
String userId= args[1];
String password= args[2];
String projectAreaName= args[3];
String typeIdentifier= args[4];
String summary= args[5];
String categoryName= args[6];
ITeamRepository teamRepository= TeamPlatform.getTeamRepositoryService().getTeamRepository(repositoryURI);
teamRepository.registerLoginHandler(new LoginHandler(userId, password));
teamRepository.login(null);
IProcessClientService processClient= (IProcessClientService) teamRepository.getClientLibrary(IProcessClientService.class);
IAuditableClient auditableClient= (IAuditableClient) teamRepository.getClientLibrary(IAuditableClient.class);
IWorkItemClient workItemClient= (IWorkItemClient) teamRepository.getClientLibrary(IWorkItemClient.class);
URI uri= URI.create(projectAreaName.replaceAll(" ", "%20"));
IProjectArea projectArea= (IProjectArea) processClient.findProcessArea(uri, null, null);
if (projectArea == null) {
System.out.println("Project area not found.");
return false;
}
IWorkItemType workItemType= workItemClient.findWorkItemType(projectArea, typeIdentifier, null);
if (workItemType == null) {
System.out.println("Work item type not found.");
return false;
}
List path= Arrays.asList(categoryName.split("/"));
ICategoryHandle category= workItemClient.findCategoryByNamePath(projectArea, path, null);
if (category == null) {
System.out.println("Category not found.");
return false;
}
WorkItemInitialization operation= new WorkItemInitialization(summary, category);
IWorkItemHandle handle= operation.run(workItemType, null);
IWorkItem workItem= auditableClient.resolveAuditable(handle, IWorkItem.FULL_PROFILE, null);
System.out.println("Created work item " + workItem.getId() + ".");
teamRepository.logout();
return true;
}
}
**This is jazz.net' offical sample code. My question is how can I set value to "categoryName" in "private static boolean run(String[] args) throws TeamRepositoryException" function.In the Main fuction,there is nothing describing the "arg[]".Who can give me a sample to initial "categoryName" argument. **
The category name argument is something that is defined in the RTC CCM project against the timeline or the project. A sample for this is shown below.
These are the values that are expected in the Category Name Argument.
You can look into your project settings to get this information.

Implement Infinite scroll with ViewModel And Retrofit in recyclerview

Before adding viewmodel & livedata , i successfully implemented infinity scroll with retrofit. But after adding viewmodel & livedata with Retrofit, My can't update recyclerview with new data call or viewmodel observer not update the list.
I simply want to infinite scrolling as my code does before. I add a global variable to reuse next page token. Am i missing anything or any sample to implement infinite recyclerview with viewmodel & retrofit will be awesome.
public static String NEXT_PAGE_URL = null;
I coded like that.
My Activity -> PlaceListActivity
placeRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
LogMe.d(tag, "onScrollStateChanged:: " + "called");
// check scrolling started or not
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LogMe.d(tag, "onScrolled:: " + "called");
super.onScrolled(recyclerView, dx, dy);
currentItem = layoutManager.getChildCount();
totalItems = layoutManager.getItemCount();
scrolledOutItems = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
LogMe.d(tag, "currentItem:: " + currentItem);
LogMe.d(tag, "totalItems:: " + totalItems);
LogMe.d(tag, "scrolledOutItems:: " + scrolledOutItems);
if (isScrolling && (currentItem + scrolledOutItems == totalItems)) {
LogMe.d(tag, "view:: " + "finished");
isScrolling = false;
if (ApplicationData.NEXT_PAGE_URL != null) {
LogMe.d(tag, "place adding:: " + " onScrolled called");
ll_loading_more.setVisibility(View.VISIBLE);
// todo: call web api here
callDataFromLocationAPi(type, ApplicationData.NEXT_PAGE_URL, currentLatLng);
} else {
LogMe.d(tag, "next_page_url:: " + " is null");
}
}
}
});
private void callDataFromLocationAPi(String type, String next_page_url, LatLng latLng) {
if (Connectivity.isConnected(activity)) {
showProgressDialog();
model.getNearestPlaces(type, next_page_url, latLng).
observe(activity, new Observer<List<PlaceDetails>>() {
#Override
public void onChanged(#Nullable List<PlaceDetails> placeDetails) {
ll_loading_more.setVisibility(View.GONE);
LogMe.i(tag, "callDataFromLocationAPi: onChanged called !");
hideProgressDialog();
if (placeDetails != null) {
placeDetailsList = placeDetails;
placeListAdapter.setPlaceList(placeDetails);
}
}
});
} else {
showAlertForInternet(activity);
}
}
In PlaceViewModel
public class PlaceViewModel extends AndroidViewModel {
//this is the data that we will fetch asynchronously
private MutableLiveData<List<PlaceDetails>> placeList;
private PlaceRepository placeRepository;
private String tag = getClass().getName();
public PlaceViewModel(Application application) {
super(application);
placeRepository = new PlaceRepository(application);
}
//we will call this method to get the data
public MutableLiveData<List<PlaceDetails>> getNearestPlaces(String type,
String next_page_token,
LatLng latLng) {
//if the list is null
if (placeList == null) {
placeList = new MutableLiveData<>();
//we will load it asynchronously from server in this method
//loadPlaces(type, next_page_token, latLng);
placeList = placeRepository.getNearestPlacesFromAPI(type, next_page_token, latLng);
}
//finally we will return the list
return placeList;
}
}
In my PlaceRepository.java looks
public class PlaceRepository {
private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
// Since we didn't alter the table, there's nothing else to do here.
}
};
private PlaceDatabase placeDatabase;
private CurrentLocation currentLocation = null;
private String tag = getClass().getName();
//this is the data that we will fetch asynchronously
private MutableLiveData<List<PlaceDetails>> placeList;
public PlaceRepository(Context context) {
placeDatabase = PlaceDatabase.getDatabase(context);
//addMigrations(MIGRATION_1_2)
placeList =
new MutableLiveData<>();
}
public MutableLiveData<List<PlaceDetails>> getNearestPlacesFromAPI(String type, final String next_page_token, LatLng latLng) {
List<PlaceDetails> placeDetailsList = new ArrayList<>();
try {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<Example> call = apiService.getNearbyPlaces(type,
latLng.latitude + "," +
latLng.longitude, ApplicationData.PROXIMITY_RADIUS,
ApplicationData.PLACE_API_KEY, next_page_token);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
try {
Example example = response.body();
ApplicationData.NEXT_PAGE_URL = example.getNextPageToken();
// next_page_url = example.getNextPageToken();
LogMe.i(tag, "next_page_url:" + ApplicationData.NEXT_PAGE_URL);
if (example.getStatus().equals("OK")) {
LogMe.i("getNearbyPlaces::", " --- " + response.toString() +
response.message() + response.body().toString());
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < example.getResults().size(); i++) {
Double lat = example.getResults().get(i).getGeometry().getLocation().getLat();
Double lng = example.getResults().get(i).getGeometry().getLocation().getLng();
String placeName = example.getResults().get(i).getName();
String vicinity = example.getResults().get(i).getVicinity();
String icon = example.getResults().get(i).getIcon();
String place_id = example.getResults().get(i).getPlaceId();
PlaceDetails placeDetails = new PlaceDetails();
if (example.getResults().get(i).getRating() != null) {
Double rating = example.getResults().get(i).getRating();
placeDetails.setRating(rating);
}
//List<Photo> photoReference = example.getResults().
// get(i).getPhotos();
placeDetails.setName(placeName);
placeDetails.setAddress(vicinity);
placeDetails.setLatitude(lat);
placeDetails.setLongitude(lng);
placeDetails.setIcon(icon);
placeDetails.setPlace_id(place_id);
//placeDetails.setPlace_type(place_type_title);
double value = ApplicationData.
DISTANCE_OF_TWO_LOCATION_IN_KM(latLng.latitude, latLng.longitude, lat, lng);
//new DecimalFormat("##.##").format(value);
placeDetails.setDistance(new DecimalFormat("##.##").format(value));
String ph = "";
if (example.getResults().
get(i).getPhotos() != null) {
try {
List<Photo> photos = example.getResults().
get(i).getPhotos();
//JSONArray array = new JSONArray(example.getResults().
//get(i).getPhotos());
//JSONObject jsonObj = new JSONObject(array.toString());
//ph = jsonObj.getString("photo_reference");
ph = photos.get(0).getPhotoReference();
//LogMe.i(tag, "\n" + ph);
} catch (Exception e) {
e.printStackTrace();
//placeDetails.setPicture_reference(ph);
//PLACE_DETAILS_LIST.add(placeDetails);
//LogMe.i(tag, "#### Exception Occureed ####");
ph = "";
//continue;
}
}
placeDetails.setPicture_reference(ph);
placeDetailsList.add(placeDetails);
placeList.postValue(placeDetailsList);
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Log.e("onFailure", t.toString());
}
});
} catch (RuntimeException e) {
//hideProgressDialog();
Log.d("onResponse", "RuntimeException is an error");
e.printStackTrace();
} catch (Exception e) {
Log.d("onResponse", "Exception is an error");
}
return placeList;
}
}
I precise code due to question simplicity.
Though you already use android-jetpack, take a look at Paging library. It's specially designed for building infinite lists using RecyclerView.
Based on your source code, I'd say that you need PageKeyedDataSource, here is some example which includes info about how to implement PageKeyedDataSource -
7 steps to implement Paging library in Android
If talking about cons of this approach:
You don't need anymore to observe list scrolling (library doing it for you), you just need to specify your page size in the next way:
PagedList.Config myPagingConfig = new PagedList.Config.Builder()
.setPageSize(50)
.build();
From documentation:
Page size: The number of items in each page.
Your code will be more clear, you'll get rid of your RecyclerView.OnScrollListener
ViewModel code will be shorter, it's will provide only PagedList:
#NonNull
LiveData<PagedList<ReviewSection>> getReviewsLiveData() {
return reviewsLiveData;
}

liferay disable import users after login or check existing users in some groups

I work with liferay-5.2.3 and I integrated LDAP
using this configuration :
in portal-ext.properties I make this lines :
ldap.import.method=group
system.community.roles=TestGr
and in liferay I make this configuration :
I activated the authentication using ldap .
I created two groups in LDAP :
TestGroup1 and TestGroup2
User import is periodic every hour As shown in the configuration
I tried to create Four users in ldap :
user1 under testGroup1
user2 under testGroup2
user3 , user4 out of the two previous groups
Import of users is done correctly : only user1 and user2 will be create in the database of liferay .
The problem is when I tried to authenticate with user3
I found that the user3 is created in the liferay database
Despite the fact that the user3 does not exist in the two groups TestGroup1 and TestGroup2
I think that the solution is to disable import users from ldap after login or also check existing users in some groups before the import ( Which exists in the configuration ).
Updated :
this is the code of LDAPAuth class :
package com.liferay.portal.security.auth;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.PasswordExpiredException;
import com.liferay.portal.UserLockoutException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.User;
import com.liferay.portal.security.ldap.PortalLDAPUtil;
import com.liferay.portal.security.pwd.PwdEncryptor;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PrefsPropsUtil;
import com.liferay.portal.util.PropsValues;
import com.liferay.portlet.admin.util.OmniadminUtil;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LDAPAuth
implements Authenticator
{
public static final String AUTH_METHOD_BIND = "bind";
public static final String AUTH_METHOD_PASSWORD_COMPARE = "password-compare";
public static final String RESULT_PASSWORD_RESET = "2.16.840.1.113730.3.4.4";
public static final String RESULT_PASSWORD_EXP_WARNING = "2.16.840.1.113730.3.4.5";
private static Log _log = LogFactoryUtil.getLog(LDAPAuth.class);
public int authenticateByEmailAddress(long companyId, String emailAddress, String password, Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
throws AuthException
{
try
{
return authenticate(companyId, emailAddress, "", 0L, password);
}
catch (Exception e)
{
_log.error(e, e);
}
throw new AuthException(e);
}
public int authenticateByScreenName(long companyId, String screenName, String password, Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
throws AuthException
{
try
{
return authenticate(companyId, "", screenName, 0L, password);
}
catch (Exception e)
{
_log.error(e, e);
}
throw new AuthException(e);
}
public int authenticateByUserId(long companyId, long userId, String password, Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
throws AuthException
{
try
{
return authenticate(companyId, "", "", userId, password);
}
catch (Exception e)
{
_log.error(e, e);
}
throw new AuthException(e);
}
protected int authenticate(long companyId, String emailAddress, String screenName, long userId, String password)
throws Exception
{
if (!PortalLDAPUtil.isAuthEnabled(companyId)) {
if (_log.isDebugEnabled()) {
_log.debug("Authenticator is not enabled");
}
return 1;
}
if (_log.isDebugEnabled()) {
_log.debug("Authenticator is enabled");
}
if (authenticateOmniadmin(companyId, emailAddress, screenName, userId) == 1)
{
return 1;
}
String baseDN = PrefsPropsUtil.getString(companyId, "ldap.base.dn");
LdapContext ctx = PortalLDAPUtil.getContext(companyId);
if (ctx == null) {
return authenticateRequired(companyId, userId, emailAddress, -1);
}
String filter = PortalLDAPUtil.getAuthSearchFilter(companyId, emailAddress, screenName, String.valueOf(userId));
try
{
SearchControls cons = new SearchControls(2, 1L, 0, null, false, false);
NamingEnumeration enu = ctx.search(baseDN, filter, cons);
SearchResult result;
if (enu.hasMoreElements()) {
if (_log.isDebugEnabled()) {
_log.debug("Search filter returned at least one result");
}
result = (SearchResult)enu.nextElement();
String fullUserDN = PortalLDAPUtil.getNameInNamespace(companyId, result);
Attributes attrs = PortalLDAPUtil.getUserAttributes(companyId, ctx, fullUserDN);
LDAPAuthResult ldapAuthResult = authenticate(ctx, companyId, attrs, fullUserDN, password);
String errorMessage = ldapAuthResult.getErrorMessage();
if (errorMessage != null) {
if (errorMessage.indexOf(PrefsPropsUtil.getString(companyId, "ldap.error.user.lockout")) != -1)
{
throw new UserLockoutException();
}
if (errorMessage.indexOf(PrefsPropsUtil.getString(companyId, "ldap.error.password.expired")) != -1)
{
throw new PasswordExpiredException();
}
}
if (!ldapAuthResult.isAuthenticated()) {
int i = authenticateRequired(companyId, userId, emailAddress, -1);
return i;
}
User user = PortalLDAPUtil.importLDAPUser(companyId, ctx, attrs, password, true);
String resultCode = ldapAuthResult.getResponseControl();
if (resultCode.equals("2.16.840.1.113730.3.4.4")) {
UserLocalServiceUtil.updatePasswordReset(user.getUserId(), true);
}
else if (resultCode.equals("2.16.840.1.113730.3.4.5"))
{
UserLocalServiceUtil.updatePasswordReset(user.getUserId(), true);
}
}
else
{
if (_log.isDebugEnabled()) {
_log.debug("Search filter did not return any results");
}
result = authenticateRequired(companyId, userId, emailAddress, 0);
return result;
}
enu.close();
}
catch (Exception e) {
_log.error("Problem accessing LDAP server: " + e.getMessage());
if (authenticateRequired(companyId, userId, emailAddress, -1) == -1)
{
throw e;
}
}
finally {
if (ctx != null) {
ctx.close();
}
}
return 1;
}
protected LDAPAuthResult authenticate(LdapContext ctx, long companyId, Attributes attrs, String userDN, String password)
throws Exception
{
LDAPAuthResult ldapAuthResult = new LDAPAuthResult();
String authMethod = PrefsPropsUtil.getString(companyId, "ldap.auth.method");
InitialLdapContext innerCtx = null;
if (authMethod.equals("bind")) {
try {
Hashtable env = ctx.getEnvironment();
env.put("java.naming.security.principal", userDN);
env.put("java.naming.security.credentials", password);
env.put("java.naming.referral", PrefsPropsUtil.getString(companyId, "ldap.referral"));
env.put("com.sun.jndi.ldap.connect.pool", "false");
innerCtx = new InitialLdapContext(env, null);
Control[] responseControls = innerCtx.getResponseControls();
ldapAuthResult.setAuthenticated(true);
ldapAuthResult.setResponseControl(responseControls);
}
catch (Exception e) {
if (_log.isDebugEnabled()) {
_log.debug("Failed to bind to the LDAP server with userDN " + userDN + " and password " + password);
}
_log.error("Failed to bind to the LDAP server: " + e.getMessage());
ldapAuthResult.setAuthenticated(false);
ldapAuthResult.setErrorMessage(e.getMessage());
}
finally {
if (innerCtx != null) {
innerCtx.close();
}
}
}
else if (authMethod.equals("password-compare")) {
Attribute userPassword = attrs.get("userPassword");
if (userPassword != null) {
String ldapPassword = new String((byte[])(byte[])userPassword.get());
String encryptedPassword = password;
String algorithm = PrefsPropsUtil.getString(companyId, "ldap.auth.password.encryption.algorithm");
if (Validator.isNotNull(algorithm)) {
encryptedPassword = "{" + algorithm + "}" + PwdEncryptor.encrypt(algorithm, password, ldapPassword);
}
if (ldapPassword.equals(encryptedPassword)) {
ldapAuthResult.setAuthenticated(true);
}
else {
ldapAuthResult.setAuthenticated(false);
if (_log.isWarnEnabled()) {
_log.warn("Passwords do not match for userDN " + userDN);
}
}
}
}
return ldapAuthResult;
}
protected int authenticateOmniadmin(long companyId, String emailAddress, String screenName, long userId)
throws Exception
{
if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
if (userId > 0L) {
if (OmniadminUtil.isOmniadmin(userId)) {
return 1;
}
}
else if (Validator.isNotNull(emailAddress)) {
try {
User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
if (OmniadminUtil.isOmniadmin(user.getUserId()))
return 1;
}
catch (NoSuchUserException nsue)
{
}
}
else if (Validator.isNotNull(screenName)) {
try {
User user = UserLocalServiceUtil.getUserByScreenName(companyId, screenName);
if (OmniadminUtil.isOmniadmin(user.getUserId())) {
return 1;
}
}
catch (NoSuchUserException nsue)
{
}
}
}
return -1;
}
protected int authenticateRequired(long companyId, long userId, String emailAddress, int failureCode)
throws Exception
{
if (PrefsPropsUtil.getBoolean(companyId, "ldap.auth.required"))
{
return failureCode;
}
return 1;
}
}
Is there anyone who can help me to modify this class ( exactly authenticateByEmailAddress methode) in order to check the user's group in ldap in login state
meaning in login methode check user only in :
testGroup1 and testGroup2 and not in all locations in ldap

Accessing activity 2 while foreground is activity 1 (either using OOP or Service in XAMARIN)

i code this from a tutorial for locating your location (but I already made some changes)
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Locations;
using System.Collections.Generic;
using Android.Util;
using System.Linq;
using Java.Lang;
using System.Threading.Tasks;
using System;
using Android.Views;
using Android.Content;
namespace LocatorApp
{
[Activity(Label = "Locator", MainLauncher = true, Icon = "#drawable/locator_ico")]
public class LocatorApp : Activity, ILocationListener
{
static readonly string TAG = "X:" + typeof(LocatorApp).Name;
TextView _addressText;
Location _currentLocation;
LocationManager _locationManager;
Address address;
string _locationProvider;
TextView _locationText;
private double latitude = 0;
private double longitude = 0;
public Location getCurrentLocation() { return _currentLocation; }
public double getLatitude() { return latitude; }
public double getLongitude() { return longitude; }
public Address getAddress() { return address; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_addressText = FindViewById<TextView>(Resource.Id.address_text);
_locationText = FindViewById<TextView>(Resource.Id.location_text);
FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick;
InitializeLocationManager();
}
public void InitializeLocationManager()
{
_locationManager = (LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Coarse,
PowerRequirement = Power.Medium
};
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
else
{
_locationProvider = string.Empty;
}
Log.Debug(TAG, "Using " + _locationProvider + ".");
}
async void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
if (_currentLocation == null)
{
Toast.MakeText(this, "Still waiting for location.", ToastLength.Short).Show();
}
else
{
try
{
var geoUri = Android.Net.Uri.Parse("geo:" + _currentLocation.Latitude + "," + _currentLocation.Longitude);
var mapIntent = new Intent(Intent.ActionView, geoUri);
StartActivity(mapIntent);
}
catch (System.Exception e)
{
Toast.MakeText(this, "Sorry, there is a problem with geomapping.", ToastLength.Short).Show();
}
}
}
async Task<Address> ReverseGeocodeCurrentLocation()
{
try
{
Geocoder geocoder = new Geocoder(this);
IList<Address> addressList =
await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);
Address address = addressList.FirstOrDefault();
return address;
}
catch (System.Exception e)
{
throw;
}
return null;
}
void DisplayAddress(Address address)
{
if (address != null)
{
StringBuilder deviceAddress = new StringBuilder();
for (int i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceAddress.Append(address.GetAddressLine(i));
}
// Remove the last comma from the end of the address.
_addressText.Text = "Address: "+deviceAddress.ToString();
}
else
{
_addressText.Text = "Unable to determine the address. Try again in a few minutes.";
}
}
public async void OnLocationChanged(Location location)
{
Toast.MakeText(this, "Location changed.", ToastLength.Short).Show();
_currentLocation = location;
if (_currentLocation == null)
{
_locationText.Text = "Unable to determine your location. Try again in a short while.";
}
else
{
try
{
_locationText.Text = "Location: " + string.Format("{0:f6},{1:f6}", _currentLocation.Latitude, _currentLocation.Longitude);
Address address = await ReverseGeocodeCurrentLocation();
DisplayAddress(address);
var nMgr = (NotificationManager)GetSystemService(NotificationService);
var notification = new Notification(Resource.Drawable.Icon, "Message from LocatorApp");
var pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(LocatorApp)), 0);
notification.SetLatestEventInfo(this, "LocatorApp", "Location changed!", pendingIntent);
nMgr.Notify(0, notification);
}
catch (Java.Lang.Exception e)
{
_addressText.Text = "Unable to determine the address. Try again in a few minutes.";
Toast.MakeText(this, "Error Occured On Geocoder!", ToastLength.Short).Show();
Log.Error(TAG, e.Message);
}
}
}
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
protected override void OnResume()
{
base.OnResume();
if (_locationManager.IsProviderEnabled(_locationProvider))
{
_locationManager.RequestLocationUpdates(_locationProvider, 100, 0, this);
Toast.MakeText(this, _locationProvider.ToString(), ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "There is a problem with "+_locationProvider.ToString()+" provider.", ToastLength.Short).Show();
}
}
protected override void OnPause()
{
base.OnPause();
_locationManager.RemoveUpdates(this);
}
}
}
(i'm just having my experiment)
what I want is to run activity B while foreground is in activity A, just like a basic OOP . but my problem is, I don't know how to make it run. I can't also jump to activity B since it has an oncreate method. I instantiated it and can get the variables values but they are null (seems there is no process happened) . What can be a best solution for this.
note: I am currently looking how to use service for background processing but also i don't know how to run this code after I typed it from a tutorial :( there is only a tutorial for creating a service part but no tutorial for buttons to access it :(
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using System.Threading;
namespace LocatorApp
{
[Service]
class SimpleService : Service
{
static readonly string TAG = "X:" + typeof(SimpleService).Name;
static readonly int TimerWait = 4000;
Timer _timer;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug(TAG, "OnStartCommand called at {2}, flags={0}, startid={1}", flags, startId, DateTime.UtcNow);
_timer = new Timer(o => { Log.Debug(TAG, "Hello from SimpleService. {0}", DateTime.UtcNow); },
null,
0,
TimerWait);
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
base.OnDestroy();
_timer.Dispose();
_timer = null;
Log.Debug(TAG, "SimpleService destroyed at {0}.", DateTime.UtcNow);
}
public override IBinder OnBind(Intent intent)
{
// This example isn't of a bound service, so we just return NULL.
return null;
}
}
}
I want to know both (OOP way and service way) since not at all time we are required to use the service.
what I want is to run activity B while foreground is in activity A, just like a basic OOP . but my problem is, I don't know how to make it run. I can't also jump to activity B since it has an oncreate method.
You can call Context.StartActivity inside your Activity with following codes:
StartActivity(new Android.Content.Intent(this, typeof(ActivityB)));
And StartActivity will call OnCreate method in ActivityB to create a new instance of ActivityB.
For details about Starting Activities, please refer to Starting Activities and Getting Results.
I am currently looking how to use service for background processing but also i don't know how to run this code after I typed it from a tutorial :( there is only a tutorial for creating a service part but no tutorial for buttons to access it :(
Similar like Activity Context.StartService offers a way to start a Service:
StartService (new Intent (this, typeof(DemoService)));
This will call the OnStartCommand method inside your Service class.
For details about usage of Service, please refer to Implementing a Service.

Writing a mock function for testing a login application

I am making the authentication of my android application, I want to send the entered password & email in json format then my web service is going to test if they are correct then it will return the result in json format also.
But before doing this, I want to make a mock function that replace my webservice and do this just to test before .
Here is the code
After making the validation of interface(Email & password are valid )
mock class
if(fault==false)
//new AttemptLogin().execute();
new GetUser().execute();
My class GetUser is here (the mock class that will replace my web service )
private class GetUser extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String e2=email.getText().toString();
String p2=password.getText().toString();
if (e2 != null && p2!=null) {
try {
JSONObject jsonObj1 = new JSONObject(e2);
JSONObject jsonObj2 =new JSONObject(p2);
UserEmail=jsonObj1.getJSONObject(TAG_Email);
UserPassword=jsonObj2.getJSONObject(TAG_Password);
Toast.makeText(getApplicationContext(),"hi",
Toast.LENGTH_LONG).show();
String c=checkLogin(UserEmail, UserPassword);
Toast.makeText(getApplicationContext(),c,
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String result) {
// dismiss the dialog once product deleted
if (pDialog.isShowing())
pDialog.dismiss();
if (result != null){
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}
And this is the method checkLogin that check if the user has logged with the right email & password .
protected String checkLogin(JSONObject UserEmail,JSONObject UserPassword) {
String e ;
String p;
String r="";
try {
e= UserEmail.getString(TAG_Email);
p = UserPassword.getString(TAG_Password);
if (e.equals("exemple.android#yahoo.fr") &&
p.equals("123456")) {
Toast.makeText(getApplicationContext(), "Hello imene!",
Toast.LENGTH_SHORT).show();
r="ok";
} else {
Toast.makeText(getApplicationContext(), "Seems like you 're not imene!",
Toast.LENGTH_LONG).show();
numberOfRemainingLoginAttempts--;
Toast.makeText(getApplicationContext(), "number of Remaining login Attemts ="+numberOfRemainingLoginAttempts,
Toast.LENGTH_LONG).show();
if (numberOfRemainingLoginAttempts == 0) {
validate.setEnabled(false);
Toast.makeText(getApplicationContext(), "Login Locked!",
Toast.LENGTH_LONG).show();
r="ko";
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return r;
}`
But ,i don't have any result .Can any one tell me where is the problem in my code .