0% found this document useful (0 votes)
35 views46 pages

Android Pract 9-10

Mobile computing lab pracs

Uploaded by

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

Android Pract 9-10

Mobile computing lab pracs

Uploaded by

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

PRACTICAL 9

AIM: - Android program to work with images and videos

THEORY: -
Audio Player:
Android has a built-in microphone through which you can capture audio and store it , or
play it on your phone. There are many ways to do that but the most common way is through
the MediaRecorder class.
Android provides a MediaRecorder class to record audio or video. In order to use the
MediaRecorder class you will first create an instance of the MediaRecorder class. Its syntax is
given below.
MediaRecorder myAudioRecorder = new MediaRecorder();

To set the source , output and encoding format and output file. The syntax is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);

After specifying the audio source and format and its output file, we can then call the two basic
methods: prepare and start to start recording the audio.

myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the MediaRecorder class that
allow you to have more control over audio and video recording.

Important Methods of MediaRecorder Class


Method Description
setAudioSource() This method will specify the source of the audio to be recorded.
setAudioEncoder() This method is used to specify the audio encoder.
setOutputFormat() This method is used to specify the output format of our audio.
setOutputFile() This method is used to specify the path of recorded audio files that are to
be stored.
stop() This method is used to stop the recording process.
start() This method is used to start the recording process.
release() This method is used to release the resource that is associated with the
Media recorder class.

Video Player:
By the help of MediaController and VideoView classes, we can play the video files in android. It
can load images from various sources taking care of computing its measurement from the video
so that it can be used for any layout manager, providing display options such as scaling and
tinting.

MediaController class
The android.widget.MediaController is a view that contains media controls like play/pause,
previous, next, fast-forward, rewind etc.

VideoView class
The android.widget.VideoView class provides methods to play and control the video player. The
commonly used methods of VideoView class are as follows:
Methods
public void setMediaController(MediaController controller)
sets the media controller to the video view.
public void setVideoURI (Uri uri)
sets the URI of the video file.
public void start()
starts the video view.
public void stopPlayback()
stops the playback.
public void pause()
pauses the playback.
public void suspend()
suspends the playback.
public void resume()
resumes the playback.
public void seekTo(int millis)
seeks to specified time in miliseconds

GPS
Get the last known location
Once you have created the Location Services client you can get the last known location of a
user's device. When your app is connected to these you can use the fused location provider's
getLastLocation() method to retrieve the device location.
The precision of the location returned by this call is determined by the permission setting you put
in your app manifest, as described in the guide on how to request location permissions.
To request the last known location, call the getLastLocation() method.
getLastLocation() gets a location estimate more quickly and minimizes battery usage that
can be attributed to your app. However, the location information might be out of date, if no
other clients have actively used location recently.
getCurrentLocation() gets a fresher, more accurate location more consistently. However,
this method can cause active location computation to occur on the device

Note: -
1) Permission need to be set in Androidmanifest.xml
2) You need to make a raw folder and insert the music and video file in it
3) Location functionality check properly by installing in your device
4) Right click on res->Android Resource Directory→Choose raw→Create it→You can copy the
video and images from any folder in your PC and paste it here
5) Name of the video file should be in small letters
6) Name of the file should only be given not the entire path.

CODE: -
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.prac9">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Prac9"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

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=".MainActivity"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/head"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:text="AUDIO PLAYER"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/rec"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:text="START RECORD"
android:onClick="rec"
tools:textAlignment="center" />
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:text="STOP RECORD"
android:onClick="stop"
tools:textAlignment="center" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/play"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:text=" PLAY AUDIO "
android:onClick="play"
tools:textAlignment="center" />
<Button
android:id="@+id/pause"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:text=" STOP PLAY "
android:onClick="pause"
tools:textAlignment="center" />
</LinearLayout>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="VIDEO PLAYER"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textView">
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="208dp" />
</FrameLayout>
<Button
android:id="@+id/btnGetLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="Show Location"
android:textSize="20sp" />
<TextView
android:id="@+id/showLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="#FF03DAC5"
android:hint="Location"
android:textColor="@color/black"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>

MainActivity.java
package com.example.prac9;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.IOException;
import java.util.Random;

