Goal: Create a button that, when clicked, shows a Toast message.
Step 1: Add a Button to activity_main.xml
• Open activity_main.xml in your res/layout folder.
• Add a Button to the layout with an ID that you’ll use to reference it in the code, like buttonShowToast.
Code:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/buttonShowToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast"/>
</LinearLayout>
Step 2: Access the Button in MainActivity.kt
• Open MainActivity.kt.
• In the onCreate method, get a reference to the button using its ID and set up an OnClickListener.
Code:
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Access the button
val buttonShowToast: Button = findViewById(R.id.buttonShowToast)
// Set up click listener for the button
buttonShowToast.setOnClickListener {
// Show a Toast message when the button is clicked
Toast.makeText(this, "I have been pushed", Toast.LENGTH_SHORT).show() }
}
}
Output:
Step 3: Run the App
• Build and run the app on an emulator or physical device.
• When the app opens, tap the "Show Toast" button.
• You should see a Toast message that says "I have been pushed" at the bottom of the screen.
Output:
Now let us build an application that supports Login functionality, and how a notification can be sent to the specific logged in user.
But to do this we need support from external services for Authentication (login) and Firebase (for storage & cloud messaging)
If you're creating your own API (using something like Node.js, Express, etc.) and want to connect it to your Android app, here's the process:
Add Retrofit dependency to your build.gradle:
implementation 'com.squareup.retrofit2:retrofit:2.x.x' implementation 'com.squareup.retrofit2:converter-gson:2.x.x'
Example of a Retrofit setup in your java file:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://your-api-url.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<Item>> call = apiService.getItems();
call.enqueue(new Callback<List<Item>>() {
@Override
public void onResponse(Call<List<Item>> call, Response<List<Item>> response) {
if (response.isSuccessful()) {
// Handle the response
}
}
@Override
public void onFailure(Call<List<Item>> call, Throwable t) {
// Handle failure
}
});
ApiService should be an interface where you define your API endpoints:
public interface ApiService {
@GET("items")
Call<List<Item>> getItems();
}
You can now try creating weather forecasting app by connecting with free weather api like OpenWeatherMap
https://openweathermap.org/api
private WeatherApiService weatherApiService; // Your API service interface
private String apiKey = "39df6b63aad4aeaa900f15a70ee59176"; // Replace with your actual API key
Firebase provides a set of tools for authentication, real-time databases, storage, and more. Here’s how you can integrate Firebase into your Android app:
In project-level build.gradle, add the classpath for Firebase:
classpath 'com.google.gms:google-services:4.3.15'
In app-level build.gradle, apply the plugin:
apply plugin: 'com.google.gms.google-services'
b) Add Firebase Dependencies:
Depending on the Firebase features you are using (Authentication, Firestore, etc.), add the relevant dependencies in your build.gradle file. For example:
implementation 'com.google.firebase:firebase-auth:21.0.7'
implementation 'com.google.firebase:firebase-firestore:24.0.5'
implementation 'com.google.firebase:firebase-database:20.0.5'
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword("user@example.com", "password")
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Sign-up successful
} else {
// Handle failure
}
});
Firestore Example
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").document("user_id")
.set(userData)
.addOnSuccessListener(aVoid -> {
// Data saved successfully
})
.addOnFailureListener(e -> {
// Handle failure
});
Realtime Database Example:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Hello, Firebase!");
Add the required dependencies for Firebase Cloud Messaging:
implementation 'com.google.firebase:firebase-messaging:23.1.0'
Firebase- https://firebase.google.com
Working of firebase authentication after connecting: