android scrolling not set to previous position - java

I have a listview with 400 items, however, when I'm on item 100 etc, I press down it would go down and all that neat stuff, but the viewing goes back to the top while keeping my item 100 selected... Here is what it's doing: http://im.ezgif.com/tmp/ezgif-2788305924.gif
How do I prevent his? Here is what I have:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
try{
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
} catch (Exception e){
Log.e("Menu", "Full screen not supported under API 19 (4.4 KitKat)");
}
mainLinearLayout = (LinearLayout) findViewById(R.id.mainLinearLayout);
listView = (ListView) findViewById(R.id.listView);
listView.setItemsCanFocus(false);
listView.setDivider(null);
listView.setFocusable(false);
listView.setDividerHeight(0);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Channel channel = channels.get(position);
if (position == menuAdapter.getSelectedPosition()) {
if ((new Random(System.currentTimeMillis())).nextBoolean()) {
openChannel(channel);
} else {
tempChannel = channel;
Log.i("Menu", "Playing ad");
if (interstitialAd.isLoaded())
interstitialAd.show();
}
} else {
menuAdapter.setSelectedPosition(position, listView);
}
Picasso.with(mainActivity).load(channel.artUrl).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapDrawable bmDrawable = new BitmapDrawable(getResources(), bitmap);
if (bmDrawable != null)
bmDrawable.setAlpha(80);
mainLinearLayout.setBackground(bmDrawable);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
});
mainActivity = this;
bannerAd = new AdView(this);
bannerAd.setAdSize(AdSize.BANNER);
bannerAd.setAdUnitId(getAdmobBannerId());
AdRequest adRequest = new AdRequest.Builder().build();
bannerAd.loadAd(adRequest);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getAdmobIntersitialId());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
openChannel(tempChannel);
}
});
interstitialAd.loadAd((new AdRequest.Builder()).build());
mainLinearLayout.addView(bannerAd, 0);
new WebServiceJob().execute();
}
public String getAdmobBannerId() {
SharedPreferences preferences = getSharedPreferences("YTApp", MODE_PRIVATE);
String result = preferences.getString("admob_banner", null);
if (result == null) {
String defaultID = "ca-app-pub-";
preferences.edit().putString("admob_banner", defaultID).apply();
return defaultID;
}
return result;
}
public String getAdmobIntersitialId() {
SharedPreferences preferences = getSharedPreferences("YTApp", MODE_PRIVATE);
String result = preferences.getString("admob_intersitial", null);
if (result == null) {
String defaultID = "ca-app-pub4";
preferences.edit().putString("admob_intersitial", defaultID).apply();
return defaultID;
}
return result;
}
public void artDownloaded(){
numArtDownloaded++;
if(numArtDownloaded == channels.size())
updateUIWithScroll();
}
public void updateUIWithScroll(){
updateUI();
if(!menuAdapter.isScrolling) {
menuAdapter.isScrolling = true;
listView.post(new Runnable() {
#Override
public void run() {
Log.i("Menu", "Scrolling");
listView.smoothScrollToPosition(menuAdapter.getSelectedPosition());
menuAdapter.isScrolling = false;
}
});
}
}
public void updateUI() {
try {
ArrayList<String> channelNames = new ArrayList<>();
for (Channel channel : channels)
channelNames.add(channel.title);
menuAdapter = new MenuAdapter(this, R.layout.listitemright, channelNames, getSharedPreferences("YTApp", MODE_PRIVATE).getInt("selectedChannelNr", -1));
listView.setAdapter(menuAdapter);
if (menuAdapter.getSelectedPosition() != -1) {
Picasso.with(mainActivity).load(channels.get(menuAdapter.getSelectedPosition()).artUrl).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapDrawable bmDrawable = new BitmapDrawable(getResources(), bitmap);
if (bmDrawable != null)
bmDrawable.setAlpha(80);
mainLinearLayout.setBackground(bmDrawable);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
} catch (Exception e){}
}

Related

OnLocationChanged never called android studio LocationListener GoogleApiClient

I'm developing a taxi application. The only problem is my marker doesn't update it's location screamingly on mapview. After some debugging I noticed that the listener named onLocationChanged is never called!!!
The idea is to view a marker on mapview to view driver's location and track is own location while driver. But, the problem is his marker never changes!.
Here is my code:
public class HomeFragment extends FragmentManagePermission implements OnMapReadyCallback, DirectionCallback, Animation.AnimationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public String NETWORK;
public String ERROR = "حدث خطأ";
public String TRYAGAIN;
Boolean flag = false;
GoogleMap myMap;
ImageView current_location, clear;
MapView mMapView;
int i = 0;
String result = "";
Animation animFadeIn, animFadeOut;
String TAG = "home";
LinearLayout linear_request;
String permissionAsk[] = {
PermissionUtils.Manifest_CAMERA,
PermissionUtils.Manifest_WRITE_EXTERNAL_STORAGE,
PermissionUtils.Manifest_READ_EXTERNAL_STORAGE,
PermissionUtils.Manifest_ACCESS_FINE_LOCATION,
PermissionUtils.Manifest_ACCESS_COARSE_LOCATION
};
CardView rides, earnings;
private String driver_id = "";
private String cost = "";
private String unit = "";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Double currentLatitude;
private Double currentLongitude;
private View rootView;
private String check = "";
private String drivername = "";
private Marker my_marker;
private boolean isShown = true;
private FusedLocationProviderClient fusedLocationProviderClient;
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fusedLocationProviderClient = new FusedLocationProviderClient(requireContext());
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
NETWORK = getString(R.string.network_not_available);
TRYAGAIN = getString(R.string.tryagian);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
rootView = inflater.inflate(R.layout.home_fragment, container, false);
// globatTitle = "Home";
((HomeActivity) getActivity()).fontToTitleBar(getString(R.string.home));
bindView(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askCompactPermissions(permissionAsk, new PermissionResult() {
#Override
public void permissionGranted() {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
#Override
public void permissionDenied() {
}
#Override
public void permissionForeverDenied() {
openSettingsApp(getActivity());
}
});
} else {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
} catch (Exception e) {
Log.e("tag", "Inflate exception " + e.toString());
}
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
getCurrentlOcation();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
#Override
public void onPause() {
super.onPause();
try {
if (getActivity() != null && mMapView != null) {
mMapView.onPause();
}
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
if (mMapView != null) {
mMapView.onDestroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
try {
if (mMapView != null) {
mMapView.onSaveInstanceState(outState);
}
} catch (Exception e) {
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
try {
if (mMapView != null) {
mMapView.onLowMemory();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
super.onStop();
try {
if (mMapView != null) {
mMapView.onStop();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
} catch (Exception e) {
}
}
#Override
public void onResume() {
super.onResume();
try {
if (mMapView != null) {
mMapView.onResume();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
} catch (Exception e) {
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onMapReady(GoogleMap googleMap) {
myMap = googleMap;
myMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(final Marker marker) {
View v = null;
if (getActivity() != null) {
v = getActivity().getLayoutInflater().inflate(R.layout.view_custom_marker, null);
TextView title = (TextView) v.findViewById(R.id.t);
TextView t1 = (TextView) v.findViewById(R.id.t1);
TextView t2 = (TextView) v.findViewById(R.id.t2);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "font/AvenirLTStd_Medium.otf");
t1.setTypeface(font);
t2.setTypeface(font);
String name = marker.getTitle();
title.setText(name);
String info = marker.getSnippet();
t1.setText(info);
driver_id = (String) marker.getTag();
drivername = marker.getTitle();
}
return v;
}
});
if (myMap != null) {
tunonGps();
}
}
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
}
#Override
public void onDirectionFailure(Throwable t) {
}
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
public void bindView(Bundle savedInstanceState) {
MapsInitializer.initialize(this.getActivity());
mMapView = (MapView) rootView.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
// load animations
animFadeIn = AnimationUtils.loadAnimation(getActivity(),
R.anim.dialogue_scale_anim_open);
animFadeOut = AnimationUtils.loadAnimation(getActivity(),
R.anim.dialogue_scale_anim_exit);
animFadeIn.setAnimationListener(this);
animFadeOut.setAnimationListener(this);
rides = (CardView) rootView.findViewById(R.id.cardview_totalride);
earnings = (CardView) rootView.findViewById(R.id.earnings);
Utils.overrideFonts(getActivity(), rootView);
getEarningInfo();
}
public void getEarningInfo() {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
RequestParams params = new RequestParams();
if (Utils.haveNetworkConnection(getActivity())) {
params.put("driver_id", SessionManager.getUserId());
}
Server.setHeader(SessionManager.getKEY());
Server.get(Server.EARN, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("earn", response.toString());
try {
if (response.has("status") && response.getString("status").equalsIgnoreCase("success")) {
if (response.getJSONObject("data").getJSONObject("request").length() != 0) {
Gson gson = new Gson();
PendingRequestPojo pojo = gson.fromJson(response.getJSONObject("data").getJSONObject("request").toString(), PendingRequestPojo.class);
((HomeActivity) getActivity()).setPojo(pojo);
((HomeActivity) getActivity()).setStatus(pojo, "", false);
}
String today_earning = response.getJSONObject("data").getString("today_earning");
String week_earning = response.getJSONObject("data").getString("week_earning");
String total_earning = response.getJSONObject("data").getString("total_earning");
String total_rides = response.getJSONObject("data").getString("total_rides");
try {
String unit = response.getJSONObject("data").getString("unit");
//SessionManager.getInstance().setUnit(unit);
} catch (JSONException e) {
}
TextView textView_today = (TextView) rootView.findViewById(R.id.txt_todayearning);
TextView textView_week = (TextView) rootView.findViewById(R.id.txt_weekearning);
TextView textView_overall = (TextView) rootView.findViewById(R.id.txt_overallearning);
TextView textView_totalride = (TextView) rootView.findViewById(R.id.txt_total_ridecount);
textView_today.setText(today_earning);
textView_week.setText(week_earning);
textView_overall.setText(total_earning);
textView_totalride.setText(total_rides);
} else {
Toast.makeText(getActivity(), response.getString("data"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), getString(R.string.error_occurred), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFinish() {
super.onFinish();
if (progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#SuppressWarnings({"MissingPermission"})
#Override
public void onConnected(#Nullable Bundle bundle) {
try {
android.location.Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
if (myMap != null) {
myMap.clear();
my_marker = myMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Your are here."));
my_marker.showInfoWindow();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15);
myMap.animateCamera(cameraUpdate);
myMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (isShown) {
isShown = false;
rides.startAnimation(animFadeOut);
rides.setVisibility(View.GONE);
earnings.startAnimation(animFadeOut);
earnings.setVisibility(View.GONE);
} else {
isShown = true;
rides.setVisibility(View.VISIBLE);
rides.startAnimation(animFadeIn);
earnings.setVisibility(View.VISIBLE);
earnings.startAnimation(animFadeIn);
}
}
});
}
setCurrentLocation(currentLatitude, currentLongitude);
}
} catch (Exception e) {
}
}
public void setCurrentLocation(final Double lat, final Double log) {
try {
my_marker.setPosition(new LatLng(lat, log));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15);
myMap.animateCamera(cameraUpdate);
RequestParams par = new RequestParams();
Server.setHeader(SessionManager.getKEY());
par.put("user_id", SessionManager.getUserId());
par.add("latitude", String.valueOf(currentLatitude));
par.add("longitude", String.valueOf(currentLongitude));
Server.post(Server.UPDATE, par, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
});
} catch (Exception e) {
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
#Override
public void onLocationChanged(android.location.Location location) {
if (location != null) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
if (!currentLatitude.equals(0.0) && !currentLongitude.equals(0.0)) {
setCurrentLocation(currentLatitude, currentLongitude);
} else {
Toast.makeText(getActivity(), getString(R.string.couldnt_get_location), Toast.LENGTH_LONG).show();
}
}
}
public void getCurrentlOcation() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
}
public void tunonGps() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
// **************************
builder.setAlwaysShow(true); // this is the key ingredient
// **************************
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result
.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can
// initialize location
// requests here.
getCurrentlOcation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be
// fixed by showing the user
// a dialog.
try {
// Show the dialog by calling
// startResolutionForResult(),
// and checkky the result in onActivityResult().
status.startResolutionForResult(getActivity(), 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have
// no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
}
public Boolean GPSEnable() {
GPSTracker gpsTracker = new GPSTracker(getActivity());
if (gpsTracker.canGetLocation()) {
return true;
} else {
return false;
}
}
}
What's the problem with my code?

Update recycler view when a item is deleted on onBindViewHolder listener

I'm having a problem, that maybe we can solve it and help the community. I have made an Adapter for my RecyclerView and I have created a listener for the constraint layout in order to remove one element of the list. As you can see in the code the delete message works well but I don't know how to update the RecyclerView from the AccountFragment (the one that's using this adapter). Does anyone know how to notify that changes?
AccountFragment:
public class AccountFragment extends Fragment {
private TextView textViewUserProfileUsername;
private TextView textViewUserProfileDescription;
private ImageButton imageButtonAccountEdit;
private EditText editTextAccountDescription;
private RecyclerView recyclerViewUserProfileComments;
private TextView textViewUserProfileNoComments;
private ImageView imageViewUserProfileSendMessage;
private EditText editTextUserProfileSendMessage;
private final Gson gson = new Gson();
private User userLocal;
private SharedPreferences sharedPreferences;
private Context context;
private AlertDialog dialog;
private String previousDescription;
private AccountCommentsAdapter accountCommentsAdapter;
private final List<UserComments> userCommentsList = new ArrayList<>();
public AccountFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
assert context != null;
sharedPreferences = context.getSharedPreferences(Constants.sharedPreferencesDocName, Context.MODE_PRIVATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_account, container, false);
}
#Override
public void onViewCreated(#NonNull #NotNull View view, #Nullable #org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bindUI(view);
setListeners();
userLocal = gson.fromJson(sharedPreferences.getString("user", ""), User.class);
showUserInformation();
setAdapter();
}
private void bindUI(View view) {
textViewUserProfileUsername = view.findViewById(R.id.textViewUserProfileUsername);
textViewUserProfileDescription = view.findViewById(R.id.textViewUserProfileDescription);
imageButtonAccountEdit = view.findViewById(R.id.imageButtonAccountEdit);
recyclerViewUserProfileComments = view.findViewById(R.id.recyclerViewUserProfileComments);
textViewUserProfileNoComments = view.findViewById(R.id.textViewUserProfileNoComments);
imageViewUserProfileSendMessage = view.findViewById(R.id.imageViewUserProfileSendMessage);
editTextUserProfileSendMessage = view.findViewById(R.id.editTextUserProfileSendMessage);
}
private void setListeners() {
imageButtonAccountEdit.setOnClickListener(v -> showEditDescriptionDialog());
imageViewUserProfileSendMessage.setOnClickListener(view -> {
if (!TextUtils.isEmpty(editTextUserProfileSendMessage.getText().toString())) {
final Date currentTime = new Date();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
TimeZone timeZone = simpleDateFormat.getTimeZone();
simpleDateFormat.setTimeZone(timeZone);
String date = simpleDateFormat.format(currentTime);
final UserComments userCommentsToAdd = new UserComments(userLocal.getId(), userLocal.getId(), userLocal.getUsername(), userLocal.getUsername(), editTextUserProfileSendMessage.getText().toString().trim(), date);
editTextUserProfileSendMessage.setText("");
addComment(userCommentsToAdd);
}
});
}
private void showUserInformation() {
textViewUserProfileUsername.setText(userLocal.getUsername());
textViewUserProfileDescription.setText(userLocal.getDescription());
getUserComments();
}
private void showEditDescriptionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(getString(R.string.edit_description));
final View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog_edit_account, null);
builder.setView(customLayout);
dialog = builder.create();
editTextAccountDescription = customLayout.findViewById(R.id.editTextAccountDescription);
if (userLocal.getDescription() != null) {
editTextAccountDescription.setText(userLocal.getDescription());
previousDescription = editTextAccountDescription.getText().toString();
}
Button buttonAccountCancelDescription = customLayout.findViewById(R.id.buttonAccountCancelDescription);
Button buttonAccountSaveDescription = customLayout.findViewById(R.id.buttonAccountSaveDescription);
buttonAccountSaveDescription.setOnClickListener(v -> saveUserDescription());
buttonAccountSaveDescription.setOnClickListener(v -> {
if (editTextAccountDescription.getText().toString().length() <= 150) {
saveUserDescription();
} else {
setErrors(2);
}
});
editTextAccountDescription.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 150) {
setErrors(2);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
buttonAccountCancelDescription.setOnClickListener(v -> dialog.dismiss());
dialog.setCancelable(false);
dialog.show();
}
private void saveUserDescription() {
if (!editTextAccountDescription.getText().toString().isEmpty()) {
if (!editTextAccountDescription.getText().toString().equals(previousDescription)) {
userLocal.setDescription(editTextAccountDescription.getText().toString());
sharedPreferences.edit().putString("user", gson.toJson(userLocal)).apply();
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserRequests.editUserDescription(userLocal.getId(), userLocal.getDescription());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
updateDescription();
} else if (responseBody.contains("2")) {
updateDescription();
} else {
setErrors(1);
}
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
} else {
setErrors(4);
}
} else {
setErrors(3);
}
}
private void updateDescription() {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
textViewUserProfileDescription.setText(userLocal.getDescription());
dialog.dismiss();
});
}
};
thread.start();
}
private void setErrors(int error) {
switch (error) {
case 1:
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> Toast.makeText(context, getString(R.string.generic_error), Toast.LENGTH_SHORT).show());
}
};
thread.start();
break;
case 2:
editTextAccountDescription.setError(getString(R.string.description_length));
editTextAccountDescription.requestFocus();
break;
case 3:
editTextAccountDescription.setError(getString(R.string.required_field));
editTextAccountDescription.requestFocus();
break;
case 4:
dialog.dismiss();
break;
}
}
private void setAdapter() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setStackFromEnd(true);
recyclerViewUserProfileComments.setLayoutManager(linearLayoutManager);
recyclerViewUserProfileComments.scrollToPosition(userCommentsList.size() - 1);
}
private void displayMessages() {
if (userCommentsList.size() > 0) {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
if (recyclerViewUserProfileComments.getVisibility() == View.GONE) {
recyclerViewUserProfileComments.setVisibility(View.VISIBLE);
}
if (textViewUserProfileNoComments.getVisibility() == View.VISIBLE) {
textViewUserProfileNoComments.setVisibility(View.GONE);
}
accountCommentsAdapter = new AccountCommentsAdapter(context, userCommentsList);
recyclerViewUserProfileComments.setAdapter(accountCommentsAdapter);
recyclerViewUserProfileComments.scrollToPosition(userCommentsList.size() - 1);
accountCommentsAdapter.notifyDataSetChanged();
});
}
};
thread.start();
} else {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
recyclerViewUserProfileComments.setVisibility(View.GONE);
textViewUserProfileNoComments.setVisibility(View.VISIBLE);
});
}
};
thread.start();
}
}
private void addComment(UserComments userCommentsToAdd) {
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.addUserComment(userCommentsToAdd);
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
userCommentsList.add(userCommentsToAdd);
userCommentsList.clear();
getUserComments();
}
} else if (response.code() == 204) {
displayMessages();
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
private void getUserComments() {
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.getUserComments(userLocal.getId());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
JSONArray responseArray = new JSONArray(responseBody);
for (int i = 0; i < responseArray.length(); i++) {
String jsonObjectString = responseArray.getJSONObject(i).toString();
userCommentsList.add(gson.fromJson(jsonObjectString, UserComments.class));
}
displayMessages();
} else if (response.code() == 204) {
displayMessages();
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
}
AccountCommentsAdapter:
public class AccountCommentsAdapter extends RecyclerView.Adapter<AccountCommentsAdapter.AccountCommentsAdapterViewHolder> {
private final Context context;
List<UserComments> userCommentsList;
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
public AccountCommentsAdapter(Context context, List<UserComments> userCommentsList) {
this.context = context;
this.userCommentsList = userCommentsList;
}
#NonNull
#NotNull
#Override
public AccountCommentsAdapterViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view;
if (viewType == MSG_TYPE_RIGHT) {
view = LayoutInflater.from(context).inflate(R.layout.fragment_chat_message_sent, parent, false);
} else {
view = LayoutInflater.from(context).inflate(R.layout.fragment_chat_message_received, parent, false);
}
return new AccountCommentsAdapterViewHolder(view);
}
#Override
public int getItemViewType(int position) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert firebaseUser != null;
if (userCommentsList.get(position).getUser_from_username().equals(firebaseUser.getDisplayName())) {
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
#Override
public void onBindViewHolder(#NonNull #NotNull AccountCommentsAdapterViewHolder holder, int position) {
UserComments userComments = userCommentsList.get(position);
int viewType = holder.getItemViewType();
if (viewType == MSG_TYPE_LEFT) {
holder.textViewMessageUsername.setText(userComments.getUser_from_username());
holder.textViewMessageUsername.setOnClickListener(v -> {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putString("userId", userComments.getUser_from_id());
bundle.putString("username", userComments.getUser_from_username());
intent.putExtras(bundle);
context.startActivity(intent);
});
holder.constraintLayoutMessageRight.setOnLongClickListener(v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.delete_message)
.setPositiveButton(R.string.yes, (dialogInterface, i) -> deleteMessage(position))
.setNegativeButton(R.string.no, (dialogInterface, which) -> dialogInterface.dismiss());
builder.create();
builder.show();
return false;
});
} else {
holder.constraintLayoutMessageRight.setOnLongClickListener(v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.delete_message)
.setPositiveButton(R.string.yes, (dialogInterface, i) -> deleteMessage(position))
.setNegativeButton(R.string.no, (dialogInterface, which) -> dialogInterface.dismiss());
builder.create();
builder.show();
return false;
});
}
holder.textViewMessageMessage.setText(userComments.getMessage());
holder.textViewMessageTime.setText(userComments.getCreated_time());
}
#Override
public int getItemCount() {
return userCommentsList.size();
}
public static class AccountCommentsAdapterViewHolder extends RecyclerView.ViewHolder {
ConstraintLayout constraintLayoutMessageRight;
TextView textViewMessageMessage;
TextView textViewMessageTime;
TextView textViewMessageUsername;
public AccountCommentsAdapterViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
textViewMessageMessage = itemView.findViewById(R.id.textViewMessageMessage);
textViewMessageTime = itemView.findViewById(R.id.textViewMessageTime);
constraintLayoutMessageRight = itemView.findViewById(R.id.constraintLayoutMessageRight);
textViewMessageUsername = itemView.findViewById(R.id.textViewMessageUsername);
}
}
private void deleteMessage(int position) {
UserComments userCommentsToRemove = userCommentsList.get(position);
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.removeUserComments(userCommentsToRemove.getId());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
userCommentsList.remove(position);
// Here it should update the recyclerview in order to notify that element has been removed.
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
}
UPDATE:
Solved by adding this method and then call it after userCommentsList.remove(position):
private void updateUI(){
Handler mainHandler = new Handler(context.getMainLooper());
Runnable runnable = this::notifyDataSetChanged;
mainHandler.post(runnable);
}
Inside the adapter you can use notifyDataSetChanged()