public class MainActivity extends AppCompatActivity {


private static int MICROPHONE_PERMISSION_CODE= 200;
MediaRecorder mediaRecorder;
MediaPlayer mediaPlayer;
private static final int REQUEST_LOCATION = 1;
Button btnGetLocation;
TextView showLocation;
LocationManager locationManager;
String latitude, longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (micCheck()){
getmicpremission();
}
VideoView videoView = findViewById(R.id.videoView);

videoView.setVideoPath("android.resource://"+getPackageName()+"/"+R.raw.parmanu);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
ActivityCompat.requestPermissions( this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
showLocation = findViewById(R.id.showLocation);
btnGetLocation = findViewById(R.id.btnGetLocation);
btnGetLocation.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onClick(View v) {
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
if
(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
OnGPS();
} else {
getLocation();
}
}
}); videoView.setMediaController(mediaController);
}
public void rec(View v){
try{
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(getRecordingFilePath());

mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.prepare();
mediaRecorder.start();
Toast.makeText(this,"Recording Started",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
e.printStackTrace();
}}
public void stop(View v){
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
Toast.makeText(this,"Recording Stopped",
Toast.LENGTH_SHORT).show();
}
public void play(View v){
try{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(getRecordingFilePath());
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(this,"Recorded Audiio Playing",Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}
}
public void pause(View v){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
Toast.makeText(this,"Audio Stopped", Toast.LENGTH_SHORT).show();
}
private boolean micCheck(){

if(this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_MICROPHONE)){
return true;
}
else{
return false;
}
}
private void getmicpremission(){
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.RECORD_AUDIO)
==PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(MainActivity.this,new
String[]{

Manifest.permission.RECORD_AUDIO},MICROPHONE_PERMISSION_CODE);
}
}
private String getRecordingFilePath() {
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File musicDirectory
=contextWrapper.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
File file = new File(musicDirectory, "testRecordingFile"+".mp3");
return file.getPath();
}
private void OnGPS() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
startActivity(new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("No", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(
MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)
!=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(
MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
Location locationGPS =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locationGPS != null) {
double lat = locationGPS.getLatitude();
double longi = locationGPS.getLongitude();
latitude = String.valueOf(lat);
longitude = String.valueOf(longi);
showLocation.setText("Your Location: " + "\n" + "Latitude: " + latitude + "\n" +
"Longitude: " + longitude);
} else {
Toast.makeText(this, "Unable to find location.",
Toast.LENGTH_SHORT).show();
}
}
}
}

OUTPUT: -
CONCLUSION: -
From this practical I have learned to implement Android program to work with images and
videos.
PRACTICAL 10

AIM: - Android program based on Rest API


A) Create a basic application that allows you to download HTML from a given web page using
HttpURLConnection.
B) Create an application to parse the data using JSONObject methods and set it in the Text
View’s. (Employee name and salary stored in JSON format).
C) Write a basic application to (use volley library), create a button and on click of the button a
HTTP request will be sent to the server. The response from the server is then displayed using
Toast on the screen.
D) Write a program to create signup page design with 3 Edit Texts (Name, email and password)
and one sign up Button. On click of button, data in EditText is validated. Implement signup api
to save the data in the database. After getting a response from the api, display the message on the
screen by using a Toast. (useRetrofit)

THEORY: -
HttpURLConnection:
A URLConnection with support for HTTP-specific features. See the spec for details.
Uses of this class follow a pattern:
1. Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to
HttpURLConnection.
2. Prepare the request. The primary property of a request is its URI. Request headers may also
include metadata such as credentials, preferred content types, and session cookies.
3. Optionally upload a request body. Instances must be configured with setDoOutput(true) if they
include a request body. Transmit data by writing to the stream returned by
URLConnection.getOutputStream().
4. Read the response. Response headers typically include metadata such as the response body's
content type and length, modified dates and session cookies. The response body may be read
from the stream returned by URLConnection.getInputStream(). If the response has no body, that
method returns an empty stream.
5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed
by calling disconnect(). Disconnecting releases the resources held by a connection so they may
be closed or reused.
For example, to retrieve the webpage at http://www.android.com/:

JsonObject:
JsonObject class represents an immutable JSON object value (an unordered collection of zero or
more name/value pairs). It also provides unmodifiable map view to the JSON object name/value
mappings. A JsonObject instance can be created from an input source using
JsonReader.readObject().
For example:
JsonReader jsonReader = Json.createReader(...);
JsonObject object = jsonReader.readObject();
jsonReader.close();

It can also be built from scratch using a JsonObjectBuilder. For example 1: An empty JSON
object can be built as follows:
JsonObject object = Json.createObjectBuilder().build();
JsonObject values can be JsonObject, JsonArray, JsonString, JsonNumber, JsonValue.TRUE,
JsonValue.FALSE, JsonV alue.NULL. These values can be accessed using various accessor
methods.
In the above example 2, "John" can be got using
String firstName = object.getString("firstName");
This map object provides read-only access to the JSON object data, and attempts to modify the
map, whether direct or via its collection views, result in an UnsupportedOperationException.
The map object's iteration ordering is based on the order in which name/value pairs are added to
the corresponding builder or the order in which name/value pairs appear in the corresponding
stream.

