Practical no.
18
XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editTextUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter URL"
android:inputType="textUri"/>
<Button
android:id="@+id/btnNavigate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Navigate"
android:layout_marginTop="16dp"/>
</LinearLayout>
Java code:
package com.example.practicalno17;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editTextUrl = findViewById(R.id.editTextUrl);
Button btnNavigate = findViewById(R.id.btnNavigate);
btnNavigate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = editTextUrl.getText().toString().trim();
// Check if the input is not empty
if (!url.isEmpty()) {
// Ensure URL has the proper scheme
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "https://" + url;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Please enter a valid URL",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Output:
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/btnDialer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/open_dialer"
android:padding="10dp"/>
</LinearLayout>
Java code:
package com.example.practicalno18or19;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDialer = findViewById(R.id.btnDialer);
btnDialer.setOnClickListener(v -> {
// Open the phone dialer with a predefined number (or leave empty to open dialer)
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:")); // Leave empty ("tel:") to open dialer without a
number
startActivity(intent);
});
}
}
Output: