Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Q.1 - How To Build A Simple Calculator App Using Android Studio? XML

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 63

Q.1 - How to build a simple Calculator app using Android Studio?

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"
android:background="#8BC34A"
android:backgroundTint="@android:color/darker_gray"
tools:context=".MainActivity">

<!-- Text View to display our basic heading of "calculator"-->


<TextView
android:layout_width="194dp"
android:layout_height="43dp"
android:layout_marginStart="114dp"
android:layout_marginLeft="114dp"
android:layout_marginTop="58dp"
android:layout_marginEnd="103dp"
android:layout_marginRight="103dp"
android:layout_marginBottom="502dp"
android:scrollbarSize="30dp"
android:text=" Calculator"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Edit Text View to input the values -->


<EditText
android:id="@+id/num1"
android:layout_width="364dp"
android:layout_height="28dp"
android:layout_marginStart="72dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="416dp"
android:background="@android:color/white"
android:ems="10"
android:onClick="clearTextNum1"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Edit Text View to input 2nd value-->


<EditText
android:id="@+id/num2"
android:layout_width="363dp"
android:layout_height="30dp"
android:layout_marginStart="72dp"
android:layout_marginTop="112dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="374dp"
android:background="@android:color/white"
android:ems="10"
android:onClick="clearTextNum2"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Text View to display result -->


<TextView
android:id="@+id/result"
android:layout_width="356dp"
android:layout_height="71dp"
android:layout_marginStart="41dp"
android:layout_marginTop="151dp"
android:layout_marginEnd="48dp"
android:layout_marginBottom="287dp"
android:background="@android:color/white"
android:text="result"
android:textColorLink="#673AB7"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform 'sum' operation -->


<Button
android:id="@+id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doSum"
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform subtraction operation. -->

<!-- A button to perform division. -->


<Button
android:id="@+id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="210dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="113dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doSub"
android:text="-"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.507" />

<Button
android:id="@+id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="307dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doDiv"
android:text="/"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform multiplication. -->


<Button
android:id="@+id/mul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMul"
android:text="x"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform a modulus function. -->


<!-- A button to perform a power function. -->

<Button
android:id="@+id/button"
android:layout_width="103dp"
android:layout_height="46dp"
android:layout_marginStart="113dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="206dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMod"
android:text="%(mod)"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.515" />

<Button
android:id="@+id/pow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="113dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="210dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doPow"
android:text="n1^n2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.507" />

</androidx.constraintlayout.widget.ConstraintLayout>

JAVA
package com.example.calculator2;

import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.text.TextUtils;
import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.calculator2.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private AppBarConfiguration appBarConfiguration;


private ActivityMainBinding binding;
public EditText e1, e2;
TextView t1;
int num1, num2;