Volley:
Volley is an HTTP library that makes networking for Android apps easier and most importantly,
faster. Volley is available on GitHub.
Volley offers the following benefits:
1. Automatic scheduling of network requests.
2. Multiple concurrent network connections.
3. Transparent disk and memory response caching with standard HTTP cache coherence.
4. Support for request prioritization.
5. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of
requests to cancel.
6. Ease of customization, for example, for retry and backoff.
7. Strong ordering that makes it easy to correctly populate your UI with data fetched
asynchronously from the network.
8. Debugging and tracing tools.
Volley excels at RPC-type operations used to populate a UI, such as fetching a page of search
results as structured data. It integrates easily with any protocol and comes out of the box with
support for raw strings, images, and JSON. By providing built-in support for the features you
need, Volley frees you from writing boilerplate code and allows you to concentrate on the logic
that is specific to your app.
Classes in Volley Library:
1. Request Queue: It is the interest one uses for dispatching requests to the network. One can
make a request queue on demand if required, but typically it is created early on, at startup time,
and keep it around and use it as a Singleton.
2. Request: All the necessary information for making web API call is stored in it. It is the base
for creating network requests(GET, POST).
Retrofit:
Retrofit is a type-safe HTTP client for Android and Java – developed by Square (Dagger,
Okhttp). Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square.
The library provides a powerful framework for authenticating and interacting with APIs and
sending network requests with OkHttp. See this guide to understand how OkHttp works. This
library makes downloading JSON or XML data from a web API fairly straightforward. Once the
data is downloaded then it is parsed into a Plain Old Java Object (POJO) which must be defined
for each "resource" in the response.

Retrofit models REST endpoints as Java interfaces, making them very simple to understand and
consume. Retrofit works by modeling over a base URL and by making interfaces return the
entities from the REST endpoint. For simplicity purposes we're going to take a small part of the
JSON by modeling our User class that is going to take the values when we have received them.

NOTE: -
DataActivity.java
1) https://designer.mocky.io/design
For the volley program i.e. DataActivity.java you have to visit the above site
Enter the data as shown in below image
Then click on Generate my HTTP response

For the data you can visit below link and copy and modify as per your need
https://run.mocky.io/v3/e563fe74-f4ab-47b9-ba6c-6fc147cd6579

In the code which is shown in the below part between quotes you need to paste your URL
private String url =””
2) add dependency in build.gradle(; app)
implementation 'com.android.volley:volley:1.2.1'

3) In AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

FormActivity.java
1) add dependency in build.gradle(; app)
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
2) In AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

3) Inside htdocs create a folder and keep PHP file in it

4) Controller.java: - Below path should be noted(May change as you make)


private static final String url="http://10.0.2.2:8080/PHP/Signup.php/";

5) Apiset.java: -Below part path of php file(May change as you make)


@POST("/PHP/Signup.php")

Xampp
1) Goto Xampp start the Apache and MySQL
2) In the Browser enter the localhost:portnumber, you will be directed to below image click on
circled part

3) Below window appears


4) Click on New

5) Enter database name and click Create

6) Enter Name and enter number of the columns and click Go


7) Enter details as shown below

8) Click on create below image window is shown


For writing code of php
→Open Notepad and write the code
→Save it with .php extension inside a folder created by you in the htdocs folder
→ Now goto Browser
Enter below link
http://localhost:your_port_number/your_filename.php

The above ip should be used in your code in Controller.java file

CODE: -
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/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HTML"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.228" />

<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/json"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.387" />

<Button
android:id="@+id/btn3"
android:layout_width="119dp"
android:layout_height="55dp"
android:text="@string/data_fetch"
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.576" />

<Button
android:id="@+id/btn4"
android:layout_width="100dp"
android:layout_height="60dp"
android:text="@string/form"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.517"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.742" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_html.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=".HtmlActivity">

<EditText
android:id="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Enter website link"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.058" />

<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="VIEW HTML"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.219" />
<TextView
android:id="@+id/txt1"
android:layout_width="375dp"
android:layout_height="436dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.526"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.79" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_json.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:orientation="vertical"
android:layout_margin="20sp"
tools:context=".JsonActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="20sp" />

<TextView
android:id="@+id/salary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Salary"
android:textSize="20sp" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

activity_data.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=".DataActivity">

