how to stay connected to the server - android

I'm trying to stay connected with a url but I don't know how.
I'm working on a quiz app so I need to refresh the question every time that user lose or win.
but it takes long time to connect to the url every time.
so I just want to connected once and then just get new questions from that url.
I'm using volley library to connect to a url.
And This is my code.
public static void getQuestionsData(Activity activity,
OnDoneLintenter onDoneListener) {
String url = "https://opentdb.com/api.php?amount=15&type=multiple";
RequestQueue queue = VolleySingleton.getInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest =
new JsonObjectRequest(ColumnStructure.GET, url, null,
jsonObject -> {
try {
JSONArray array
= jsonObject.getJSONArray(ColumnStructure.COL_RESULTS);
for (int i = 0; i < array.length(); i++) {
setColumnStructureFields(array, i);
}
onDoneListener.onDone();
} catch (JSONException e) {
Log.e("Log", "there is not result : " + e.getMessage());
}
},
volleyError -> {
Log.e("Log", "volley error : " + volleyError.getMessage());
});
queue.add(jsonObjectRequest);
}
I use this code at the beginning and every time user lose or win.So is there any way to stay connected with the url or at least get the json faster.

Related

java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 error

Can anyone help me? I debugg app many more time but I can not found what exact issue going in my android app. In my android app, My cases are describe below.
cases 1: Insert data into database It is perfectly worked fine.
case 2: That data display in to recycler view ok. It will display fine.
It will work with only single user login. When another user will login in to app and try to add data then It will get this exception. Or when I will refresh first user login view at that time it have same exception.
Or when I remove second user from database then I refresh first login user view at that time it will work perfectly . Now what to do? Please any one help me out of this issue. I attached screen shot of my error log please refer it.
Retrive data.java
private void makeJsonArrayRequest(final String email) {
String cancel_req_tag = "list";
JsonArrayRequest req = new JsonArrayRequest(URL_FOR_SELECT,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("OnResponse", response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
ListMobileModal objMobileModal = new ListMobileModal();
if (jsonObject.getString("email").equals(email)) {
objMobileModal.email = jsonObject.getString("email");
if (!jsonObject.isNull("name")) {
objMobileModal.lname = jsonObject.getString("name"); //here we can fetch webservice field
}
if (!jsonObject.isNull("title")) {
objMobileModal.title = jsonObject.getString("title"); //here we can fetch webservice field
}
if (!jsonObject.isNull("eimage")) {
objMobileModal.eimage = jsonObject.getString("eimage");
}
if (!jsonObject.isNull("eid")) {
objMobileModal.eid = jsonObject.getString("eid");
}
if (!jsonObject.isNull("ename")) {
objMobileModal.ename = jsonObject.getString("ename");
}
if (!jsonObject.isNull("edescription")) {
objMobileModal.edescription = jsonObject.getString("edescription");
}
if (!jsonObject.isNull("evlocation")) {
objMobileModal.elocation = jsonObject.getString("elocation");
}
lstListMobile.add(i, objMobileModal);
}
}
objMobileAdapter = new ListMobileAdapter(SavedPhoneBottomActivity.this, lstListMobile);
objEmptyRecyclerViewAdapter = new EmptyRecyclerViewAdapter("No selected list!");
if (lstListMobile == null || lstListMobile.size() == 0) {
rvDisplay.setAdapter(objEmptyRecyclerViewAdapter);
rvDisplay.setVisibility(View.VISIBLE);
} else {
rvDisplay.setAdapter(objMobileAdapter);
rvDisplay.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SavedPhoneBottomActivity.this,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("VolleyError", "Error: " + error.getMessage());
Toast.makeText(SavedPhoneBottomActivity.this,
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(req, cancel_req_tag);
}
List exception error
try to replace lstListMobile.add(i, objMobileModal); with lstListMobile.add(objMobileModal);
when if (jsonObject.getString("email").equals(email)) condition fails 0 index is not added for that user.
you will get ArrayIndexOutOfBound error on lstListMobile.add(1, objMobileModal); if 0 index is not present
You're inserting lstListMobile.add(i, objMobileModal); maybe you can just add lstListMobile.add(objMobileModal);? Probably whats happening is that when i==0 is does not pass the test if (jsonObject.getString("email").equals(email)) {. So it does not add and the size remains 0. When i==1 it breaks when inserting.
Please check first array is not null
if (response.length > 0) {
// do something
}
else{
//empty array
}

Retreiving data from MySQL database using Android Volley library is too slow

I tried to retrieve a list of form data stored in database in my Android application. Each row of database contains some personal information of a person in string format and also an image of that person. I have stored the images in database in MEDIUMBLOB format.
Whenever I try to retrieve data from my server using JSONObjectrequest of Volley Library in my Android app, the response is usually very slow. Sometimes it takes more than 1 minute to view only 10 to 12 rows retrieved from the database.
This is my logcat:
D/Volley: [337] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://helpclick.ahsanaasim.me/v1/tasksall/johny 0xa3e020c1 NORMAL 1> [lifetime=14740],
I tried to search for a perfect solution but I couldn't find anything satisfactory. Here is my Java code:
mRequestStartTime = System.currentTimeMillis();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
showUrl2, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
System.out.println(totalRequestTime);
System.out.println(response.toString());
try { c1++;
System.out.println(c1);
JSONArray incidents = response.getJSONArray("incidents");
for (int i = 0; i < incidents.length(); i++) {
e=0;
JSONObject incident = incidents.getJSONObject(i);
c1++;
id= incident.getString("id");
age = incident.getString("age");
gender = incident.getString("gender");
location = incident.getString("location");
//det= incident.getString("det");
String image=new String();
image = incident.getString("bigimage");
if(image.length()!=0) {
myBitmap = ConvertToImage(image);
Bitmap bitmap= Bitmap.createScaledBitmap(myBitmap,500,500,true);
imgs.add(bitmap);
ages.add(age);
genders.add(gender);
locations.add(location);
ids.add(id);
}
}
if(c1>0) {
System.out.println(ages.size());
Intent intent1 = new Intent(search_buttons_page.this, All_Incidents.class);
startActivity(intent1);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
20000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
It would be really helpful if someone can tell me the reason of this slow performance and how to solve it by making minimum modifications in my source code.
Don't keep the images in the db. Keep them in files, and keep the URL of the files in the db. Download the images separately as needed via URL. Then you aren't killing your database access times with what should be file IO.

Android Volley request weird "1 second" delay between multiple fast clicks

Sorry for my bad english, but i have problem and can't figure it out..
I have custom listview in my fragment for getting products from JSON array. And I have 3 ImageButtons in every listview row;
Plus Button(+), Minus Button(-) and Remove Button(X)..
So when i click each button, its calling JSON request for update product's piece number, getting new datas from response and repopulate array list.
Everything ok but, when I click that buttons faster, it seems there is 1 sec delay between multiple requests even first volley request has already done before.
Here is my JSON method in TableAdapter.java
public void JSON(final int position, final int process) {
if (inProgress==false) {
dialog = new ProgressDialog(myContext);
dialog.setMessage("Updating.....");
dialog.show();
inProgress = true;
System.out.println("**** Now request is beginning............");
final int rowID = tableModelList.get(position).getID();
final int treeID = tableModelList.get(position).getAna_dal();
final float price = tableModelList.get(position).getBFiyat();
final int quantity = tableModelList.get(position).getAdet();
final int print = tableModelList.get(position).getYazdimi();
final String insertUrl = "http://"+getServer+"/t6mobilservice/order-piece.php";
Map<String, String> parameters = new HashMap<>();
parameters.put("tableID", "" + getTableId);
parameters.put("rowID", "" + rowID);
parameters.put("treeID", ""+treeID);
parameters.put("process",""+process);
parameters.put("quantity",""+quantity);
parameters.put("price",""+price);
parameters.put("print",""+print);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, insertUrl, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray getOrders = response.getJSONArray("order");
Gson gson = new Gson();
tableModelList.clear();
for (int i = 0; i < getOrders.length(); i++) {
JSONObject order = getOrders.getJSONObject(i);
TableModel tableModel = gson.fromJson(order.toString(), TableModel.class);
tableModelList.add(tableModel);
}
mAdapter.notifyDataSetChanged();
System.out.println("**** onResponse: Request is done............");
System.out.println("**** JSON: "+response.toString());
dialog.cancel();
inProgress = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError response) {
Log.d("Response: ", response.toString());
inProgress = false;
}
});
requestQueue.add(jsObjRequest);
}
}
Dialog is showing when request beginning and canceling when request is done. But as I said, when I click faster, there is a delay between multiple requests even first request has already done. I'm saying 1 sec, because 2nd request is beginning after 1 sec exactly, no matter how I clicking fast. I can't figure it out..
I tested fast clicks to showing toasts with random numbers and it's working fine. But when I testing with JSON method, there is a weird delay.
I have SwipeRefreshLayout and ScrollView in my fragment.
I'm using Volley with singleton.
EDIT 1. : Here's a video link to showing what my problem is..
EDIT 2. : Here's a LogCat output video for every click
Every fast click has returning success json output, but nothing change instantly..
Thanks for your help.

How to get reddit URL JSON data in android?

I'm attempting to get a list of URL's from a subreddit in order to load them into universal image loader for viewing pleasure. However, I cannot figure out where my query is going wrong. Plus, I'm not familiar with android studio's logcat as compared to eclipses logcat, so I'm not exactly sure where to look for my debugging responses.
Here's the query method:
public void queryReddit()
{
// Prepare your search string to be put in a URL
// It might have reserved characters or something
// String urlString = "";
// try {
// urlString = URLEncoder.encode(searchString, "UTF-8");
// } catch (UnsupportedEncodingException e) {
//
// // if this fails for some reason, let the user know why
// e.printStackTrace();
// Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
// }
// Create a client to perform networking
AsyncHttpClient client = new AsyncHttpClient();
// 11. start progress bar
setProgressBarIndeterminateVisibility(true);
// Have the client get a JSONArray of data
// and define how to respond
client.get("http://www.reddit.com/r/pics/.json",
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject jsonObject) {
// 11. stop progress bar
setProgressBarIndeterminateVisibility(false);
// Display a "Toast" message
// to announce your success
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
// // 8. For now, just log results
// Log.d("omg android", jsonObject.toString());
try
{
Log.d("go reddit yay", jsonObject.toString());
JSONObject testingData = (JSONObject) jsonObject.get("data");
JSONArray testingChildren = (JSONArray) testingData.get("children");
JSONObject testingLogData = (JSONObject) testingChildren.get(0);
JSONArray children = (JSONArray) jsonObject.get("children");
JSONObject logData = (JSONObject) children.get(0);
Log.d("go reddit yay", logData.getString("url"));
Log.d("go reddit yay", testingLogData.getString("url"));
for(int i = 0; i < 10; i++)
{
JSONObject data = (JSONObject) children.get(i);
if(data.getString("url") != null)
{
System.out.println(data.getString("url"));
}
//if the url field exists and it's a picture that univ image loader understands then add it
if(data.getString("url") != null && data.getString("url").substring(data.getString("url").length()-3).equals("png") ||
data.getString("url").substring(data.getString("url").length()-3).equals("jpg"))
{
imageUrls.add(data.getString("url"));
System.out.println(data.getString("url"));
}
//TODO I found this error: this requires android.permission.INTERACT_ACROSS_USERS_FULL
}
mPagerAdapter.notifyDataSetChanged();
} catch (JSONException e)
{
e.printStackTrace();
}
//TODO Might want to put all this data in a try catch block and do it right here.
// update the data in your custom method.
//updateData()
}
#Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error)
{
// 11. stop progress bar
setProgressBarIndeterminateVisibility(false);
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Log error message
// to help solve any problems
Log.e("omg android", statusCode + " " + throwable.getMessage());
}
});
}
Within the try catch block, the only logged information that ends up being sent to logcat is the first line, Log.d("go reddit yay", jsonObject.toString());
I can't find the responses from the other log calls which is very strange to me.
Here's the response from the first log call:
06-17 06:35:29.324 17133-17133/.wallpaper D/absfr﹕ {"data":{"after":"t3_2823ou","children":[{"data":{"media_embed":{},"author_flair_css_class":null,"score":503,"created_utc":1402931529,"clicked":false,"visited":false,"id":"28a94k","author":"JamesBDW","title":"Any Bronson fans? [1920x1080]","over_18":false,"created":1402960329,"name":"t3_28a94k","selftext_html":null,"domain":"i.imgur.com","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"https:\/\/i.imgur.com\/Hq1fcSm.jpg","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":31,"approved_by":null,"thumbnail":"http:\/\/a.thumbs.redditmedia.com\/Dh2iU7Q0rpFogkWt.jpg","permalink":"\/r\/wallpaper\/comments\/28a94k\/any_bronson_fans_1920x1080\/","hidden":false,"likes":null,"downs":188,"ups":691,"selftext":"","media":null},"kind":"t3"},{"data":{"media_embed":{},"author_flair_css_class":null,"score":8,"created_utc":1402989714,"clicked":false,"visited":false,"id":"28cnyn","author":"ZadocPaet","title":"Active Dunes on Mars (OS) [1024x768]","over_18":false,"created":1403018514,"name":"t3_28cnyn","selftext_html":null,"domain":"nasa.gov","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"http:\/\/www.nasa.gov\/sites\/default\/files\/styles\/1024x768_autoletterbox\/public\/pia18244.jpg","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":1,"approved_by":null,"thumbnail":"http:\/\/a.thumbs.redditmedia.com\/dFTBquSWiMSjK0aZ.jpg","permalink":"\/r\/wallpaper\/comments\/28cnyn\/active_dunes_on_mars_os_1024x768\/","hidden":false,"likes":null,"downs":3,"ups":11,"selftext":"","media":null},"kind":"t3"},{"data":{"media_embed":{"content":"<iframe class=\"embedly-embed\" src=\"\/\/cdn.embedly.com\/widgets\/media.html?src=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf%2Fembed&url=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf&image=http%3A%2F%2Fi.imgur.com%2F2PdUiuE.jpg&key=2aa3c4d5f3de4f5b9120b660ad850dc9&type=text%2Fhtml&schema=imgur\" width=\"550\" height=\"550\" scrolling=\"no\" frameborder=\"0\" allowfullscreen><\/iframe>","scrolling":false,"height":550,"width":550},"author_flair_css_class":null,"score":1,"created_utc":1403004127,"clicked":false,"visited":false,"id":"28czid","author":"smessies","title":"I found a wallpaper album full of iconic design chairs. I tought there were some important ones missing so i started adding some myself. work in progress! [1920x1200]","over_18":false,"created":1403032927,"name":"t3_28czid","selftext_html":null,"domain":"imgur.com","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"http:\/\/imgur.com\/a\/0jeZf","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":0,"approved_by":null,"thumbnail":"http:\/\/b.thumbs.redditmedia.com\/GYaN5fyJfY8fI8xE.jpg","permalink":"\/r\/wallpaper\/comments\/28czid\/i_found_a_wallpaper_album_full_of_iconic_design\/","hidden":false,"likes":null,"downs":0,"ups":1,"selftext":"","media":{"type":"imgur.com","oembed":{"thumbnail_height":1200,"author_url":"http:\/\/imgur.com\/user\/smessies","width":550,"type":"rich","version":"1.0","thumbnail_url":"http:\/\/i.imgur.com\/2PdUiuE.jpg","thumbnail_width":1920,"title":"imgur: the simple image sharer","height":550,"description":"Imgur is home to the web's most popular image content, curated in real time by a dedicated community through commenting, voting and sharing.","author_name":"smessies","html":"<iframe class=\"embedly-embed\" src=\"\/\/cdn.embedly.com\/widgets\/media.html?src=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf%2Fembed&url=http%3A%2F%2Fimgur.com%2F
no idea what to do.
One last debugging info is that the toast for the onSuccess method does appear, so it is clearly successful in it's query, I'm just doing something wrong in interpreting the data.
From your description it seems like a statement after the first Log.d("go reddit yay", ...); call throws an exception which you can't see.
Try replacing your exception handling code:
} catch (JSONException e)
{
e.printStackTrace();
}
with this:
} catch (Throwable t)
{
Log.e("omg android", "Exception in onSuccess()", t);
}
and check if any exceptions are logged.

How to get current time from internet in android

I am making an app in which I want to get the current time from internet.
I know how to get the time from the device using System.currentTimeMillis, and even after searching a lot, I did not get any clue about how to get it from internet.
You can get time from internet time servers using the below program
import java.io.IOException;
import org.apache.commons.net.time.TimeTCPClient;
public final class GetTime {
public static final void main(String[] args) {
try {
TimeTCPClient client = new TimeTCPClient();
try {
// Set timeout of 60 seconds
client.setDefaultTimeout(60000);
// Connecting to time server
// Other time servers can be found at : http://tf.nist.gov/tf-cgi/servers.cgi#
// Make sure that your program NEVER queries a server more frequently than once every 4 seconds
client.connect("time.nist.gov");
System.out.println(client.getDate());
} finally {
client.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
1.You would need Apache Commons Net library for this to work. Download the library and add to your project build path.
(Or you can also use the trimmed Apache Commons Net Library here : https://www-us.apache.org/dist//commons/net/binaries/commons-net-3.6-bin.tar.gz This is enough to get time from internet )
2.Run the program. You will get the time printed on your console.
Here is a method that i have created for you
you can use this in your code
public String getTime() {
try{
//Make the Http connection so we can retrieve the time
HttpClient httpclient = new DefaultHttpClient();
// I am using yahoos api to get the time
HttpResponse response = httpclient.execute(new
HttpGet("http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo"));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
// The response is an xml file and i have stored it in a string
String responseString = out.toString();
Log.d("Response", responseString);
//We have to parse the xml file using any parser, but since i have to
//take just one value i have deviced a shortcut to retrieve it
int x = responseString.indexOf("<Timestamp>");
int y = responseString.indexOf("</Timestamp>");
//I am using the x + "<Timestamp>" because x alone gives only the start value
Log.d("Response", responseString.substring(x + "<Timestamp>".length(),y) );
String timestamp = responseString.substring(x + "<Timestamp>".length(),y);
// The time returned is in UNIX format so i need to multiply it by 1000 to use it
Date d = new Date(Long.parseLong(timestamp) * 1000);
Log.d("Response", d.toString() );
return d.toString() ;
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}catch (ClientProtocolException e) {
Log.d("Response", e.getMessage());
}catch (IOException e) {
Log.d("Response", e.getMessage());
}
return null;
}
If you don't care for millisecond accuracy, and if you are already using google firebase or don't mind using it (they provide a free tier), check this out: https://firebase.google.com/docs/database/android/offline-capabilities#clock-skew
Basically, firebase database has a field that provides offset value between the device time and the firebase server time. You can use this offset to get the current time.
DatabaseReference offsetRef = FirebaseDatabase.getInstance().getReference(".info/serverTimeOffset");
offsetRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
double offset = snapshot.getValue(Double.class);
double estimatedServerTimeMs = System.currentTimeMillis() + offset;
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});
As I said, it will be inaccurate based on network latency.
I think the best solution is to use SNTP, in particular the SNTP client code from Android itself, e.g.:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/net/SntpClient.java/
I believe Android uses SNTP for automatic date/time updates when a cell network is not available (e.g. wifi tablets).
I think it is better then the other solutions because it uses SNTP/NTP rather then the Time protocol (RFC 868) used by the Apache TimeTCPClient. I don't know anything bad about RFC 868, but NTP is newer and seems to have superceeded it and is more widely used. I believe that Android devices that don't have cellular uses NTP.
Also, because it uses sockets. Some of the solutions proposed use HTTP so they will lose something in their accuracy.
You will need to have access to a webservice that provides current time in XML or JSON format.
If you don't find such type of service, you could parse the time from a web page, like http://www.timeanddate.com/worldclock/, or host your own time service on a server using a simple PHP page for example.
Check out JSoup for the parsing of HTML pages.
Nothing from the above worked from me. This is what I ended up with (with Volley);
This example also converts to another timezone.
Long time = null;
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.timeapi.org/utc/now";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = simpleDateFormat.parse(response);
TimeZone tz = TimeZone.getTimeZone("Israel");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(date);
Log.d(TAG, "onResponse: " + result.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.w(TAG, "onErrorResponse: "+ error.getMessage());
}
});
queue.add(stringRequest);
return time;
Import Volley in gradle:
compile 'com.android.volley:volley:1.0.0'
There is a clear answer available already in Stackoverflow
https://stackoverflow.com/a/71274296/11789675
Call this url or use as GET API
http://worldtimeapi.org/api/timezone/Asia/Kolkata
the response will be like
{
"abbreviation": "IST",
"client_ip": "45.125.117.46",
"datetime": "2022-02-26T10:50:43.406519+05:30",
}
This thing works best for my apps. I use jsoup to search the google time and gets current time and then I compare the phone time with google time. So if these time are different you can stop user using a dialogbox or alertbox to tell them the times have changed. You can implement in MainActivity to check this condition. Here is a snippet so you get the idea more clearly.
public class HomeActivity extends AppCompatActivity {
//phoneDate and phoneTime to get current phone date and time
String phoneDate = new SimpleDateFormat("dd MMM yyyy ").format(clnd.getTime()).trim();
String phoneTime = new SimpleDateFormat("hh:mm a").format(clnd.getTime()).trim();
String googleDate;
String googleTime ;
#Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.home);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//URL to search time
String url = "https://www.google.co.in/search?q=time";
Document document = Jsoup.connect(url).get();
org.jsoup.select.Elements time = document.getElementsByClass("gsrt vk_bk FzvWSb YwPhnf");
org.jsoup.select.Elements date = document.getElementsByClass("KfQeJ");
Log.d("HTML", "google date" + String.format(date.text()));
Log.d("HTML", "google time" + time.text());
googleDate = date.text().trim();
googleTime = time.text().trim();
//'0'is not present when hour is single digit
char second = googleTime.charAt(1);
if(second == ':'){
googleTime = "0" + googleTime;
}
Log.d("Proper format", "google time" + googleTime);
Log.d("Date", "your current url when webpage loading.." + phoneDate);
Log.d("Time", "your current url when webpage loading.." + phoneTime);
if(googleDate.contains(phoneDate) && googleTime.equals(phoneTime)){
Log.d("Time", "your current url when webpage loading.." + " true");
}else{
Log.d("Time", "your current url when webpage loading.." + " false");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}

Categories

Resources