public boolean getNumbers() {

//checkAndClear();
// defining the edit text 1 to e1
e1 = (EditText) findViewById(R.id.num1);

// defining the edit text 2 to e2


e2 = (EditText) findViewById(R.id.num2);

// defining the text view to t1


t1 = (TextView) findViewById(R.id.result);

// taking input from text box 1


String s1 = e1.getText().toString();

// taking input from text box 2


String s2 = e2.getText().toString();

if(s1.equals("Please enter value 1") && s2.equals(null))


{
String result = "Please enter value 2";
e2.setText(result);
return false;
}
if(s1.equals(null) && s2.equals("Please enter value 2"))
{
String result = "Please enter value 1";
e1.setText(result);
return false;
}
if(s1.equals("Please enter value 1") || s2.equals("Please enter value 2"))
{
return false;
}

if((!s1.equals(null) && s2.equals(null))|| (!s1.equals("") && s2.equals("")) ){

String result = "Please enter value 2";

e2.setText(result);
return false;
}
if((s1.equals(null) && !s2.equals(null))|| (s1.equals("") && !s2.equals("")) ){
//checkAndClear();
String result = "Please enter value 1";
e1.setText(result);
return false;
}
if((s1.equals(null) && s2.equals(null))|| (s1.equals("") && s2.equals("")) ){
//checkAndClear();
String result1 = "Please enter value 1";
e1.setText(result1);
String result2 = "Please enter value 2";
e2.setText(result2);
return false;
}

else {
// converting string to int.
num1 = Integer.parseInt(s1);

// converting string to int.


num2 = Integer.parseInt(s2);

return true;
}

public void doSum(View v) {

// get the input numbers


if (getNumbers()) {
int sum = num1 + num2;
t1.setText(Integer.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}

}
public void clearTextNum1(View v) {

// get the input numbers


e1.getText().clear();
}
public void clearTextNum2(View v) {

// get the input numbers


e2.getText().clear();
}
public void doPow(View v) {

//checkAndClear();
// get the input numbers
if (getNumbers()) {
double sum = Math.pow(num1, num2);
t1.setText(Double.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}

// a public method to perform subtraction


public void doSub(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
int sum = num1 - num2;
t1.setText(Integer.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}

// a public method to perform multiplication


public void doMul(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
int sum = num1 * num2;
t1.setText(Integer.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}

// a public method to perform Division


public void doDiv(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
// displaying the text in text view assigned as t1
double sum = num1 / (num2 * 1.0);
t1.setText(Double.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}

// a public method to perform modulus function


public void doMod(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
double sum = num1 % num2;
t1.setText(Double.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.num1);
// defining the edit text 2 to e2
e2 = (EditText) findViewById(R.id.num2);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}

Q.2 Create an app that explores life cycle of an activity?


=>
JAVA
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",
Toast.LENGTH_LONG).show();
}

protected void onStart() {


super.onStart();
Toast toast = Toast.makeText(getApplicationContext(), "onStart Called",
Toast.LENGTH_LONG).show();
}

@Override
protected void onRestart() {
super.onRestart();
Toast toast = Toast.makeText(getApplicationContext(), "onRestart Called",
Toast.LENGTH_LONG).show();
}

protected void onPause() {


super.onPause();
Toast toast = Toast.makeText(getApplicationContext(), "onPause Called",
Toast.LENGTH_LONG).show();
}

protected void onResume() {


super.onResume();
Toast toast = Toast.makeText(getApplicationContext(), "onResume Called",
Toast.LENGTH_LONG).show();
}

protected void onStop() {


super.onStop();
Toast toast = Toast.makeText(getApplicationContext(), "onStop Called",
Toast.LENGTH_LONG).show();
}
protected void onDestroy() {
super.onDestroy();
Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called",
Toast.LENGTH_LONG).show();
}
}

Q.3 Create an app of registration form ?


=>
XML(Main Activity)

<?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">

<!--text view for heading-->


<TextView
android:id="@+id/idTVHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:padding="5dp"
android:text="Welcome to Geeks for Geeks \n Register Form"
android:textAlignment="center"
android:textColor="@color/purple_700"
android:textSize="18sp" />

<!--edit text for user name-->


<EditText
android:id="@+id/idEdtUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idTVHeader"
android:layout_marginStart="10dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="10dp"
android:hint="Enter UserName"
android:inputType="textEmailAddress" />

<!--edit text for user password-->


<EditText
android:id="@+id/idEdtPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtUserName"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Enter Password"
android:inputType="textPassword" />

<!--button to register our new user-->


<Button
android:id="@+id/idBtnRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtPassword"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:text="Register User"
android:textAllCaps="false" />

</RelativeLayout>

JAVA(Main Activity )

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;

public class MainActivity extends AppCompatActivity {

// creating variables for our edit text and buttons.


private EditText userNameEdt, passwordEdt;
private Button registerBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// initializing our edit text and buttons.


userNameEdt = findViewById(R.id.idEdtUserName);
passwordEdt = findViewById(R.id.idEdtPassword);
registerBtn = findViewById(R.id.idBtnRegister);

// adding on click listener for our button.


registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line we are getting data from our edit text.
String userName = userNameEdt.getText().toString();
String password = passwordEdt.getText().toString();

// checking if the entered text is empty or not.


if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password)) {
Toast.makeText(MainActivity.this, "Please enter user name and password",
Toast.LENGTH_SHORT).show();
}

// calling a method to register a user.


registerUser(userName, password);
}
});
}

