in android array list is not getting validated - arraylist

sbtbtn.setOnClickListener(new View.OnClickListener()
//try to do validate this array list which coming from CustomAdpater if this Array list is empty then code will return and show the Toast but it showing any Toast Data Inserted
{
#Override
public void onClick(View v) {
final String dbName = "/data/data/" + getClass().getPackage().getName() + "/sync.bdb.db";
if (productListAdapter.getList().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Please insert data into list", Toast.LENGTH_SHORT).show();
return;
}
helper.savePurchaseList(productListAdapter.getList(), invoiceNo.getText().toString());
Toast.makeText(getApplicationContext(), "Data Inserted", Toast.LENGTH_SHORT).show();
}
}
);

Related

startactivityforresult deprecated java and how I can use requestcodes

I'm trying to capture image & display in imageview and pick image from gallery to image view. So, I have to different requestcodes but startactivityforresult deprecated, and so, ı use that:
ActivityResultLauncher<Intent> startActivityIntent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
// Add same code that you want to add in onActivityResult method
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_PERM_CODE){
Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
File f = new File(currentPhotoPath);
selectedImage.setImageURI(Uri.fromFile(f));
Log.d("tag","Absolute Uri of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);}
if(requestCode == GALLERY_PERM_CODE){
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
Uri contentUri = data.getData();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(contentUri);
Log.d("tag","Absolute Uri of Image is " + imageFileName);
selectedImage.setImageURI(contentUri);
}
}
How can I add requestcodes in ActivityResultLauncher? or are there other ways to do that?

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;
}

Google Play Sign in Failure Api Exception 4

Im trying to integrate google sign in and took the code from another project that it works on, but for the new app it goes thru the log in but the dialog to allow doesnt show up and instead I get sign in failure with Api Exception 4.
Here is all the applicable code:
//Create the client used to sign in to Google services
mGoogleSignInClient = GoogleSignIn.getClient(this,
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode(getString(R.string.client_id))
.requestEmail()
.build());
private void signInSilently(){
Log.d(TAG, "signInSilently()");
mGoogleSignInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInSilently(): success");
onConnected(task.getResult());
} else {
Log.d(TAG, "signInSilently(): failure", task.getException());
onDisconnected();
}
}
});
}
private void startSignInIntent() {
startActivityForResult(mGoogleSignInClient.getSignInIntent(), RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task =
GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
onConnected(account);
} catch (ApiException apiException) {
String message = apiException.getMessage();
if (message == null || message.isEmpty()) {
message = getString(R.string.signin_other_error);
}
onDisconnected();
new AlertDialog.Builder(this)
.setMessage(message)
.setNeutralButton(android.R.string.ok, null)
.show();
}
}
}
private void onDisconnected() {
Log.d(TAG, "onDisconnected()");
mPlayersClient = null;
// Show sign-in button on main menu
if(game.user != null) {
game.user.setDisplayName(null);
game.user.setPlayerID(null);
}
}
private void onConnected(final GoogleSignInAccount googleSignInAccount) {
Log.d(TAG, "onConnected(): connected to Google APIs");
GamesClient gamesClient = Games.getGamesClient(AndroidLauncher.this, googleSignInAccount);
View view = ((AndroidGraphics) Gdx.graphics).getView();
gamesClient.setViewForPopups(view);
gamesClient.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
mPlayersClient = Games.getPlayersClient(this, googleSignInAccount);
// Set the greeting appropriately on main menu
mPlayersClient.getCurrentPlayer()
.addOnCompleteListener(new OnCompleteListener<Player>() {
#Override
public void onComplete(#NonNull Task<Player> task) {
String displayName;
if (task.isSuccessful()) {
user = new User();
user.setDisplayName(task.getResult().getDisplayName());
user.setPlayerID(task.getResult().getPlayerId());
game.user = user;
firebaseAuthWithPlayGames(googleSignInAccount);
} else {
Exception e = task.getException();
handleException(e, getString(R.string.players_exception));
displayName = "???";
}
}
});
}
private void handleException(Exception e, String details) {
int status = 0;
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
status = apiException.getStatusCode();
}
String message = getString(R.string.status_exception_error, details, status, e);
new AlertDialog.Builder(AndroidLauncher.this)
.setMessage(message)
.setNeutralButton(android.R.string.ok, null)
.show();
}

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 .

Current location on map using WIFI in android

i just need to find the current location on maps using WIFI.I used tha below code to do that.
My code:
public class LocationActivity extends MapActivity implements LocationListener {
private MapView mapView;
private LocationManager locationManager;
private String latitude,longtitude;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getIntent().getExtras();
latitude = bundle.getString("latitude");
longtitude = bundle.getString("longtitude");
setContentView(R.layout.locationtab);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
locationIdentifier();
}
private void createMyLocOverlay(Double latitude, Double longtitude) {
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.mylocation);
GeoPoint point = new GeoPoint((int) (latitude * 1E6),
(int) (longtitude * 1E6));
OverlayItem overlayitem = new OverlayItem(point, null, "You are here!");
MyLocationOverlay itemizedoverlay = new MyLocationOverlay(drawable,
this);
itemizedoverlay.addOverlay(overlayitem);
MyLocationOverlay overlayToRemove = null;
for (Overlay overlay : mapOverlays) {
if (overlay instanceof MyLocationOverlay) {
overlayToRemove = (MyLocationOverlay) overlay;
}
}
if (overlayToRemove != null) {
mapOverlays.remove(overlayToRemove);
}
mapOverlays.add(itemizedoverlay);
}
public void locationIdentifier() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria,true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
createMyLocOverlay(location.getLatitude(), location.getLongitude());
Toast.makeText(
this,
"Latitude : " + location.getLatitude() + " : Longtitude : "
+ location.getLongitude(), Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this, "Latitude/Longtitude not found",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
createMyLocOverlay(location.getLatitude(), location.getLongitude());
Toast.makeText(
this,
"LocationChanged Latitude : " + location.getLatitude()
+ " Longtitude : " + location.getLongitude(),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Location is null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_LONG)
.show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
How could i check it on emulator whether its working or not.?
For now, It is not possible to simulate it using emulator because it is simply doesn't support it. As alternative, you may put a flag constant (e.g. DEBUG=false/true) then if DEBUG=true, use the constant location otherwise use WIFI location.
Or use location provider which can support IP Address location. Which you can use as alternative if DEBUG=true.