Q13. Write a program to demonstrate Context Menu in android.
activity_main.xml.
<?xml
version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ContextMenuBar">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fileslist"
/>
</LinearLayout>
MainActivity.java:
package
com.example.menubar; import
androidx.appcompat.app.AppCompatActivity;
import
android.os.Bundle;
import
android.view.ContextMenu;
import
android.view.View;
import
android.widget.ArrayAdapter;
import
android.widget.ListView;
public
class ContextMenuBar extends AppCompatActivity {
ListView file_list;
String[]
files={"PDF","DOCS","HTML","PPT","ZIP"};
@Override protected void onCreate(Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_context_menu_bar);
file_list=(ListView)
findViewById(R.id.fileslist);
ArrayAdapter<String>
adapter=new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,files);
file_list.setAdapter(adapter);
registerForContextMenu(file_list);
}
@Override
public void onCreateContextMenu(ContextMenu
menu, View v,
ContextMenu.ContextMenuInfo
menuInfo) {
super.onCreateContextMenu(menu,
v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu,menu);
}
}
Output-
==========================================================================
Q14
. Design android application for login activity. Write android
code to check login credentials with username = "mca" and password =
"android". Display appropriate toast message to the user.
activity_main.xml :
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login
Action"
android:textSize="40dp"
android:textStyle="bold"
android:layout_marginBottom="40dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10px"
android:text="Username :
"
android:textSize="20dp" />
<EditText
android:id="@+id/username"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_margin="10px"
android:hint="Enter
Username"
android:textSize="20dp"
tools:ignore="TouchTargetSizeCheck" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password :
"
android:textSize="20dp"
android:layout_margin="10px"/>
<EditText
android:id="@+id/password"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textSize="20dp"
android:layout_margin="10px"
android:hint="Enter
Password"
tools:ignore="TouchTargetSizeCheck" />
</LinearLayout>
<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_marginTop="20dp"/>
</LinearLayout>
MainActivity.java :
package com.example.labq14;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText ed1, ed2;
Button b;
String u,p;
Context context;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1 = (EditText) findViewById(R.id.username);
ed2 = (EditText)
findViewById(R.id.password);
b = (Button)
findViewById(R.id.submit);
b.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View
view) {
u = ed1.getText().toString();
p =
ed2.getText().toString();
if
(u.equals("mca") && p.equals("android")){
Toast.makeText(MainActivity.this,"Login
Successful",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,"Invalid username &
password",Toast.LENGTH_SHORT).show();
}
}
});
}}
Output :
==========================================================================
Q15. Write a program to demonstrate Popup Menu in
android for cut, copy and paste options in it and display appropriate
information related to operation.
activity_main.xml
<?xml version="1.0"
encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/clickBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0F9D58"
android:text="Click
Me"
android:textColor="#ffffff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
popup_menu.xml
<?xml version="1.0"
encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/java"
android:title="Java"
/>
<item
android:id="@+id/kotlin"
android:title="Kotlin"
/>
<item
android:id="@+id/android"
android:title="Android"
/>
<item
android:id="@+id/react_native"
android:title="React
Native" />
</menu>
MainActivity.xml
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button
= (Button) findViewById(R.id.clickBtn);
button.setOnClickListener(new
View.OnClickListener() {
@Override
public
void onClick(View view) {
PopupMenu
popupMenu = new PopupMenu(MainActivity.this, button);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu,
popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener() {
@Override
public
boolean onMenuItemClick(MenuItem menuItem) {
Toast.makeText(MainActivity.this,"YouClicked"+menuItem.getTitle(),
Toast.LENGTH_SHORT).show();
return
true;
}
});
popupMenu.show();
}
});
} }
Output :
==========================================================================
Q16. Write an application to display image button.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_foreground"
android:layout_centerInParent="true"/>
</RelativeLayout>
MainActivity.java
package com.example.imagebuttonexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
@Override
protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton imageButton = findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Display a toast message when the image button is clicked
Toast.makeText(getApplicationContext(), "You clicked image
button", Toast.LENGTH_SHORT).show();
}
});
}
}
Output :
==========================================================================
Q17. Demonstrate an
application to implement web view in android.
<!--
AndroidManifest.xml -->
<uses-permission
android:name="android.permission.INTERNET" />
<!--
res/layout/activity_main.xml -->
<?xml
version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
MainActivity.java
package
com.example.webviewexample;
import androidx.appcompat.app.AppCompatActivity;
import
android.os.Bundle;
import
android.webkit.WebSettings;
import
android.webkit.WebView;
import
android.webkit.WebViewClient;
public
class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new
WebViewClient());
webView.loadUrl("https://www.google.com/");
}
// Override the onBackPressed method to
handle navigation within the WebView
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
Output :
==========================================================================
Q.18.Write
an android code to turn ON/OFF Bluetooth
XML : -
<?xml
version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--Changes the state of
Bluetooth on button click-->
<Button
android:id="@+id/BtBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click"
/>
<!--Displays the state of
Bluetooth on button click-->
<TextView
android:id="@+id/BtTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/BtBtn"
android:layout_centerHorizontal="true"
android:hint="Bluetooth
Status"
android:textSize="30sp"
/>
</RelativeLayout>
Java Code
import android.bluetooth.BluetoothAdapter;
import
android.content.Intent;
import
android.os.Bundle;
import
android.view.View;
import
android.widget.Button;
import
androidx.appcompat.app.AppCompatActivity;
public
class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter =
BluetoothAdapter.getDefaultAdapter();
Button toggleButton =
findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
toggleBluetooth();
}
});
}
private void toggleBluetooth() {
if (bluetoothAdapter == null) {
// Device does not support
Bluetooth
return;
}
if (bluetoothAdapter.isEnabled()) {
// Bluetooth is currently enabled,
turn it off
bluetoothAdapter.disable();
} else {
// Bluetooth is currently disabled,
turn it on
Intent enableBluetoothIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, 1);
}
}
}
Output :
==========================================================================
Q19. Write an android
application using SQLite to create table and perform CRUD operations (Example.
COURSE table (ID, Name, Duration, Description), perform ADD, UPDATE, DELETE and
READ operations)
Activity_main.xml
<?xml version="1.0"
encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<!-- Name -->
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"/>
<!-- Duration -->
<EditText
android:id="@+id/editTextDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editTextName"
android:layout_marginTop="16dp"
android:hint="Duration"/>
<!-- Description -->
<EditText
android:id="@+id/editTextDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editTextDuration"
android:layout_marginTop="16dp"
android:hint="Description"/>
<!-- Add Button -->
<Button
android:id="@+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editTextDescription"
android:layout_marginTop="16dp"
android:text="Add"/>
<!-- Read Button -->
<Button
android:id="@+id/buttonRead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/buttonAdd"
android:layout_marginTop="16dp"
android:text="Read"/>
<!-- Update Button -->
<Button
android:id="@+id/buttonUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/buttonRead"
android:layout_marginTop="16dp"
android:text="Update"/>
<!-- Delete Button -->
<Button
android:id="@+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/buttonUpdate"
android:layout_marginTop="16dp"
android:text="Delete"/>
</RelativeLayout>
MainActivity.java
package com.example.a19;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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 {
private EditText etName, etDuration,
etDescription;
private Button btnAdd, btnRead,
btnUpdate, btnDelete;
private DatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName =
findViewById(R.id.editTextName);
etDuration =
findViewById(R.id.editTextDuration);
etDescription =
findViewById(R.id.editTextDescription);
btnAdd =
findViewById(R.id.buttonAdd);
btnRead = findViewById(R.id.buttonRead);
btnUpdate =
findViewById(R.id.buttonUpdate);
btnDelete =
findViewById(R.id.buttonDelete);
dbHelper = new
DatabaseHelper(this);
btnAdd.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View
view) {
addCourse();
}
});
btnRead.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View
view) {
readCourses();
}
});
btnUpdate.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View
view) {
updateCourse();
}
});
btnDelete.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View
view) {
deleteCourse();
}
});
}
private void addCourse() {
SQLiteDatabase db =
dbHelper.getWritableDatabase();
ContentValues values = new
ContentValues();
values.put(DatabaseHelper.COLUMN_NAME, etName.getText().toString());
values.put(DatabaseHelper.COLUMN_DURATION,
etDuration.getText().toString());
values.put(DatabaseHelper.COLUMN_DESCRIPTION,
etDescription.getText().toString());
long newRowId =
db.insert(DatabaseHelper.TABLE_NAME, null, values);
showToast(newRowId != -1 ?
"Course added successfully!" : "Error adding course.");
db.close();
}
private void readCourses() {
SQLiteDatabase db =
dbHelper.getReadableDatabase();
String[] projection = {
DatabaseHelper.COLUMN_ID,
DatabaseHelper.COLUMN_NAME,
DatabaseHelper.COLUMN_DURATION,
DatabaseHelper.COLUMN_DESCRIPTION
};
Cursor cursor = db.query(
DatabaseHelper.TABLE_NAME,
projection,
null,
null,
null,
null,
null
);
StringBuilder result = new
StringBuilder("Courses:\n");
while (cursor.moveToNext()) {
long id =
cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ID));
String name =
cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_NAME));
String duration =
cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_DURATION));
String description =
cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_DESCRIPTION));
result.append("ID:
").append(id).append(", Name: ").append(name)
.append(",
Duration: ").append(duration).append(", Description:
").append(description).append("\n");
}
showToast(result.toString());
cursor.close();
db.close();
}
private void updateCourse() {
SQLiteDatabase db =
dbHelper.getWritableDatabase();
ContentValues values = new
ContentValues();
values.put(DatabaseHelper.COLUMN_NAME,
etName.getText().toString());
values.put(DatabaseHelper.COLUMN_DURATION,
etDuration.getText().toString());
values.put(DatabaseHelper.COLUMN_DESCRIPTION,
etDescription.getText().toString());
String selection =
DatabaseHelper.COLUMN_ID + " = ?";
String[] selectionArgs =
{String.valueOf(1)}; // You need to provide the course ID for update
int count = db.update(
DatabaseHelper.TABLE_NAME,
values,
selection,
selectionArgs
);
showToast(count > 0 ?
"Course updated successfully!" : "Error updating course.");
db.close();
}
private void deleteCourse() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
String selection =
DatabaseHelper.COLUMN_ID + " = ?";
String[] selectionArgs =
{String.valueOf(1)}; // You need to provide the course ID for delete
int count = db.delete(
DatabaseHelper.TABLE_NAME,
selection,
selectionArgs
);
showToast(count > 0 ?
"Course deleted successfully!" : "Error deleting course.");
db.close();
}
private void showToast(String
message) {
Toast.makeText(this, message,
Toast.LENGTH_SHORT).show();
}
}
DatabaseHelper.java
package com.example.a19;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String
DATABASE_NAME = "courses.db";
private static final int
DATABASE_VERSION = 1;
public static final String TABLE_NAME
= "COURSE";
public static final String COLUMN_ID
= "ID";
public static final String
COLUMN_NAME = "Name";
public static final String
COLUMN_DURATION = "Duration";
public static final String
COLUMN_DESCRIPTION = "Description";
private static final String
SQL_CREATE_TABLE =
"CREATE TABLE " +
TABLE_NAME + " (" +
COLUMN_ID + "
INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + "
TEXT," +
COLUMN_DURATION +
" TEXT," +
COLUMN_DESCRIPTION + "
TEXT)";
private static final String
SQL_DELETE_TABLE =
"DROP TABLE IF EXISTS
" + TABLE_NAME;
public DatabaseHelper(Context
context) {
super(context, DATABASE_NAME,
null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase
db) {
db.execSQL(SQL_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase
db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_TABLE);
onCreate(db);
}
}
Output:-
==========================================================================
Q20.
Create an Android app, powered by Firebase Realtime database that supports:
Adding Data to Firebase Realtime database, Retrieving Data from Firebase and
Deleting data from firebase data.
Activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter
data"/>
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add
Data"/>
<Button
android:id="@+id/btnRetrieve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retrieve
Data"/>
<Button
android:id="@+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete
Data"/>
<TextView
android:id="@+id/textViewData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"/>
</LinearLayout>
MainActivity.java
package com.example.a20;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.*;
public class MainActivity extends AppCompatActivity {
private EditText editTextData;
private TextView textViewData;
private DatabaseReference
database;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextData =
findViewById(R.id.editTextData);
textViewData =
findViewById(R.id.textViewData);
// Get the Firebase
reference
database =
FirebaseDatabase.getInstance().getReference();
Button btnAdd =
findViewById(R.id.btnAdd);
Button btnRetrieve =
findViewById(R.id.btnRetrieve);
Button btnDelete =
findViewById(R.id.btnDelete);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void
onClick(View view) {
addData();
}
});
btnRetrieve.setOnClickListener(new View.OnClickListener() {
@Override
public void
onClick(View view) {
retrieveData();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void
onClick(View view) {
deleteData();
}
});
}
private void addData() {
String data =
editTextData.getText().toString().trim();
if (!data.isEmpty()) {
String key =
database.child("data").push().getKey();
if (key != null) {
database.child("data").child(key).setValue(data);
editTextData.getText().clear();
}
}
}
private void retrieveData() {
database.child("data").addListenerForSingleValueEvent(new
ValueEventListener() {
@Override
public void
onDataChange(@NonNull DataSnapshot snapshot) {
StringBuilder
dataStringBuilder = new StringBuilder();
for (DataSnapshot
childSnapshot : snapshot.getChildren()) {
String data =
childSnapshot.getValue(String.class);
if (data !=
null) {
dataStringBuilder.append(data).append("\n");
}
}
textViewData.setText(dataStringBuilder.toString());
}
@Override
public void
onCancelled(@NonNull DatabaseError error) {
// Handle error
}
});
}
private void deleteData() {
// Delete all data in the
"data" node
database.child("data").removeValue();
textViewData.setText("");
}
}
Output:-
==========================================================================
Q21.
Write an android app to write JSON data into a file and read JSON data from
created file
Activity_main.xml
<?xml
version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/buttonWrite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Write JSON to
File"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"/>
<Button
android:id="@+id/buttonRead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read JSON from
File"
android:layout_below="@id/buttonWrite"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"/>
<TextView
android:id="@+id/textViewOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_below="@id/buttonRead"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"/>
</RelativeLayout>
MainActivity.java
package com.example.a21;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private static final String FILE_NAME
= "json_data.json";
private TextView textViewOutput;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonWrite =
findViewById(R.id.buttonWrite);
Button buttonRead =
findViewById(R.id.buttonRead);
textViewOutput =
findViewById(R.id.textViewOutput);
buttonWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
writeJsonToFile();
}
});
buttonRead.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
readJsonFromFile();
}
});
}
private void writeJsonToFile() {
try {
// Create a JSON object
JSONObject jsonObject = new
JSONObject();
jsonObject.put("name", "Bhupendra Jogi");
jsonObject.put("age", 29);
jsonObject.put("city", "New
York");
// Convert the JSON object to
a string
String jsonString =
jsonObject.toString();
// Write the JSON string to a
file
FileOutputStream
fileOutputStream = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fileOutputStream.write(jsonString.getBytes());
fileOutputStream.close();
Log.d("WriteJsonToFile", "JSON data written to file
successfully");
} catch (JSONException |
IOException e) {
e.printStackTrace();
}
}
private void readJsonFromFile() {
try {
// Read the JSON string from
the file
InputStream inputStream =
openFileInput(FILE_NAME);
InputStreamReader inputStreamReader
= new InputStreamReader(inputStream);
BufferedReader bufferedReader
= new BufferedReader(inputStreamReader);
StringBuilder stringBuilder =
new StringBuilder();
String line;
while ((line = bufferedReader.readLine())
!= null) {
stringBuilder.append(line);
}
inputStream.close();
// Convert the JSON string to
a JSON object
JSONObject jsonObject = new
JSONObject(stringBuilder.toString());
// Display the JSON data in
the TextView
String output = "Name:
" + jsonObject.getString("name") +
"\nAge: " +
jsonObject.getInt("age") +
"\nCity: "
+ jsonObject.getString("city");
textViewOutput.setText(output);
Log.d("ReadJsonFromFile", "JSON data read from file
successfully");
} catch (JSONException |
IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
Output:-
==========================================================================
Q22.Demonstrate
flutter application using android.
import
'package:flutter/material.dart';
void
main() {
runApp(MyApp());
}
class
MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Counter App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class
MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() =>
_MyHomePageState();
}
class
_MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter:',
style: TextStyle(fontSize: 20),
),
Text(
'$_counter',
style: TextStyle(fontSize: 40,
fontWeight: FontWeight.bold),
),
],
),
),
floatingActionButton:
FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
void _incrementCounter() {
setState(() {
_counter++;
});
}}
0 Comments