private void registerUser(String userName, String password) {

// on below line we are creating


// a new user using parse user.
ParseUser user = new ParseUser();

// Set the user's username and password,


// which can be obtained from edit text
user.setUsername(userName);
user.setPassword(password);

// calling a method to register the user.


user.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
// on user registration checking if
// the error is null or not.
if (e == null) {
// if the error is null we are displaying a toast message and
// redirecting our user to new activity and passing the user name.
Toast.makeText(MainActivity.this, "User Registered successfully",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, HomeActivity.class);
i.putExtra("username", userName);
startActivity(i);
} else {
// if we get any error then we are logging out
// our user and displaying an error message
ParseUser.logOut();
Toast.makeText(MainActivity.this, "Fail to Register User..", Toast.LENGTH_SHORT).show();
}
}
});
}
}

Q.4 Create a simple game ?


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:id="@+id/rlVar1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!--TextView to display game instruction-->


<TextView
android:id="@+id/tvVar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="20dp"
android:text="Click on Start first, and wait
until the background color changes.
As soon as it changes hit Stop"
android:textSize="25dp" />

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tvVar1"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:padding="20dp">

<!--start button-->
<Button
android:id="@+id/btVar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Start" />

<!--stop button-->
<Button
android:id="@+id/btVar2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Stop" />

</LinearLayout>

</RelativeLayout>

JAVA

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

public Button button1, button2;


public RelativeLayout relativeLayout;

// runnable function
Runnable runnable = new Runnable() {
@Override
public void run() {

// set the background on the screen


relativeLayout.setBackgroundResource(R.color.green);

// get the system time in milli second


// when the screen background is set
final long time = System.currentTimeMillis();

// function when stop button is clicked


button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// get the system time in milli second
// when the stop button is clicked
long time1 = System.currentTimeMillis();

// display reflex time in toast message


Toast.makeText(getApplicationContext(), "Your reflexes takes " + (time1 - time) + " time to
work", Toast.LENGTH_LONG).show();

// remove the background again


relativeLayout.setBackgroundResource(0);
}
});
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

relativeLayout = findViewById(R.id.rlVar1);
button1 = findViewById(R.id.btVar1);
button2 = findViewById(R.id.btVar2);

// function when the start button is clicked


button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

// generate a random number from 1-10


Random random = new Random();
int num = random.nextInt(10);

// call the runnable function after


// a post delay of num seconds
Handler handler = new Handler();
handler.postDelayed(runnable, num * 1000);
}
});
}
}

Q.5 Create a music player using spinner?

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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
android:orientation="vertical"
android:theme="@style/Theme.AppCompat"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="430dp"
android:background="@drawable/download"
android:contentDescription="@string/todo" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="@color/colorAccent"
android:orientation="horizontal"
android:padding="10dp">

<Button
android:id="@+id/pause"
style="@style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="125dp"
android:layout_height="match_parent"
android:background="@android:drawable/ic_media_pause"
android:onClick="musicpause" />

<Button
android:id="@+id/start"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="125dp"
android:layout_height="match_parent"
android:background="@android:drawable/ic_media_play"
android:onClick="musicplay" />

<Button
android:id="@+id/stop"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="125dp"
android:layout_height="match_parent"
android:background="@android:drawable/ic_delete"
android:onClick="musicstop" />
</LinearLayout>
</LinearLayout>

JAVA

package com.example.amusinz;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity


extends AppCompatActivity {

// Instantiating the MediaPlayer class


MediaPlayer music;

@Override
protected void onCreate(
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Adding the music file to our


// newly created object music
music = MediaPlayer.create(
this, R.raw.sound);
}

// Plaing the music


public void musicplay(View v)
{
music.start();
}

// Pausing the music


public void musicpause(View v)
{
music.pause();
}
// Stoping the music
public void musicstop(View v)
{
music.stop();
music
= MediaPlayer.create(
this, R.raw.sound);
}
}

Q. 6 Create a chat application ?

XML =>

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@android:color/white"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- (RecyclerView with chat messages view will go here) -->

<RelativeLayout
android:id="@+id/rlSend"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:paddingTop="5dp"
android:paddingBottom="10dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/etMessage"
android:layout_toLeftOf="@+id/ibSend"
android:layout_alignBottom="@+id/ibSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:hint="@string/message_hint"
android:inputType="textShortMessage"
android:imeOptions="actionSend"
/>
<ImageButton
android:id="@+id/ibSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingRight="10dp"
android:layout_alignParentRight="true"
android:contentDescription="@string/send"
android:src="@drawable/ic_baseline_send_24"
android:textSize="18sp" />
</RelativeLayout>
</RelativeLayout>
JAVA (Login)