How to allow multiple windows on webview to get facebook login working?

I'm creating an app for my website and need to when you click on external links like facebook and google login you get a new window tab that closes after login.
I`ve added mWebView.getSettings().setSupportMultipleWindows(true); but now when I click on the link nothing happens
MainFragment.java
public class MainFragment extends TaskFragment implements SwipeRefreshLayout.OnRefreshListener, AdvancedWebView.Listener {
private static final String ARGUMENT_URL = "url";
private static final String ARGUMENT_SHARE = "share";
private static final int REQUEST_FILE_PICKER = 1;
private boolean mProgress = false;
private View mRootView;
private StatefulLayout mStatefulLayout;
private AdvancedWebView mWebView;
private String mUrl = "about:blank";
private String mShare;
private boolean mLocal = false;
private ValueCallback<Uri> mFilePathCallback4;
private ValueCallback<Uri[]> mFilePathCallback5;
private int mStoredActivityRequestCode;
private int mStoredActivityResultCode;
private Intent mStoredActivityResultIntent;
public static MainFragment newInstance(String url, String share) {
MainFragment fragment = new MainFragment();
// arguments
Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_URL, url);
arguments.putString(ARGUMENT_SHARE, share);
fragment.setArguments(arguments);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
// handle fragment arguments
Bundle arguments = getArguments();
if (arguments != null) {
handleArguments(arguments);
}
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.DISABLED ? R.layout.fragment_main : R.layout.fragment_main_swipeable;
mRootView = inflater.inflate(layout, container, false);
mWebView = mRootView.findViewById(R.id.main_webview);
return mRootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// restore webview state
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
// setup webview
setupView();
// pull to refresh
setupSwipeRefreshLayout();
// setup stateful layout
setupStatefulLayout(savedInstanceState);
// load data
if (mStatefulLayout.getState() == StatefulLayout.EMPTY) loadData();
// progress popup
showProgress(mProgress);
// check permissions
if (WebViewAppConfig.GEOLOCATION) {
PermissionUtility.checkPermissionAccessLocation(this);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mWebView.onResume();
}
#Override
public void onPause() {
super.onPause();
mWebView.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mRootView = null;
}
#Override
public void onDestroy() {
super.onDestroy();
mWebView.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(this)) {
// permitted
mWebView.onActivityResult(requestCode, resultCode, intent);
} else {
// not permitted
mStoredActivityRequestCode = requestCode;
mStoredActivityResultCode = resultCode;
mStoredActivityResultIntent = intent;
}
//handleFilePickerActivityResult(requestCode, resultCode, intent); // not used, used advanced webview instead
}
#Override
public void onSaveInstanceState(Bundle outState) {
// save current instance state
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
// stateful layout state
if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState);
// save webview state
mWebView.saveState(outState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// action bar menu
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_main, menu);
// show or hide share button
MenuItem share = menu.findItem(R.id.menu_main_share);
share.setVisible(mShare != null && !mShare.trim().equals(""));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// action bar menu behavior
switch (item.getItemId()) {
case R.id.menu_main_share:
IntentUtility.startShareActivity(getContext(), getString(R.string.app_name), getShareText(mShare));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA:
case PermissionUtility.REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE:
case PermissionUtility.REQUEST_PERMISSION_ACCESS_LOCATION: {
// if request is cancelled, the result arrays are empty
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
// permission granted
if (requestCode == PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA) {
// continue with activity result handling
if (mStoredActivityResultIntent != null) {
mWebView.onActivityResult(mStoredActivityRequestCode, mStoredActivityResultCode, mStoredActivityResultIntent);
mStoredActivityRequestCode = 0;
mStoredActivityResultCode = 0;
mStoredActivityResultIntent = null;
}
}
} else {
// permission denied
}
}
} else {
// all permissions denied
}
break;
}
}
}
#Override
public void onRefresh() {
runTaskCallback(new Runnable() {
#Override
public void run() {
refreshData();
}
});
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
Logcat.d("");
}
#Override
public void onPageFinished(String url) {
Logcat.d("");
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
Logcat.d("");
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
Logcat.d("");
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
}
}
#Override
public void onExternalPageRequest(String url) {
Logcat.d("");
}
public void refreshData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress popup
showProgress(true);
// load web url
String url = mWebView.getUrl();
if (url == null || url.equals("")) url = mUrl;
mWebView.loadUrl(url);
} else {
showProgress(false);
Toast.makeText(getActivity(), R.string.global_network_offline, Toast.LENGTH_LONG).show();
}
}
private void handleArguments(Bundle arguments) {
if (arguments.containsKey(ARGUMENT_URL)) {
mUrl = arguments.getString(ARGUMENT_URL);
mLocal = mUrl.contains("file://");
}
if (arguments.containsKey(ARGUMENT_SHARE)) {
mShare = arguments.getString(ARGUMENT_SHARE);
}
}
// not used, used advanced webview instead
private void handleFilePickerActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_FILE_PICKER) {
if (mFilePathCallback4 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback4.onReceiveValue(uri);
} else {
mFilePathCallback4.onReceiveValue(null);
}
}
if (mFilePathCallback5 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback5.onReceiveValue(new Uri[]{uri});
} else {
mFilePathCallback5.onReceiveValue(null);
}
}
mFilePathCallback4 = null;
mFilePathCallback5 = null;
}
}
private void loadData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress
if (WebViewAppConfig.PROGRESS_PLACEHOLDER) {
mStatefulLayout.showProgress();
} else {
mStatefulLayout.showContent();
}
// load web url
mWebView.loadUrl(mUrl);
} else {
mStatefulLayout.showOffline();
}
}
private void showProgress(boolean visible) {
// show pull to refresh progress bar
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (contentSwipeRefreshLayout != null) contentSwipeRefreshLayout.setRefreshing(visible);
if (offlineSwipeRefreshLayout != null) offlineSwipeRefreshLayout.setRefreshing(visible);
if (emptySwipeRefreshLayout != null) emptySwipeRefreshLayout.setRefreshing(visible);
mProgress = visible;
}
private void showContent(final long delay) {
final Handler timerHandler = new Handler();
final Runnable timerRunnable = new Runnable() {
#Override
public void run() {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mRootView != null) {
Logcat.d("timer");
mStatefulLayout.showContent();
}
}
});
}
};
timerHandler.postDelayed(timerRunnable, delay);
}
private void setupView() {
// webview settings
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath());
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
// user agent
if (WebViewAppConfig.WEBVIEW_USER_AGENT != null && !WebViewAppConfig.WEBVIEW_USER_AGENT.equals("")) {
mWebView.getSettings().setUserAgentString(WebViewAppConfig.WEBVIEW_USER_AGENT);
}
// advanced webview settings
mWebView.setListener(getActivity(), this);
mWebView.setGeolocationEnabled(true);
// webview style
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // fixes scrollbar on Froyo
// webview hardware acceleration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// webview chrome client
View nonVideoLayout = getActivity().findViewById(R.id.main_non_video_layout);
ViewGroup videoLayout = getActivity().findViewById(R.id.main_video_layout);
View progressView = getActivity().getLayoutInflater().inflate(R.layout.placeholder_progress, null);
VideoEnabledWebChromeClient webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, progressView, (VideoEnabledWebView) mWebView);
webChromeClient.setOnToggledFullscreen(new MyToggledFullscreenCallback());
mWebView.setWebChromeClient(webChromeClient);
//mWebView.setWebChromeClient(new MyWebChromeClient()); // not used, used advanced webview instead
// webview client
mWebView.setWebViewClient(new MyWebViewClient());
// webview key listener
mWebView.setOnKeyListener(new WebViewOnKeyListener((DrawerStateListener) getActivity()));
// webview touch listener
mWebView.requestFocus(View.FOCUS_DOWN); // http://android24hours.blogspot.cz/2011/12/android-soft-keyboard-not-showing-on.html
mWebView.setOnTouchListener(new WebViewOnTouchListener());
// webview scroll listener
//((RoboWebView) mWebView).setOnScrollListener(new WebViewOnScrollListener()); // not used
// admob
setupBannerView();
}
private void setupBannerView() {
if (WebViewAppConfig.ADMOB_UNIT_ID_BANNER != null && !WebViewAppConfig.ADMOB_UNIT_ID_BANNER.equals("") && NetworkUtility.isOnline(getActivity())) {
ViewGroup contentLayout = mRootView.findViewById(R.id.container_content);
AdMobUtility.createAdView(getActivity(), WebViewAppConfig.ADMOB_UNIT_ID_BANNER, AdSize.BANNER, contentLayout);
}
}
private void controlBack() {
if (mWebView.canGoBack()) mWebView.goBack();
}
private void controlForward() {
if (mWebView.canGoForward()) mWebView.goForward();
}
private void controlStop() {
mWebView.stopLoading();
}
private void controlReload() {
mWebView.reload();
}
private void setupStatefulLayout(Bundle savedInstanceState) {
// reference
mStatefulLayout = (StatefulLayout) mRootView;
// state change listener
mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() {
#Override
public void onStateChange(View view, #StatefulLayout.State int state) {
Logcat.d(String.valueOf(state));
// do nothing
}
});
// restore state
mStatefulLayout.restoreInstanceState(savedInstanceState);
}
private void setupSwipeRefreshLayout() {
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.ENABLED) {
contentSwipeRefreshLayout.setOnRefreshListener(this);
offlineSwipeRefreshLayout.setOnRefreshListener(this);
emptySwipeRefreshLayout.setOnRefreshListener(this);
} else if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.PROGRESS) {
contentSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
offlineSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
emptySwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
}
}
private String getShareText(String text) {
if (mWebView != null) {
if (mWebView.getTitle() != null) {
text = text.replaceAll("\\{TITLE\\}", mWebView.getTitle());
}
if (mWebView.getUrl() != null) {
text = text.replaceAll("\\{URL\\}", mWebView.getUrl());
}
}
return text;
}
private boolean isLinkExternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_EXTERNAL_BROWSER) {
if (url.contains(rule)) return true;
}
return false;
}
private boolean isLinkInternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_INTERNAL_WEBVIEW) {
if (url.contains(rule)) return true;
}
return false;
}
// not used, used advanced webview instead
private class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback5 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
return true;
}
return false;
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
public void openFileChooser(ValueCallback<Uri> filePathCallback) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
}
private class MyToggledFullscreenCallback implements VideoEnabledWebChromeClient.ToggledFullscreenCallback {
#Override
public void toggledFullscreen(boolean fullscreen) {
if (fullscreen) {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
} else {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
}
private class MyWebViewClient extends WebViewClient {
private boolean mSuccess = true;
#Override
public void onPageFinished(final WebView view, final String url) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mSuccess) {
showContent(500); // hide progress bar with delay to show webview content smoothly
showProgress(false);
if (WebViewAppConfig.ACTION_BAR_HTML_TITLE) {
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(view.getTitle());
}
CookieSyncManager.getInstance().sync(); // save cookies
}
mSuccess = true;
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null) {
mSuccess = false;
mStatefulLayout.showEmpty();
showProgress(false);
}
}
});
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
// forward to deprecated method
onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString());
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (DownloadFileUtility.isDownloadableFile(url)) {
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
return true;
}
return true;
} else if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
// determine for opening the link externally or internally
boolean external = isLinkExternal(url);
boolean internal = isLinkInternal(url);
if (!external && !internal) {
external = WebViewAppConfig.OPEN_LINKS_IN_EXTERNAL_BROWSER;
}
// open the link
if (external) {
IntentUtility.startWebActivity(getContext(), url);
return true;
} else {
showProgress(true);
return false;
}
} else if (url != null && url.startsWith("file://")) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
return false;
} else {
return IntentUtility.startIntentActivity(getContext(), url);
}
}
}
}

How to fix ExoPlayer video Freeze 2.9.6

I use this code to play the full-screen video but I have a problem when it is video playing and moving from the main activity to the full-screen activity occurs freezing of the video for 2-3 seconds This problem occurs only with the releases after 2.8.3 only but with 2.8.0 works Video is smooth
code full: https://github.com/MATPOCKIH/ExoPlayerFullscreen
PlayerViewManager
public class PlayerViewManager {
private static final String TAG = "ExoPlayerViewManager";
public static final String EXTRA_VIDEO_URI = "video_uri";
private static Map<String, PlayerViewManager> instances = new HashMap<>();
private Uri videoUri;
public boolean isPlayerPlaying;
private boolean isMustPlaying;
private UniversalPlayerView universalPlayer;
public static PlayerViewManager getInstance(String videoUri) {
PlayerViewManager instance = instances.get(videoUri);
if (instance == null) {
instance = new PlayerViewManager(videoUri);
instances.put(videoUri, instance);
}
return instance;
}
private PlayerViewManager(String videoUri) {
this.videoUri = Uri.parse(videoUri);
}
public void preparePlayer(PlayerHolderView playerHolderView) {
if (playerHolderView == null) {
return;
}
if (universalPlayer == null) {
universalPlayer = createPlayer(playerHolderView.getContext());
isPlayerPlaying = true;
isMustPlaying = true;
}
universalPlayer.initialize(videoUri, playerHolderView);
}
public void releaseVideoPlayer() {
if (universalPlayer != null) {
universalPlayer.release();
}
universalPlayer = null;
}
public void goToBackground() {
if (universalPlayer != null /*&& !isMustPlaying*/) {
//isPlayerPlaying = player.getPlayWhenReady();
universalPlayer.pause();
}
}
public void goToForeground() {
if (universalPlayer != null && isMustPlaying) {
universalPlayer.play();
}
}
public void pausePlayer(){
if (universalPlayer != null) {
universalPlayer.pause();
isPlayerPlaying = false;
isMustPlaying = false;
}
}
public void playPlayer(){
if (universalPlayer != null) {
universalPlayer.play();
isPlayerPlaying = true;
isMustPlaying = true;
}
}
private UniversalPlayerView createPlayer(Context context){
if (videoUri.getScheme().startsWith("http")){
return new FaceterExoPlayerView(context);
}
return new FaceterExoPlayerView(context);
}
}
FaceterExoPlayerView
public class FaceterExoPlayerView extends UniversalPlayerView {
private Uri videoUri;
private DefaultDataSourceFactory dataSourceFactory;
private SimpleExoPlayer player;
private PlayerView exoPlayerView;
private Context context;
public FaceterExoPlayerView(Context context) {
this.context = context;
}
#Override
public void initialize(Uri videoUri, PlayerHolderView playerHolderView) {
if (playerHolderView == null || videoUri == null)
return;
exoPlayerView = playerHolderView.findViewById(R.id.exo_player);
if (player == null) {
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "faceter"));
MediaSource videoSource = buildMediaSource(videoUri, null);
player.prepare(videoSource);
}
player.clearVideoSurface();
player.setVideoTextureView((TextureView) exoPlayerView.getVideoSurfaceView());
exoPlayerView.setPlayer(player);
exoPlayerView.hideController();
setResizeModeFill(playerHolderView.isResizeModeFill());
}
#Override
public void play() {
player.setPlayWhenReady(true);
}
#Override
public void pause() {
player.setPlayWhenReady(false);
}
#SuppressWarnings("unchecked")
private MediaSource buildMediaSource(Uri uri, #Nullable String overrideExtension) {
int type = Util.inferContentType(uri, overrideExtension);
switch (type) {
/*case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new DashManifestParser(), (List<RepresentationKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new SsManifestParser(), (List<StreamKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);*/
case C.TYPE_HLS:
return new HlsMediaSource.Factory(dataSourceFactory)
/*.setPlaylistParser(
new FilteringManifestParser<>(
new HlsPlaylistParser(), (List<RenditionKey>) getOfflineStreamKeys(uri)))*/
.createMediaSource(uri);
case C.TYPE_OTHER:
return new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
#Override
public void release() {
if (player != null) {
player.release();
}
player = null;
}
#Override
public void setResizeModeFill(boolean isResizeModeFill) {
if (isResizeModeFill) {
exoPlayerView.setResizeMode(RESIZE_MODE_FILL);
} else {
exoPlayerView.setResizeMode(RESIZE_MODE_FIT);
}
}
}
PlayerHolderView.java
public class PlayerHolderView extends FrameLayout {
private String videoUrl;
private boolean isResizeModeFill = true;
private OnUserInteractionListener onUserInteractionListener;
public PlayerHolderView(#NonNull Context context) {
super(context);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.layout_player, this, true);
View controlView = this.findViewById(R.id.exo_controller);
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).pausePlayer();
}
});
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FullscreenVideoActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
getContext().startActivity(intent);
}
});
MainActivity
public class MainActivity extends AppCompatActivity {
private List<PlayerHolderView> playerHolders = new ArrayList<>();
private List<TextView> links = new ArrayList<>();
private List<String> mVideoUrls = new ArrayList<>(
Arrays.asList(
//"http://10.110.3.30/api/Playlists/6a3ecad7-e744-446f-9341-0e0ba834de63?from=2018-09-20&to=2018-09-21"
"https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/hls/TearsOfSteel.m3u8",
"http://redirector.c.youtube.com/videoplayback?id=604ed5ce52eda7ee&itag=22&source=youtube&sparams=ip,ipbits,expire,source,id&ip=0.0.0.0&ipbits=0&expire=19000000000&signature=513F28C7FDCBEC60A66C86C9A393556C99DC47FB.04C88036EEE12565A1ED864A875A58F15D8B5300&key=ik0",
"https://html5demos.com/assets/dizzy.mp4"
//"https://cdn.faceter.io/hls/ab196789-8876-4854-82f3-087e5682d013",
//"https://cdn.faceter.io/hls/65d1c673-6a63-44c8-836b-132449c9462a"
)
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerHolders.add((PlayerHolderView) findViewById(R.id.holder1));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder2));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder3));
links.add((TextView) findViewById(R.id.title1));
links.add((TextView) findViewById(R.id.title2));
links.add((TextView) findViewById(R.id.title3));
}
#Override
public void onResume() {
super.onResume();
int i = 0;
for (final String videoUrl : mVideoUrls) {
playerHolders.get(i).setupPlayerView(videoUrl);
playerHolders.get(i).setOnUserInteractionListener(this);
links.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVideoTitleClicked(videoUrl);
}
});
i++;
}
}
#Override
public void onPause() {
super.onPause();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).goToBackground();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).releaseVideoPlayer();
}
}
public void onVideoTitleClicked(String videoUrl) {
Intent intent = new Intent(getBaseContext(), DetailActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
startActivity(intent);
}
}
FullscreenVideoActivity
public class FullscreenVideoActivity extends AppCompatActivity {
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private View mContentView;
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of
// API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
private String mVideoUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_video);
mContentView = findViewById(R.id.enclosing_layout);
PlayerHolderView playerHolderView = findViewById(R.id.player_holder);
playerHolderView.setResizeModeFill(false);
mVideoUri = getIntent().getStringExtra(PlayerViewManager.EXTRA_VIDEO_URI);
PlayerViewManager.getInstance(mVideoUri).preparePlayer(playerHolderView);
/*
// Set the fullscreen button to "close fullscreen" icon
View controlView = playerView.findViewById(R.id.exo_controller);
ImageView fullscreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
fullscreenIcon.setImageResource(R.drawable.exo_controls_fullscreen_exit);
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).pausePlayer();
}
});*/
}
#Override
public void onResume() {
super.onResume();
PlayerViewManager.getInstance(mVideoUri).goToForeground();
}
#Override
public void onPause() {
super.onPause();
PlayerViewManager.getInstance(mVideoUri).goToBackground();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide();
}
private void hide() {
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide() {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, 100);
}
}
Just try out this code for video freeze problem:
#Override
public void play() {
player.setPlayWhenReady(true);
player.getPlaybackState();
}
#Override
public void pause() {
player.setPlayWhenReady(false);
player.getPlaybackState();
}
Here player.getPlaybackState(); is help full to get it to back state.

o.realm.exceptions.RealmFileException: Unable to open a realm at path '/data/data/com.apphoctienganhpro.firstapp/files/default.realm':

Realm class
public class RealmManager
private static Realm mRealm;
public static Realm open() {
mRealm = Realm.getDefaultInstance();
return mRealm;
}
public static void close() {
if (mRealm != null) {
mRealm.close();
}
}
public static RecordsDao recordsDao() {
checkForOpenRealm();
return new RecordsDao(mRealm);
}
private static void checkForOpenRealm() {
if (mRealm == null || mRealm.isClosed()) {
throw new IllegalStateException("RealmManager: Realm is closed, call open() method first");
}
}
}
When I call RealmManager.open(); my app crashes with error
Unable to open a realm at path
'/data/data/com.apphoctienganhpro.firstapp/files/default.realm':
Unsupported Realm file format version. in
/Users/cm/Realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_SharedRealm.cpp
line 92 Kind: ACCESS_ERROR
Activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
ButterKnife.bind(this);
RealmManager.open();
NestedScrollView scrollView = findViewById(R.id.nest_scrollview);
scrollView.setFillViewport(true);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = findViewById(R.id.appbar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = true;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
isShow = true;
} else if (isShow) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
isShow = false;
}
}
});
arrayListCategory = Utility.getAppcon().getSession().arrayListCategory;
arrayListGoal = Utility.getAppcon().getSession().arrayListGoal;
arrayList = new ArrayList<>();
arrayList = Utility.getAppcon().getSession().arrayListCategory;
if (arrayListGoal.size() > 0) {
goal_id = arrayListGoal.get(0).getSingleGoalId();
}else{
if(!arrayList.get(0).getCategory_description().equals("")) {
if(!Utility.getAppcon().getSession().screen_name.equals("lessson_complete")) {
displayDialog();
}
}
}
collapsingToolbarLayout.setTitle(arrayListCategory.get(0).getCategoryName());
layoutManager = new LinearLayoutManager(this);
recycler_view.setLayoutManager(layoutManager);
apiservice = ApiServiceCreator.createService("latest");
sessionManager = new SessionManager(this);
getCategoryLesson();
}
private void displayDialog() {
dialog = new Dialog(LessonActivity.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_detail);
dialog.setCancelable(true);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_main_d = dialog.findViewById(R.id.img_main_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
img_play_d.setVisibility(View.GONE);
Picasso.with(LessonActivity.this).load(ApiConstants.IMAGE_URL + arrayList.get(0).getCategoryImage())
.noFade()
.fit()
.placeholder(R.drawable.icon_no_image)
.into(img_main_d);
txt_title_d.setText(arrayList.get(0).getCategoryName());
txt_description_d.setText(Html.fromHtml(arrayList.get(0).getCategory_description().replaceAll("\\\\", "")));
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_close.setOnClickListener(view -> dialog.dismiss());
}
private void getCategoryLesson() {
pDialog = new ProgressDialog(LessonActivity.this);
pDialog.setTitle("Checking Data");
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Observable<LessonResponse> responseObservable = apiservice.getCategoryLesson(
sessionManager.getKeyEmail(),
arrayListCategory.get(0).getCategoryId(),
goal_id,
sessionManager.getUserData().get(0).getUserId(),
sessionManager.getKeyToken());
responseObservable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(throwable -> {
if (throwable instanceof retrofit2.HttpException) {
retrofit2.HttpException ex = (retrofit2.HttpException) throwable;
Log.e("error", ex.getLocalizedMessage());
}
return Observable.empty();
})
.subscribe(new Observer<LessonResponse>() {
#Override
public void onCompleted() {
pDialog.dismiss();
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(LessonResponse lessonResponse) {
if (lessonResponse.getData().size() > 9) {
txt_total_lesson.setText(String.valueOf(lessonResponse.getData().size()));
} else {
txt_total_lesson.setText(String.valueOf("0" + lessonResponse.getData().size()));
}
if (lessonResponse.getStatusCode() == 200) {
adapter = new LessonAdapter(lessonResponse.getData(), LessonActivity.this);
recycler_view.setAdapter(adapter);
} else {
Utility.displayToast(getApplicationContext(), lessonResponse.getMessage());
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onClickFavButton(int position, boolean toggle) {
}
public boolean isFavourate(String LessionId,String UserId){
if (arrayList!=null){
for (int i=0;i<arrayList.size();i++)
if (favarrayList.get(1).getLessonId().equals(LessionId) && favarrayList.get(0).getUserID().equals(UserId)){
return true;
}
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
RealmManager.close();
}
}
Adapter Class
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_lesson, parent, false);
return new LessonAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
dialog = new Dialog(context);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_audio);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
frm_header = dialog.findViewById(R.id.frm_header);
img_back_d = dialog.findViewById(R.id.img_back_d);
holder.txt_lesson_title.setText(arrayList.get(position).getLessonName());
holder.btn_view.setOnClickListener(view -> {
txt_title_d.setText(arrayList.get(position).getLessonName());
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_description_d.setText(Html.fromHtml(arrayList.get(position).getLessonDescription().replaceAll("\\\\", "")));
displayDialog(holder.getAdapterPosition());
});
holder.btn_go.setOnClickListener(view -> {
Utility.getAppcon().getSession().arrayListLesson = new ArrayList<>();
Utility.getAppcon().getSession().arrayListLesson.add(arrayList.get(position));
Intent intent = new Intent(context, LessonCompleteActivity.class);
context.startActivity(intent);
});
if (arrayList.get(position).isFavourate())
holder.favCheck.setChecked(true);
else
holder.favCheck.setChecked(false);
holder.favCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
if (checkBox.isChecked()) {
RealmManager.recordsDao().saveToFavorites(arrayList.get(position));
} else {
RealmManager.recordsDao().removeFromFavorites(arrayList.get(position));
}
}
});
}
private void displayDialog(int Position) {
final MediaPlayer mediaPlayer = new MediaPlayer();
String url = ApiConstants.IMAGE_URL + arrayList.get(Position).getLesson_audio_url();
//String url = "http://208.91.198.96/~diestechnologyco/apphoctienganhpro/uploads/mp3/mp3_1.mp3"; // your URL here
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare(); // might take long! (for buffering, etc)
} catch (IOException e) {
e.printStackTrace();
}
img_play_d.setOnClickListener(view -> {
if (audio_flag == 0) {
mediaPlayer.start();
audio_flag = 1;
img_play_d.setImageResource(R.mipmap.pause_circle);
} else {
mediaPlayer.pause();
audio_flag = 0;
img_play_d.setImageResource(R.mipmap.icon_play);
}
});
//img_play_d.setOnClickListener(view -> mediaPlayer.start());
txt_close.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
img_back_d.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.txt_lesson_title)
TextView txt_lesson_title;
#BindView(R.id.txt_lesson_type)
TextView txt_lesson_type;
#BindView(R.id.btn_view)
Button btn_view;
#BindView(R.id.btn_go)
Button btn_go;
#BindView(R.id.image_favborder)
CheckBox favCheck;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
//RealmManager.open();
}
}
public void getdata(){
}
public void addFavourate(String LessonId,String UserId) {
if (mRealm != null) {
mRealm.beginTransaction();
favList_model = mRealm.createObject(FavList_model.class);
favList_model.setLessonId(LessonId);
favList_model.setUserID(UserId);
mRealm.commitTransaction();
mRealm.close();
}
}
}

Categories

Resources