<Button
android:id="@+id/buttonRequest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetch Response" />

</LinearLayout>

activity_form.html
<?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:orientation="vertical"
android:layout_margin="20sp"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">

<EditText
android:id="@+id/t1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:inputType="textPersonName"
android:minHeight="48dp" />

<EditText
android:id="@+id/t2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Username"
android:inputType="textEmailAddress"
android:minHeight="48dp" />

<EditText
android:id="@+id/t3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:inputType="textPassword"
android:minHeight="48dp" />
<Button
android:id="@+id/SignUpBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign up"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Signup.php
<?php
$conn = mysqli_connect("localhost","root","","android");
$name=trim($_POST['name']);
$email=trim($_POST['email']);
$pass=trim($_POST['password']);
if($conn)
{
$qry = "select * from form where email='$email'";
$result = mysqli_query($conn,$qry);
if(mysqli_num_rows($result)>0)
{
$response['message']="exist";
echo json_encode($response);
}
else
{
$qry = "insert into form(name,email,password)values('$name','$email','$pass')";
if(mysqli_query($conn,$qry))
{
$response['message']="success";
}
else{
$response['message']="failed";
}
echo json_encode($response);
}
}
else{

$response['message']="failed";
echo json_encode($response);

}
?>

MainActivity.java
package com.example.prac10;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


Button html,json,data, form;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
html = findViewById(R.id.btn1);
json=findViewById(R.id.btn2);
data=findViewById(R.id.btn3);
form=findViewById(R.id.btn4);
html.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, HtmlActivity.class);
startActivity(intent);
}
});
json.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,JsonActivity.class);
startActivity(intent);
}
});
data.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DataActivity.class);
startActivity(intent);
}
});
form.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FormActivity.class);
startActivity(intent);
}
});
}

HtmlActivity.java
package com.example.prac10;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HtmlActivity extends AppCompatActivity {
private static final String TAG_HTTP_URL_CONNECTION =
"HTTP_URL_CONNECTION";
private static final int REQUEST_CODE_SHOW_RESPONSE_TEXT = 1;
private static final String KEY_RESPONSE_TEXT = "KEY_RESPONSE_TEXT";
private static final String REQUEST_METHOD_GET = "GET";
private EditText requestUrlEditor = null;
private Button requestUrlButton = null;
private TextView responseTextView = null;
private Handler uiUpdater = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_html);
setTitle("Html Downloader");
initControls();
requestUrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String reqUrl = requestUrlEditor.getText().toString();
if(!TextUtils.isEmpty(reqUrl)) {
if(URLUtil.isHttpUrl(reqUrl) ||
URLUtil.isHttpsUrl(reqUrl)) {
startSendHttpRequestThread(reqUrl);
}else {
Toast.makeText(getApplicationContext(), "The request url is not a valid http or
https url.", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(getApplicationContext(), "The request url can not be empty.",
Toast.LENGTH_LONG).show();
}
}
});
}
private void initControls()
{
if(requestUrlEditor == null) {
requestUrlEditor =
(EditText)findViewById(R.id.et1);
}
if(requestUrlButton == null) {
requestUrlButton =
(Button)findViewById(R.id.btn5);
}
if(responseTextView == null) {
responseTextView =
(TextView)findViewById(R.id.txt1);
}
{
uiUpdater = new Handler()
{
@Override
public void handleMessage(Message msg) {
if(msg.what == REQUEST_CODE_SHOW_RESPONSE_TEXT)
{
Bundle bundle = msg.getData();
if(bundle != null)
{
String responseText =
bundle.getString(KEY_RESPONSE_TEXT);
responseTextView.setText(responseText);
}
}
}
};
}
}
private void startSendHttpRequestThread(final String reqUrl)
{
Thread sendHttpRequestThread = new Thread()
{
@Override
public void run() {
HttpURLConnection httpConn = null;
InputStreamReader isReader = null;
BufferedReader bufReader = null;
StringBuffer readTextBuf = new StringBuffer();
try {
URL url = new URL(reqUrl);
httpConn = (HttpURLConnection)url.openConnection();
httpConn.setRequestMethod(REQUEST_METHOD_GET);
httpConn.setConnectTimeout(10000);
httpConn.setReadTimeout(10000);
InputStream inputStream = httpConn.getInputStream();
isReader = new InputStreamReader(inputStream);
bufReader = new BufferedReader(isReader);
String line = bufReader.readLine();
while(line != null) {
readTextBuf.append(line);
line = bufReader.readLine();
}
Message message = new Message();
message.what = REQUEST_CODE_SHOW_RESPONSE_TEXT;
Bundle bundle = new Bundle();
bundle.putString(KEY_RESPONSE_TEXT,
readTextBuf.toString());
message.setData(bundle);
uiUpdater.sendMessage(message);
}catch(MalformedURLException ex) {
Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(), ex);
}catch(IOException ex) {
Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(), ex);
}finally {
try {
if (bufReader != null) {
bufReader.close();
bufReader = null;
}
if (isReader != null) {
isReader.close();
isReader = null;
}
if (httpConn != null) {
httpConn.disconnect();
httpConn = null;
}
}catch (IOException ex) {
Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(),
ex);
}
}
}
};
sendHttpRequestThread.start();
}
}