public class ChatActivity extends AppCompatActivity {


static final String TAG = ChatActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
// User login

if (ParseUser.getCurrentUser() != null) { // start with existing user

startWithCurrentUser();
} else { // If not logged in, login as a new anonymous user

login();
}
}

// Get the userId from the cached currentUser object

void startWithCurrentUser() {
// TODO:

// Create an anonymous user using ParseAnonymousUtils and set sUserId

void login() {
ParseAnonymousUtils.logIn(new LogInCallback() {
@Override
public void done(ParseUser user, ParseException e) {
if (e != null) {
Log.e(TAG, "Anonymous login failed: ", e);
} else {
startWithCurrentUser();
}
}
});
}
}

class ChatActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
// User login
if (ParseUser.getCurrentUser() != null) { // start with existing user
startWithCurrentUser()
} else { // If not logged in, login as a new anonymous user
login()
}
}

// Get the userId from the cached currentUser object


fun startWithCurrentUser() {
// TODO:
}

// Create an anonymous user using ParseAnonymousUtils and set sUserId


fun login() {
ParseAnonymousUtils.logIn { user, e ->
if (e != null) {
Log.e(TAG, "Anonymous login failed: ", e)
} else {
startWithCurrentUser()
}
}
}

companion object {
val TAG: String = "ChatActivity"
}
}

SAVE MESSAGE

public class ChatActivity extends AppCompatActivity {

static final String USER_ID_KEY = "userId";


static final String BODY_KEY = "body";

EditText etMessage;
ImageButton ibSend;

// Get the userId from the cached currentUser object

void startWithCurrentUser() {
setupMessagePosting();
}

// Set up button event handler which posts the entered message to Parse

void setupMessagePosting() {
// Find the text field and button
etMessage = (EditText) findViewById(R.id.etMessage);
ibSend = (ImageButton) findViewById(R.id.ibSend);

// When send button is clicked, create message object on Parse

ibSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data = etMessage.getText().toString();
ParseObject message = ParseObject.create("Message");
message.put(USER_ID_KEY, ParseUser.getCurrentUser().getObjectId());
message.put(BODY_KEY, data);
message.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(ChatActivity.this, "Successfully
created message on Parse",
Toast.LENGTH_SHORT).show();
} else {
Log.e(TAG, "Failed to save message", e);
}
}
});
etMessage.setText(null);
}
});
}
}

val USER_ID_KEY = "userId"


val BODY_KEY = "body"

var etMessage: EditText? = null


var ibSend: ImageButton? = null

// Get the userId from the cached currentUser object


fun startWithCurrentUser() {
setupMessagePosting()
}

// Set up button event handler which posts the entered message to Parse
fun setupMessagePosting() {
// Find the text field and button
etMessage = findViewById<View>(R.id.etMessage) as EditText
ibSend = findViewById<View>(R.id.ibSend) as ImageButton

// When send button is clicked, create message object on Parse


ibSend.setOnClickListener(object : OnClickListener() {
fun onClick(v: View?) {
val data: String = etMessage.getText().toString()
val message = ParseObject.create("Message")
message.put(USER_ID_KEY, ParseUser.getCurrentUser().objectId)
message.put(BODY_KEY, data)
message.saveInBackground(object : SaveCallback {
override fun done(e: ParseException?) {
if (e == null) {
Toast.makeText(
this@ChatActivity, "Successfully created message on
Parse",
Toast.LENGTH_SHORT
).show()
} else {
Log.e(TAG, "Failed to save message", e)
}
}
})
etMessage.setText(null)
}
})
}

Q. 7 Create an application using navigation drawer?


XML =>

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="HardcodedText">

<item
android:id="@+id/nav_account"
android:title="My Account" />

<item
android:id="@+id/nav_settings"
android:title="Settings" />

<item
android:id="@+id/nav_logout"
android:title="Logout" />

</menu>

<?xml version="1.0" encoding="utf-8"?>

<!--the root view must be the DrawerLayout-->


<androidx.drawerlayout.widget.DrawerLayout
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:id="@+id/my_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="128dp"
android:gravity="center"
android:text="GeeksforGeeks"
android:textSize="18sp" />

