Q.1 - How to build a simple Calculator app using Android Studio?
XML
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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/[Link].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" />
</[Link]>
JAVA
package [Link].calculator2;
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];
import [Link];
import [Link];
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([Link].num1);
// defining the edit text 2 to e2
e2 = (EditText) findViewById([Link].num2);
// defining the text view to t1
t1 = (TextView) findViewById([Link]);
// taking input from text box 1
String s1 = [Link]().toString();
// taking input from text box 2
String s2 = [Link]().toString();
if([Link]("Please enter value 1") && [Link](null))
{
String result = "Please enter value 2";
[Link](result);
return false;
}
if([Link](null) && [Link]("Please enter value 2"))
{
String result = "Please enter value 1";
[Link](result);
return false;
}
if([Link]("Please enter value 1") || [Link]("Please enter value 2"))
{
return false;
}
if(( && [Link](null))|| ( && [Link]("")) ){
String result = "Please enter value 2";
[Link](result);
return false;
}
if(([Link](null) && )|| ([Link]("") && ) ){
//checkAndClear();
String result = "Please enter value 1";
[Link](result);
return false;
}
if(([Link](null) && [Link](null))|| ([Link]("") && [Link]("")) ){
//checkAndClear();
String result1 = "Please enter value 1";
[Link](result1);
String result2 = "Please enter value 2";
[Link](result2);
return false;
}
else {
// converting string to int.
num1 = [Link](s1);
// converting string to int.
num2 = [Link](s2);
return true;
}
public void doSum(View v) {
// get the input numbers
if (getNumbers()) {
int sum = num1 + num2;
[Link]([Link](sum));
}
else
{
[Link]("Error Please enter Required Values");
}
}
public void clearTextNum1(View v) {
// get the input numbers
[Link]().clear();
}
public void clearTextNum2(View v) {
// get the input numbers
[Link]().clear();
}
public void doPow(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
double sum = [Link](num1, num2);
[Link]([Link](sum));
}
else
{
[Link]("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;
[Link]([Link](sum));
}
else
{
[Link]("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;
[Link]([Link](sum));
}
else
{
[Link]("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);
[Link]([Link](sum));
}
else
{
[Link]("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;
[Link]([Link](sum));
}
else
{
[Link]("Error Please enter Required Values");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
e1 = (EditText) findViewById([Link].num1);
// defining the edit text 2 to e2
e2 = (EditText) findViewById([Link].num2);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link].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 [Link].
int id = [Link]();
//noinspection SimplifiableIfStatement
if (id == [Link].action_settings) {
return true;
}
return [Link](item);
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = [Link](this,
[Link].nav_host_fragment_content_main);
return [Link](navController, appBarConfiguration)
|| [Link]();
}
}
Q.2 Create an app that explores life cycle of an activity?
=>
JAVA
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Toast toast = [Link](getApplicationContext(), "onCreate Called",
Toast.LENGTH_LONG).show();
}
protected void onStart() {
[Link]();
Toast toast = [Link](getApplicationContext(), "onStart Called",
Toast.LENGTH_LONG).show();
}
@Override
protected void onRestart() {
[Link]();
Toast toast = [Link](getApplicationContext(), "onRestart Called",
Toast.LENGTH_LONG).show();
}
protected void onPause() {
[Link]();
Toast toast = [Link](getApplicationContext(), "onPause Called",
Toast.LENGTH_LONG).show();
}
protected void onResume() {
[Link]();
Toast toast = [Link](getApplicationContext(), "onResume Called",
Toast.LENGTH_LONG).show();
}
protected void onStop() {
[Link]();
Toast toast = [Link](getApplicationContext(), "onStop Called",
Toast.LENGTH_LONG).show();
}
protected void onDestroy() {
[Link]();
Toast toast = [Link](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="[Link]
xmlns:tools="[Link]
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 [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 {
// creating variables for our edit text and buttons.
private EditText userNameEdt, passwordEdt;
private Button registerBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// initializing our edit text and buttons.
userNameEdt = findViewById([Link]);
passwordEdt = findViewById([Link]);
registerBtn = findViewById([Link]);
// adding on click listener for our button.
[Link](new [Link]() {
@Override
public void onClick(View v) {
// on below line we are getting data from our edit text.
String userName = [Link]().toString();
String password = [Link]().toString();
// checking if the entered text is empty or not.
if ([Link](userName) && [Link](password)) {
[Link]([Link], "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
[Link](userName);
[Link](password);
// calling a method to register the user.
[Link](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.
[Link]([Link], "User Registered successfully",
Toast.LENGTH_SHORT).show();
Intent i = new Intent([Link], [Link]);
[Link]("username", userName);
startActivity(i);
} else {
// if we get any error then we are logging out
// our user and displaying an error message
[Link]();
[Link]([Link], "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="[Link]
xmlns:tools="[Link]
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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
[Link]([Link]);
// get the system time in milli second
// when the screen background is set
final long time = [Link]();
// function when stop button is clicked
[Link](new [Link]() {
@Override
public void onClick(View view) {
// get the system time in milli second
// when the stop button is clicked
long time1 = [Link]();
// display reflex time in toast message
[Link](getApplicationContext(), "Your reflexes takes " + (time1 - time) + " time to
work", Toast.LENGTH_LONG).show();
// remove the background again
[Link](0);
}
});
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
relativeLayout = findViewById([Link].rlVar1);
button1 = findViewById([Link].btVar1);
button2 = findViewById([Link].btVar2);
// function when the start button is clicked
[Link](new [Link]() {
@Override
public void onClick(View view) {
// generate a random number from 1-10
Random random = new Random();
int num = [Link](10);
// call the runnable function after
// a post delay of num seconds
Handler handler = new Handler();
[Link](runnable, num * 1000);
}
});
}
}
Q.5 Create a music player using spinner?
XML =>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
xmlns:tools="[Link]
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/[Link]"
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/[Link]"
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/[Link]"
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/[Link]"
android:layout_width="125dp"
android:layout_height="match_parent"
android:background="@android:drawable/ic_delete"
android:onClick="musicstop" />
</LinearLayout>
</LinearLayout>
JAVA
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity
extends AppCompatActivity {
// Instantiating the MediaPlayer class
MediaPlayer music;
@Override
protected void onCreate(
Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].activity_main);
// Adding the music file to our
// newly created object music
music = [Link](
this, [Link]);
}
// Plaing the music
public void musicplay(View v)
{
[Link]();
}
// Pausing the music
public void musicpause(View v)
{
[Link]();
}
// Stoping the music
public void musicstop(View v)
{
[Link]();
music
= [Link](
this, [Link]);
}
}
Q. 6 Create a chat application ?
XML =>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
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 = [Link]();
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_chat);
// User login
if ([Link]() != 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() {
[Link](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?) {
[Link](savedInstanceState)
setContentView([Link].activity_chat)
// User login
if ([Link]() != 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() {
[Link] { 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([Link]);
ibSend = (ImageButton) findViewById([Link]);
// When send button is clicked, create message object on Parse
[Link](new [Link]() {
@Override
public void onClick(View v) {
String data = [Link]().toString();
ParseObject message = [Link]("Message");
[Link](USER_ID_KEY, [Link]().getObjectId());
[Link](BODY_KEY, data);
[Link](new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
[Link]([Link], "Successfully
created message on Parse",
Toast.LENGTH_SHORT).show();
} else {
Log.e(TAG, "Failed to save message", e);
}
}
});
[Link](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>([Link]) as EditText
ibSend = findViewById<View>([Link]) as ImageButton
// When send button is clicked, create message object on Parse
[Link](object : OnClickListener() {
fun onClick(v: View?) {
val data: String = [Link]().toString()
val message = [Link]("Message")
[Link](USER_ID_KEY, [Link]().objectId)
[Link](BODY_KEY, data)
[Link](object : SaveCallback {
override fun done(e: ParseException?) {
if (e == null) {
[Link](
this@ChatActivity, "Successfully created message on
Parse",
Toast.LENGTH_SHORT
).show()
} else {
Log.e(TAG, "Failed to save message", e)
}
}
})
[Link](null)
}
})
}
Q. 7 Create an application using navigation drawer?
XML =>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="[Link]
xmlns:tools="[Link]
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-->
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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-->
<[Link]
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_menu" />
</[Link]>
JAVA
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// drawer layout instance to toggle the menu icon to open
// drawer and back button to close drawer
drawerLayout = findViewById([Link].my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
[Link].nav_open, [Link].nav_close);
// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
[Link](actionBarDrawerToggle);
[Link]();
// 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 ([Link](item)) {
return true;
}
return [Link](item);
}
}
Q.8 Create an application of notification ?
XML =>
<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
b1 = (Button)findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
addNotification();
}
});
}
private void addNotification() {
[Link] builder =
new [Link](this)
.setSmallIcon([Link])
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, [Link]);
PendingIntent contentIntent = [Link](this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
[Link](contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
[Link](0, [Link]());
}
}
Q. 9 Create an application of game ?
XML =>
1 - activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<[Link]
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" />
</[Link]>
2 – [Link]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
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 - [Link]
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="[Link]
<solid android:color="@color/white" />
<corners android:radius="19dp"/>
</shape>
JAVA
4 - [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 {
// Creating RecyclerView
private RecyclerView recyclerView;
// Creating a ArrayList of type Modelclass
private List<Modelclass> barsColor;
// Alert dialog
[Link] alertDialog;
private Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].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= [Link](2);
// Giving the color for the
// bar based on the random number
if(n==0)
{
[Link](new Modelclass("Yellow"));
}
else
{
[Link](new Modelclass("Red"));
}
}
// Finding the RecyclerView by it's ID
recyclerView = findViewById([Link]);
// Creating an Adapter Object
adapter=new Adapter(this,barsColor);
[Link](adapter);
[Link](new LinearLayoutManager(this));
// Add ItemTouchHelper to the recyclerView
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
[Link](recyclerView);
[Link]();
[Link] simpleCallback= new
[Link](0,[Link]|[Link]) {
@Override
public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull
[Link] viewHolder, @NonNull @NotNull [Link] target) {
return false;
}
@Override
public void onSwiped(@NonNull @NotNull [Link] viewHolder, int direction)
{
// get the position of the swiped bar
int position = [Link]();
switch (direction) {
// Right side is for Yellow
case [Link]: {
if (([Link](position).getColor()).equals("Red")) {
[Link](position);
[Link]();
} else {
endthegame();
[Link]();
[Link]();
}
break;
}
// Left side is for Red
case [Link]: {
if (([Link](position).getColor()).equals("Yellow")) {
[Link](position);
[Link]();
} else {
endthegame();
[Link]();
[Link]();
}
break;
}
}
}
};
// Shows game ended dialog
private void endthegame()
{
alertDialog=new [Link](this);
[Link]("Oopa! Wrong side! Try Again! ").setPositiveButton("Try Again", new
[Link]() {
@Override
public void onClick(DialogInterface dialog, int which) {
[Link]([Link], "Try again", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Later", new [Link]() {
@Override
public void onClick(DialogInterface dialog, int which) {
[Link]([Link], "Later!", Toast.LENGTH_SHORT).show();
}
});
[Link]();
}
}
5 - [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 Adapter extends [Link]<[Link]> {
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 = [Link]([Link]()).inflate([Link],parent,false);
return new ViewHolder(view);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onBindViewHolder(@NonNull @NotNull [Link] holder, int position) {
// Getting the color for every position
String color = [Link](position).getColor();
// Set the color to the bar
if ([Link]("Yellow"))
{
[Link]([Link]().getColorStateList([Link]
ow));
}
else
{
[Link]([Link]().getColorStateList([Link]
d));
}
}
@Override
public int getItemCount() {
return [Link]();
}
public class ViewHolder extends [Link] {
LinearLayout linearLayout;
public ViewHolder(@NonNull @[Link] View itemView) {
super(itemView);
linearLayout=[Link]([Link]);
}
}
}
Q.10 create an application of android tutorial using sqlite ?
XML =>
1 - [Link]
<uses-permission
android:name="[Link].READ_EXTERNAL_STORAGE" />
2 – activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
xmlns:tools="[Link]
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- [Link]
import [Link];
import [Link];
import [Link];
import [Link];
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
[Link](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 = [Link]();
// 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.
[Link](NAME_COL, courseName);
[Link](DURATION_COL, courseDuration);
[Link](DESCRIPTION_COL, courseDescription);
[Link](TRACKS_COL, courseTracks);
// after adding all values we are passing
// content values to our table.
[Link](TABLE_NAME, null, values);
// at last we are closing our
// database after adding database.
[Link]();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// this method is called to check if the table exists already.
[Link]("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
4 - [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// initializing all our variables.
courseNameEdt = findViewById([Link]);
courseTracksEdt = findViewById([Link]);
courseDurationEdt = findViewById([Link]);
courseDescriptionEdt = findViewById([Link]);
addCourseBtn = findViewById([Link]);
// creating a new dbhandler class
// and passing our context to it.
dbHandler = new DBHandler([Link]);
// below line is to add on click listener for our add course button.
[Link](new [Link]() {
@Override
public void onClick(View v) {
// below line is to get data from all edit text fields.
String courseName = [Link]().toString();
String courseTracks = [Link]().toString();
String courseDuration = [Link]().toString();
String courseDescription = [Link]().toString();
// validating if the text fields are empty or not.
if ([Link]() && [Link]() && [Link]() &&
[Link]()) {
[Link]([Link], "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.
[Link](courseName, courseDuration, courseDescription, courseTracks);
// after adding the data we are displaying a toast message.
[Link]([Link], "Course has been added.", Toast.LENGTH_SHORT).show();
[Link]("");
[Link]("");
[Link]("");
[Link]("");
}
});
}
}