0% found this document useful (0 votes)
2 views15 pages

Android Code Snippets for Beginners

Uploaded by

vachapatel22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Android Code Snippets for Beginners

Uploaded by

vachapatel22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

write code for send data from one to other activity using implicit intent

Java File

import [Link];
import [Link];
import [Link];
import [Link];

public class ActivityA extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_a);

// Example: Sending data using implicit intent


String dataToSend = "Hello from Activity A!";
Intent intent = new Intent(Intent.ACTION_SEND);
[Link]("text/plain");
[Link](Intent.EXTRA_TEXT, dataToSend);

// Check if there is an app to handle this intent


if ([Link](getPackageManager()) != null) {
startActivity(intent);
}
}
}

XML File

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Data" />
</LinearLayout>
2. program for a toast message

JAVA File

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

Button buttonShowToast = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {
// Display a Toast message
[Link]([Link], "Hello, this is a Toast message!",
Toast.LENGTH_SHORT).show();
}
});
}
}

XML File

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<Button
android:id="@+id/buttonShowToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast" />
</LinearLayout>
3. Code for CRUD operations in android

Java File

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private DatabaseHelper dbHelper;


private EditText editName, editGrade, editId;
private TextView textViewResults;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

dbHelper = new DatabaseHelper(this);

editName = findViewById([Link]);
editGrade = findViewById([Link]);
editId = findViewById([Link]);
textViewResults = findViewById([Link]);

Button buttonAdd = findViewById([Link]);


Button buttonRead = findViewById([Link]);
Button buttonUpdate = findViewById([Link]);
Button buttonDelete = findViewById([Link]);

// Add Student
[Link](v -> {
String name = [Link]().toString();
String grade = [Link]().toString();
long result = [Link](name, grade);
if (result != -1) {
[Link](this, "Student Added", Toast.LENGTH_SHORT).show();
}
});

// Read Students
[Link](v -> {
Cursor cursor = [Link]();
if ([Link]() == 0) {
[Link]("No Data Found");
return;
}
StringBuilder result = new StringBuilder();
while ([Link]()) {
[Link]("ID: ").append([Link](0))
.append(", Name: ").append([Link](1))
.append(", Grade: ").append([Link](2)).append("\n");
}
[Link]([Link]());
});

// Update Student
[Link](v -> {
int id = [Link]([Link]().toString());
String name = [Link]().toString();
String grade = [Link]().toString();
int rowsUpdated = [Link](id, name, grade);
if (rowsUpdated > 0) {
[Link](this, "Student Updated", Toast.LENGTH_SHORT).show();
} else {
[Link](this, "Update Failed", Toast.LENGTH_SHORT).show();
}
});

// Delete Student
[Link](v -> {
int id = [Link]([Link]().toString());
int rowsDeleted = [Link](id);
if (rowsDeleted > 0) {
[Link](this, "Student Deleted", Toast.LENGTH_SHORT).show();
} else {
[Link](this, "Delete Failed", Toast.LENGTH_SHORT).show();
}
});
}
}

XML File

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<EditText
android:id="@+id/editGrade"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Grade" />

<EditText
android:id="@+id/editId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter ID (for Update/Delete)" />

<Button
android:id="@+id/buttonAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Student" />

<Button
android:id="@+id/buttonRead"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read Students" />

<Button
android:id="@+id/buttonUpdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Update Student" />

<Button
android:id="@+id/buttonDelete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete Student" />

<TextView
android:id="@+id/textViewResults"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Results will appear here"
android:padding="10dp"
android:textSize="16sp" />
</LinearLayout>
4. code to create sqlite connection to database

Java File

import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private DatabaseHelper databaseHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Initialize the DatabaseHelper


databaseHelper = new DatabaseHelper(this);

// Example: Open the database connection


try {
[Link](); // Opens writable connection
[Link](this, "Database connection established!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
[Link](this, "Failed to connect to database: " + [Link](),
Toast.LENGTH_LONG).show();
}
}
}
5. write a code to play music in android

Java File

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private MediaPlayer mediaPlayer;


private boolean isPlaying = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Initialize the MediaPlayer with the audio resource


mediaPlayer = [Link](this, [Link]);

Button buttonPlayPause = findViewById([Link]);

// Set button click listener to play or pause music


[Link](v -> {
if (isPlaying) {
pauseMusic();
[Link]("Play");
} else {
playMusic();
[Link]("Pause");
}
});
}

// Method to play music


private void playMusic() {
if (mediaPlayer != null) {
[Link]();
isPlaying = true;
}
}