</LinearLayout>

<!--this the navigation view which draws


and shows the navigation drawer-->
<!--include the menu created in the menu folder-->
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

JAVA

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import android.os.Bundle;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {


public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// drawer layout instance to toggle the menu icon to open


// drawer and back button to close drawer
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.string.nav_open, R.string.nav_close);

// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();

// to make the Navigation drawer icon always appear on the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

// override the onOptionsItemSelected()


// function to implement
// the item click listener callback
// to open and close the navigation
// drawer when the icon is clicked
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Q.8 Create an application of notification ?


XML =>

<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/button"
android:layout_marginTop="62dp"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

</RelativeLayout>

JAVA

package com.example.notificationdemo;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {


Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}

private void addNotification() {


NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");

Intent notificationIntent = new Intent(this, MainActivity.class);


PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);

// Add as notification
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}

Q. 9 Create an application of game ?


XML =>
1 - 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">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

2 – bars.xml
<?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="60dp"
android:background="@drawable/shapeofthebar"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:id="@+id/barlayout"
android:orientation="horizontal">
</LinearLayout>

3 - shapeofthebar.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white" />
<corners android:radius="19dp"/>
</shape>

JAVA
4 - MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

// Creating RecyclerView
private RecyclerView recyclerView;
// Creating a ArrayList of type Modelclass
private List<Modelclass> barsColor;

// Alert dialog
AlertDialog.Builder alertDialog;
private Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Adding elements to the barsColor


barsColor=new ArrayList<>();
Random random = new Random();
// Add 15 bars to the RecyclerView
for(int i=0;i<15;i++)
{
// Generate a random number
int n= random.nextInt(2);
// Giving the color for the
// bar based on the random number
if(n==0)
{
barsColor.add(new Modelclass("Yellow"));
}
else
{
barsColor.add(new Modelclass("Red"));
}
}

// Finding the RecyclerView by it's ID


recyclerView = findViewById(R.id.recyclerview);

// Creating an Adapter Object


adapter=new Adapter(this,barsColor);

recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

// Add ItemTouchHelper to the recyclerView


ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);

adapter.notifyDataSetChanged();

ItemTouchHelper.SimpleCallback simpleCallback= new


ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull
RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull @NotNull RecyclerView.ViewHolder viewHolder, int direction)
{
// get the position of the swiped bar
int position = viewHolder.getPosition();
switch (direction) {
// Right side is for Yellow
case ItemTouchHelper.LEFT: {
if ((barsColor.get(position).getColor()).equals("Red")) {
barsColor.remove(position);
adapter.notifyDataSetChanged();
} else {
endthegame();
adapter.notifyDataSetChanged();
alertDialog.show();
}
break;
}
// Left side is for Red
case ItemTouchHelper.RIGHT: {
if ((barsColor.get(position).getColor()).equals("Yellow")) {
barsColor.remove(position);
adapter.notifyDataSetChanged();
} else {
endthegame();
adapter.notifyDataSetChanged();
alertDialog.show();
}
break;
}
}
}
};

// Shows game ended dialog


private void endthegame()
{
alertDialog=new AlertDialog.Builder(this);
alertDialog.setMessage("Oopa! Wrong side! Try Again! ").setPositiveButton("Try Again", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Try again", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Later!", Toast.LENGTH_SHORT).show();
}
});
alertDialog.create();
}
}

5 - Adapter.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.ColorSpace;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

List<Modelclass> bars;
Context context;

Adapter(Context c, List<Modelclass> list )


{
bars=list;
context = c;
}

@NonNull
@NotNull
@Override
@SuppressLint("ResourceType")
public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bars,parent,false);
return new ViewHolder(view);
}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onBindViewHolder(@NonNull @NotNull Adapter.ViewHolder holder, int position) {

// Getting the color for every position


String color = bars.get(position).getColor();

// Set the color to the bar


if (color.equals("Yellow"))
{
holder.linearLayout.setBackgroundTintList(context.getResources().getColorStateList(R.color.yell
ow));
}
else
{
holder.linearLayout.setBackgroundTintList(context.getResources().getColorStateList(R.color.Re
d));
}
}

