public class FloatingActivity extends AppCompatActivity {
static final String TAG = "FloatingActivity";
private final Handler handler = new Handler();
public Activity mActivity;
MediaPlayer mediaPlayer;
AppSharedPref appSharedPref;
finishAfterTransition();
} catch (Exception e) {
e.printStackTrace();
}
});
btn_translate.setOnClickListener(v -> {
del_img.setEnabled(false);
try {
if (AppUtills.getInstance().isNetworkAvailable(mActivity)) {
String translation = new SqliteHelper(mActivity).getPreviousTranslatedText(
text.getText().toString(),
from_custom_spinner.getText().toString(),
to_custom_spinner.getText().toString()
);
translated_text.setText(translation);
boolean isTranslated = new SqliteHelper(mActivity).isTextAlreadyTranslated(
text.getText().toString(),
translated_text.getText().toString(),
from_custom_spinner.getText().toString(),
to_custom_spinner.getText().toString()
);
if (isTranslated) {
del_img.setEnabled(true);
return;
}
if (!text.getText().toString().trim().isEmpty()) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
try {
to_speeker.setImageResource(R.drawable.ic_speaker);
} catch (Exception e) {
e.printStackTrace();
}
to_speeker.setTag("speak");
}
progress.setVisibility(View.VISIBLE);
btn_translate.setVisibility(View.GONE);
VolleyRequestHelper volleyRequestHelper = new VolleyRequestHelper();
volleyRequestHelper.makeTranslationRequest(getApplicationContext(), "auto", to_language_code, text.getText().toString().trim(), new VolleyRequestHelper.OnTranslationListener() {
@Override
public void onTranslate(translation_result_model translationModel) {
new Handler().postDelayed(() -> del_img.setEnabled(true),1000);
try {
translated_text.setText(AppUtills.getInstance().CapitalizeFirstLetter(translationModel.getTranslatedText()));
progress.setVisibility(View.GONE);
btn_translate.setVisibility(View.VISIBLE);
SqliteHelper helper = new SqliteHelper(mActivity);
history_model h = new history_model();
h.setSource_language_text(languagesRepo.getLanguageByLangCode(translationModel.getSourceLang()).getLangName());
h.setTarget_language_text(to_custom_spinner.getText().toString());
h.setSource_text(text.getText().toString().trim());
h.setTarget_text(translationModel.getTranslatedText());
h.setDate(getCurrentDate());
helper.insert(h);
selectSourceLanguage(translationModel.getSourceLang());
} catch (Exception e) {
Log.d(FloatingActivity.class.getName(), " setOnTranslationListener " + e.getMessage());
}
}
@Override
public void onTranslateError(String error) {
try {
progress.setVisibility(View.GONE);
btn_translate.setVisibility(View.VISIBLE);
del_img.setEnabled(true);
} catch (Exception e) {
Log.d(FloatingActivity.class.getName(), " " + e.getMessage());
}
}
});
} else {
if (mActivity != null)
Toast.makeText(mActivity, "No text available", Toast.LENGTH_SHORT).show();
}
} else {
if (mActivity != null)
Toast.makeText(mActivity, "Internet is not available", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
});
enableOrDisableMoreBtn();
mediaPlayer = new MediaPlayer();
new Handler(Looper.getMainLooper()).postDelayed(() -> paste(), 300);
Rect rectangle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
window.findViewById(Window.ID_ANDROID_CONTENT).setOnClickListener(v -> {
});
}
private String getCurrentDate() {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yy", Locale.getDefault());
return df.format(c);
}
@Override
public void onBackPressed() {
finishAfterTransition();
}
private void enableOrDisableMoreBtn() {
try {
if (translated_text.getText().toString().isEmpty()) {
more_img.setEnabled(false);
more_img.setImageResource(R.drawable.ic_more);
}
TextWatcher textWatcher = 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) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().isEmpty()) {
more_img.setEnabled(false);
more_img.setImageResource(R.drawable.ic_more);
} else {
more_img.setEnabled(true);
more_img.setImageResource(R.drawable.ic_more);
}
}
};
translated_text.addTextChangedListener(textWatcher);
} catch (Exception e) {
new customException("ignore " + e.getMessage()).printStackTrace();
}
}
private void paste() {
try {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard != null && clipboard.hasPrimaryClip() && clipboard.getPrimaryClip() != null) {
CharSequence clip = clipboard.getPrimaryClip().getItemAt(0).coerceToText(FloatingActivity.this).toString();
text.setText(AppUtills.getInstance().CapitalizeFirstLetter(clip.toString().trim()));
from_language_code = "auto";
btn_translate.callOnClick();
}
} catch (Exception e) {
new customException("ignore " + e.getMessage()).printStackTrace();
}
}
Certainly! Let's perform a comprehensive code review of your FloatingActivity class to identify potential improvements, best practices, and areas where you might encounter issues. This review will cover aspects such as code organization, performance, error handling, UI management, and best practices for Android development.
1. Code Organization and Readability
a. Separation of Concerns
Issue: The onCreate method is quite lengthy, handling UI initialization, event listeners, network requests, and more.
Recommendation: Break down the onCreate method into smaller, manageable methods. This enhances readability and maintainability.
Issue: Resetting MediaPlayer without checking its state might lead to exceptions.
Recommendation: Always check the state of MediaPlayer before performing operations.
java
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
}
5. Network Requests and Asynchronous Operations
a. Using Modern Networking Libraries
Issue: The code uses a custom VolleyRequestHelper. While Volley is a solid choice, consider using Retrofit combined with OkHttp for more flexibility and easier integration with modern features like coroutines.
Recommendation: Evaluate if Retrofit better suits your needs, especially for larger projects.
b. Avoiding Memory Leaks with Callbacks
Issue: Anonymous inner classes or handlers holding references to the Activity can cause memory leaks.
Recommendation: Use WeakReferences in callbacks or leverage Lifecycle-aware components like LiveData or ViewModel.
6. Exception Handling
a. Avoid Catching Generic Exceptions
Issue: The code frequently catches Exception, which can obscure real issues.
Recommendation: Catch more specific exceptions and handle them appropriately.
private static final String TAG = "FloatingActivity";
private static final String TAG_SPEAK = "speak";
private static final String TAG_STOP = "stop";
Conclusion
Your FloatingActivity class encompasses a wide range of functionalities, and it's evident that considerable effort has been put into its implementation. By addressing the areas highlighted above, you can enhance the readability, maintainability, performance, and user experience of your application. Adopting modern Android development practices such as View Binding, Lifecycle-aware components, and better resource management will not only streamline your code but also make it more robust and scalable.
If you have specific questions or encounter particular issues within this code, feel free to ask for more targeted assistance!