'How to get difference of response received time and request made time
i need a difference between response recieved time - request made time.it should print the difference on the screen.for now it shows a button and if we click that button it prints response time stamp.
Xml code below for the reference
<?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:id="@+id/Click"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="@string/app_name"
android:textStyle="bold"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="@string/app_name"
android:textStyle="bold"
android:visibility="gone"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="@string/app_name"
android:textStyle="bold"
android:visibility="gone"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
</androidx.constraintlayout.widget.ConstraintLayout>
mainacivity class code for reference
package com.example.volleydemo;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
Button Click;
TextView responseText, timerText, timeLast;
int clickCount = 0;
Date endTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
endTime = Calendar.getInstance().getTime();
Click = findViewById(R.id.button);
Click.setOnClickListener(this);
responseText = findViewById(R.id.textView);
timerText = findViewById(R.id.textView2);
timeLast = findViewById(R.id.textView3);
}
@SuppressLint("SetTextI18n")
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.button) {
timerText.setVisibility(View.VISIBLE);
timeLast.setVisibility(View.VISIBLE);
Date currentTime = Calendar.getInstance().getTime();
@SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm.ss aa");
String differenceTime = dateFormat.format(currentTime);
timeLast.setText("Current API call Time : " + differenceTime);
String diff = DateUtils.getRelativeTimeSpanString(currentTime.getTime(), endTime.getTime(),
DateUtils.SECOND_IN_MILLIS).toString();
String lastSeen = dateFormat.format(endTime);
timerText.setText("Last call was done at : " + lastSeen +
"\nLast API Call was done before : " + diff + " ago");
endTime = Calendar.getInstance().getTime();
}
int randomInt = ThreadLocalRandom.current().nextInt(1, 200);
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(getApplicationContext());
@SuppressLint("SetTextI18n") JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
"https://jsonplaceholder.typicode.com/todos/" + randomInt,
null, response -> {
try {
responseText.setVisibility(View.VISIBLE);
Log.d(TAG, "the response is" + response.getString("title"));
responseText.setText(" ID" + response.getString("id") + "\n Title-" +
response.getString("title") + "\n Completed-" +
response.getString("completed") + "\n User ID"
+ response.getString("userId") + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.d("myapp", "something went wrong"));
requestQueue.add(jsonObjectRequest);
}
}
Build.gradle file for the reference
plugins {
id 'com.android.application'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.volleydemo"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.android.volley:volley:1.2.1'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Solution 1:[1]
Try This-
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button Click;
TextView responseText, timerText, timeLast;
Date endTime;
long startTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
endTime = Calendar.getInstance().getTime();
Click = findViewById(R.id.button);
Click.setOnClickListener(this);
responseText = findViewById(R.id.textView);
timerText = findViewById(R.id.textView2);
timeLast = findViewById(R.id.textView3);
}
@SuppressLint("SetTextI18n")
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.button) {
timerText.setVisibility(View.INVISIBLE);
timeLast.setVisibility(View.INVISIBLE);
startTime = System.currentTimeMillis();
timeLast.setText("Request made at : " + getDate(startTime, "dd/MM/yyyy hh:mm:ss.SS"));
int randomInt = ThreadLocalRandom.current().nextInt(1, 200);
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(getApplicationContext());
@SuppressLint("SetTextI18n") JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
"https://jsonplaceholder.typicode.com/todos/" + randomInt,
null, response -> {
try {
timerText.setVisibility(View.VISIBLE);
timeLast.setVisibility(View.VISIBLE);
long elapsedTime = System.currentTimeMillis() - startTime;
timerText.setText("Request Completed within : "
+ convertSecondsToHMmSs(elapsedTime));
responseText.setVisibility(View.VISIBLE);
responseText.setText(" ID" + response.getString("id") + "\n Title-" +
response.getString("title") + "\n Completed-" +
response.getString("completed") + "\n User ID"
+ response.getString("userId") + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.d("myapp", "something went wrong"));
requestQueue.add(jsonObjectRequest);
}
}
@SuppressLint("DefaultLocale")
public static String convertSecondsToHMmSs(long seconds) {
long s = seconds % 60;
long m = (seconds / 60) % 60;
long h = (seconds / (60 * 60)) % 24;
return String.format("%d Minute:%02d Second:%02d MilliSecond", h, m, s);
}
public static String getDate(long milliSeconds, String dateFormat) {
@SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sandesh KhutalSaheb |