@Override
public int getItemCount() {
return bars.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {


LinearLayout linearLayout;
public ViewHolder(@NonNull @org.jetbrains.annotations.NotNull View itemView) {
super(itemView);
linearLayout=itemView.findViewById(R.id.barlayout);
}
}
}

Q.10 create an application of android tutorial using sqlite ?

XML =>
1 - AndroidManifest.xml

<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
2 – 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">

<!--Edit text to enter course name-->


<EditText
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter course Name" />

<!--edit text to enter course duration-->


<EditText
android:id="@+id/idEdtCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Duration" />
<!--edit text to display course tracks-->
<EditText
android:id="@+id/idEdtCourseTracks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Tracks" />

<!--edit text for course description-->


<EditText
android:id="@+id/idEdtCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Description" />

<!--button for adding new course-->


<Button
android:id="@+id/idBtnAddCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Add Course"
android:textAllCaps="false" />

</LinearLayout>
JAVA
3- sqlitejavacon.java

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHandler extends SQLiteOpenHelper {

// creating a constant variables for our database.


// below variable is for our database name.
private static final String DB_NAME = "coursedb";

// below int is our database version


private static final int DB_VERSION = 1;

// below variable is for our table name.


private static final String TABLE_NAME = "mycourses";

// below variable is for our id column.


private static final String ID_COL = "id";

// below variable is for our course name column


private static final String NAME_COL = "name";

// below variable id for our course duration column.


private static final String DURATION_COL = "duration";

// below variable for our course description column.


private static final String DESCRIPTION_COL = "description";

// below variable is for our course tracks column.


private static final String TRACKS_COL = "tracks";

// creating a constructor for our database handler.


public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}

// below method is for creating a database by running a sqlite query


@Override
public void onCreate(SQLiteDatabase db) {
// on below line we are creating
// an sqlite query and we are
// setting our column names
// along with their data types.
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COL + " TEXT,"
+ DURATION_COL + " TEXT,"
+ DESCRIPTION_COL + " TEXT,"
+ TRACKS_COL + " TEXT)";
// at last we are calling a exec sql
// method to execute above sql query
db.execSQL(query);
}

// this method is use to add new course to our sqlite database.


public void addNewCourse(String courseName, String courseDuration, String courseDescription,
String courseTracks) {

// on below line we are creating a variable for


// our sqlite database and calling writable method
// as we are writing data in our database.
SQLiteDatabase db = this.getWritableDatabase();

// on below line we are creating a


// variable for content values.
ContentValues values = new ContentValues();

// on below line we are passing all values


// along with its key and value pair.
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL, courseDescription);
values.put(TRACKS_COL, courseTracks);

// after adding all values we are passing


// content values to our table.
db.insert(TABLE_NAME, null, values);
// at last we are closing our
// database after adding database.
db.close();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// this method is called to check if the table exists already.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

4 - MainActivity.java

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 {

// creating variables for our edittext, button and dbhandler


private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;
private Button addCourseBtn;
private DBHandler dbHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// initializing all our variables.


courseNameEdt = findViewById(R.id.idEdtCourseName);
courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
addCourseBtn = findViewById(R.id.idBtnAddCourse);

// creating a new dbhandler class


// and passing our context to it.
dbHandler = new DBHandler(MainActivity.this);

// below line is to add on click listener for our add course button.
addCourseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

// below line is to get data from all edit text fields.


String courseName = courseNameEdt.getText().toString();
String courseTracks = courseTracksEdt.getText().toString();
String courseDuration = courseDurationEdt.getText().toString();
String courseDescription = courseDescriptionEdt.getText().toString();

// validating if the text fields are empty or not.


if (courseName.isEmpty() && courseTracks.isEmpty() && courseDuration.isEmpty() &&
courseDescription.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter all the data..", Toast.LENGTH_SHORT).show();
return;
}

// on below line we are calling a method to add new


// course to sqlite data and pass all our values to it.
dbHandler.addNewCourse(courseName, courseDuration, courseDescription, courseTracks);

// after adding the data we are displaying a toast message.


Toast.makeText(MainActivity.this, "Course has been added.", Toast.LENGTH_SHORT).show();
courseNameEdt.setText("");
courseDurationEdt.setText("");
courseTracksEdt.setText("");
courseDescriptionEdt.setText("");
}
});
}
}

You might also like