JsonActivity.java
package com.example.prac10;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonActivity extends AppCompatActivity {


String JSON_STRING = "{\"employee\":{\"name\":\"Christy Philip\",\"salary\":40000}}";
String name, salary;
TextView employeeName, employeeSalary;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
employeeName = (TextView) findViewById(R.id.name);
employeeSalary = (TextView) findViewById(R.id.salary);
try {
JSONObject obj = new JSONObject(JSON_STRING);
JSONObject employee = obj.getJSONObject("employee");

name = employee.getString("name");
salary = employee.getString("salary");
employeeName.setText("Name: "+name);
employeeSalary.setText("Salary: "+salary);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

DataActivity.java
package com.example.prac10;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
public class DataActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
private Button btnRequest;
private RequestQueue mRequestQueue;
private StringRequest mStringRequest;
private String url = "https://run.mocky.io/v3/e563fe74-f4ab-47b9-ba6c-6fc147cd6579";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
btnRequest = (Button) findViewById(R.id.buttonRequest);
btnRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
sendAndRequestResponse();
}
});
}
private void sendAndRequestResponse() {
mRequestQueue = Volley.newRequestQueue(this);
mStringRequest = new StringRequest(Request.Method.GET, url, new
Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(),"Response :" +
response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,"Error :" + error.toString());
}
});
mRequestQueue.add(mStringRequest);
}
}
FormActivity.java
package com.example.prac10;

import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
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 retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FormActivity extends AppCompatActivity {
EditText t1,t2,t3;
Button SignUpBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
t1=(EditText)findViewById(R.id.t1);
t2=(EditText)findViewById(R.id.t2);
t3=(EditText)findViewById(R.id.t3);
SignUpBtn=(Button)findViewById(R.id.SignUpBtn);
SignUpBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
processSignUp();
}
});
}
void processSignUp(){
String name = t1.getText().toString();
String email = t2.getText().toString();
String password = t3.getText().toString();
Call<ResponseModel> call =
Controller.getInstance().getapi().verifyuser(name,email,password);
call.enqueue(new Callback<ResponseModel>() {
@Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel>
response) {
ResponseModel obj=response.body();
String output=obj.getMessage();
if(output.equals("exist")) {
t1.setText("");
t2.setText("");
t3.setText("");
Toast.makeText(getApplicationContext(),"User Already Exist",
Toast.LENGTH_LONG).show();
}
if(output.equals("success")) {
Toast.makeText(getApplicationContext(),"User Registered Successfully",
Toast.LENGTH_LONG).show();
}
if(output.equals("failed")) {
Toast.makeText(getApplicationContext(),"Something went wrong",
Toast.LENGTH_LONG).show();
}
if(output.equals("failed")) {
Toast.makeText(getApplicationContext(),"Connection failure",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Toast.makeText(getApplicationContext(),""+t+call, Toast.LENGTH_LONG).show();
}
});}}

ResponseModel.java
package com.example.prac10;

public class ResponseModel {


String message;
public ResponseModel(String message) {
this.message = message;
}
public ResponseModel() {}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

Controller.java
package com.example.prac10;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Controller {
private static final String url="http://10.0.2.2:8080/PHP/Signup.php/";
private static Controller clientobject;
private static Retrofit retrofit;
Controller() {
retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized Controller getInstance() {
if(clientobject==null)
clientobject=new Controller();
return clientobject;
}
Apiset getapi() {
return retrofit.create(Apiset.class);
}
}

Apiset.java
package com.example.prac10;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface Apiset {
@FormUrlEncoded
@POST("/PHP/Signup.php")
Call<ResponseModel> verifyuser(
@Field("name") String name,
@Field("email") String email,
@Field("password") String password
);
}

OUTPUT: -
Html
Json
Volley
Retrofit
Result on localhost:8080

CONCLUSION: -
From this practical I have learned to implement Android program based on Rest API

You might also like