public class LeaderboardActivity extends AppCompatActivity {
code
DrawerLayout drawerLayout;
NavigationView navigationView;
ActionBarDrawerToggle drawerToggle;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference usersRef = db.collection("users");
Query leaderboardQuery = usersRef.orderBy("score", Query.Direction.DESCENDING).limit(10);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
menuConfig();
readLeaderboard();
}
//menu
public void menuConfig() {
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
navigationView.bringToFront();
if (id == R.id.home) {
Toast.makeText(LeaderboardActivity.this, "Home pressed", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LeaderboardActivity.this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.leaderboard) {
Toast.makeText(LeaderboardActivity.this, "Contact pressed", Toast.LENGTH_SHORT).show();
} else if (id == R.id.gallery) {
Toast.makeText(LeaderboardActivity.this, "Gallery pressed", Toast.LENGTH_SHORT).show();
} else if (id == R.id.about) {
Toast.makeText(LeaderboardActivity.this, "About pressed", Toast.LENGTH_SHORT).show();
} else if (id == R.id.login) {
Toast.makeText(LeaderboardActivity.this, "Login pressed", Toast.LENGTH_SHORT).show();
} else if (id == R.id.share) {
Toast.makeText(LeaderboardActivity.this, "Share pressed", Toast.LENGTH_SHORT).show();
} else if (id == R.id.rate_us) {
Toast.makeText(LeaderboardActivity.this, "Rate us pressed", Toast.LENGTH_SHORT).show();
}
// Close drawer after item is selected.
drawerLayout.closeDrawer(GravityCompat.START);
return false; // return true if you want to indicate the item was selected.
}
});
AdView mAdView = findViewById(R.id.adView);
AdRequest BannerAdRequest = new AdRequest.Builder().build();
mAdView.loadAd(BannerAdRequest);
mAdView.setVisibility(View.VISIBLE);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
// handle other menu items here if necessary
return super.onOptionsItemSelected(item);
}
private void readLeaderboard() {
leaderboardQuery.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
LinearLayout leaderboardLayout = findViewById(R.id.leaderboardLayout);
// Clear the layout if you rerun the query to prevent duplicating views
leaderboardLayout.removeAllViews();
for (QueryDocumentSnapshot document : task.getResult()) {
// Create TextView for each entry
TextView scoreView = new TextView(this);
String nickname = document.getString("nickname");
String score = document.getLong("score").toString();
String text = nickname != null ? nickname + " " + score : "Anonymous " + score;
scoreView.setText(text);
scoreView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
scoreView.setGravity(Gravity.CENTER_HORIZONTAL);
leaderboardLayout.addView(scoreView);
}
} else {
Log.w("TagDB", "Error getting documents.", task.getException());
}
});
}
}
Both have common elements, like the menu.
Is it possible to combine these? So all functions would be in one place. Wouldn't that be more optimized and efficient?
How can I achieve this?
It's often a good idea to try to maximize code reuse and minimize duplication, which makes your code more maintainable and less error-prone. However, combining everything into a single Activity is not always the best way to achieve this. Android applications are designed to work with multiple Activities, each representing a different screen or concept, and it's a common practice to separate different functionalities into different Activities.
To reduce code duplication, you can consider the following strategies:
Base Activity: Create a base Activity class that implements common functionality such as the navigation drawer and menu handling, and have all other Activities in your app extend this base class.
Fragments: Use Fragments to encapsulate reusable parts of the user interface. You can include these fragments in different activities as needed. If parts of the navigation drawer are shared, you could create a Fragment for those.
Utility Classes: Move reusable pieces of logic into utility classes or helper methods. This is especially useful for database operations, shared preferences, and other operations that can be abstracted away from the UI.
Services and Providers: For operations that need to be accessed by multiple components in your app, consider using Services, ContentProviders, or singleton objects to centralize access to these resources.
Shared Resources: For elements like string resources, styles, themes, and dimensions, use the res folder to ensure that they are defined only once and can be reused across the application.
Custom Views: If you have complex views that are reused across different Activities, consider creating custom view classes that encapsulate the view logic.
Here is an example of how you could create a base activity to minimize code duplication for the navigation drawer:
java
public abstract class BaseActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
NavigationView navigationView;
ActionBarDrawerToggle drawerToggle;
// Call this method in onCreate of derived activities to initialize the drawer
protected void initDrawer() {
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(item -> {
// Your drawer item clicked logic goes here
drawerLayout.closeDrawer(GravityCompat.START);
return true;
});
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
// Add other common methods here...
}
Each Activity can then extend BaseActivity and call initDrawer() within its onCreate() method after setting the content view. You can override methods in child activities to customize behavior as needed.
Remember, while reducing code duplication is critical, so is adhering to good architectural patterns like separation of concerns. It’s essential to find the right balance between code reuse and keeping a clear structure where each class has a distinct responsibility.