// Method to pause music


private void pauseMusic() {
if (mediaPlayer != null && [Link]()) {
[Link]();
isPlaying = false;
}
}

@Override
protected void onDestroy() {
[Link]();
// Release the MediaPlayer resources
if (mediaPlayer != null) {
[Link]();
mediaPlayer = null;
}
}
}

XML File

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<Button
android:id="@+id/buttonPlayPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play" />
</LinearLayout>
6. code to send email using explixit intent in android

Java File

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private EditText editTextTo, editTextSubject, editTextMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

editTextTo = findViewById([Link]);
editTextSubject = findViewById([Link]);
editTextMessage = findViewById([Link]);
Button buttonSendEmail = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {
sendEmail();
}
});
}

private void sendEmail() {


// Get user input
String recipient = [Link]().toString();
String subject = [Link]().toString();
String message = [Link]().toString();

// Check if recipient field is empty


if ([Link]()) {
[Link](this, "Please enter a recipient email address", Toast.LENGTH_SHORT).show();
return;
}

// Create an intent for sending an email


Intent emailIntent = new Intent(Intent.ACTION_SEND);
[Link]("message/rfc822"); // MIME type for email
[Link](Intent.EXTRA_EMAIL, new String[]{recipient});
[Link](Intent.EXTRA_SUBJECT, subject);
[Link](Intent.EXTRA_TEXT, message);

// Launch email client


try {
startActivity([Link](emailIntent, "Choose an Email client:"));
} catch ([Link] ex) {
[Link](this, "No email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}

XML File

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/editTextTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Recipient Email"
android:inputType="textEmailAddress" />

<EditText
android:id="@+id/editTextSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message"
android:minLines="4"
android:gravity="top"
android:inputType="textMultiLine" />

<Button
android:id="@+id/buttonSendEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Email" />
</LinearLayout>

7. code to click pic in camera and send to gallery in android


Java File
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

public class MainActivity extends AppCompatActivity {

private Uri imageUri;


private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

imageView = findViewById([Link]);
Button buttonCapture = findViewById([Link]);

// Register ActivityResultLauncher for camera intent


ActivityResultLauncher<Intent> cameraLauncher = registerForActivityResult(
new [Link](),
result -> {
if ([Link]() == RESULT_OK) {
// Show the captured image in the ImageView
[Link](imageUri);

// Add the image to the gallery


addImageToGallery();
} else {
[Link](this, "Cancelled", Toast.LENGTH_SHORT).show();
}
}
);

[Link](v -> {
// Create a new image file to store the photo
imageUri = createImageUri();
if (imageUri != null) {
// Launch the camera intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
[Link](MediaStore.EXTRA_OUTPUT, imageUri);
[Link](cameraIntent);
} else {
[Link](this, "Error creating image file", Toast.LENGTH_SHORT).show();
}
});
}

// Method to create a new image URI


@Nullable
private Uri createImageUri() {
ContentValues values = new ContentValues();
[Link]([Link].DISPLAY_NAME, "IMG_" + [Link]() + ".jpg");
[Link]([Link].MIME_TYPE, "image/jpeg");
[Link]([Link].RELATIVE_PATH, Environment.DIRECTORY_PICTURES); //
Save in Pictures directory
return getContentResolver().insert([Link].EXTERNAL_CONTENT_URI, values);
}

// Method to add the captured image to the gallery


private void addImageToGallery() {
try {
OutputStream outputStream = getContentResolver().openOutputStream(imageUri);
if (outputStream != null) {
[Link]();
}
[Link](this, "Image saved to gallery", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
[Link]();
[Link](this, "Failed to save image to gallery", Toast.LENGTH_SHORT).show();
}
}
}

XML File
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">

<Button
android:id="@+id/buttonCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture Photo" />

<ImageView
android:id="@+id/imageView"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
android:background="#CCCCCC" />
</LinearLayout>

8. code to validate email in android


Java File

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private EditText editTextEmail;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

editTextEmail = findViewById([Link]);
Button buttonValidate = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {
String email = [Link]().toString();
if (isValidEmail(email)) {
[Link]([Link], "Email is valid", Toast.LENGTH_SHORT).show();
} else {
[Link]([Link], "Invalid email address", Toast.LENGTH_SHORT).show();
}
}
});
}

// Method to validate email using Android's built-in patterns


private boolean isValidEmail(String email) {
return email != null && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}

XML File

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Email"
android:inputType="textEmailAddress" />

<Button
android:id="@+id/buttonValidate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Validate Email" />
</LinearLayout>

You might also like