0

I'm trying to create a simple app that picks time from an API, worldtimeapi, and then display it once I click a button. However, when I click, the onFailure() method is fired up. I don't understand why onSuccess() seems to have a problem. Here is my code. I've tried to pick time via ip address since the fields in the JSON returned are more self explanatory as compared to when picking time using regions.

MainActivity.java


import androidx.appcompat.app.AppCompatActivity;

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

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

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

import cz.msebera.android.httpclient.Header;

public class MainActivity extends AppCompatActivity {
    final String BASE_URL = "http://worldtimeapi.org/api/timezone/ip";
    TextView holder;
    Button timeCollectButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        holder = findViewById(R.id.holder_text_view);
        timeCollectButton = findViewById(R.id.collect_button);

        timeCollectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Time", "Button has been clicked.");

                letsDoSomeNetworking(BASE_URL);
            }
        });



    }

    private void letsDoSomeNetworking(String url) {
        AsyncHttpClient client = new AsyncHttpClient();

        client.get(url, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d("Time", "Successful" + response.toString());



                try { // Try to...
                    Log.d("Time", "try block" + response.toString());
                    String timeHolder = response.getString("utc_datetime");
                    holder.setText(timeHolder);


                } catch (JSONException e) { // Catch a JSON exception if there is a problem parsing it
                    e.printStackTrace();
                }



            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject response) {
                // The "onFailure()" method is called when response HTTP status is "4XX" (eg. 401, 403, 404)
                Log.d("Time", "Nothing Selected");
            }
        });
    }
}

Logcat

01-10 08:19:52.031 21703-21703/com.example.time D/Time: Button has been clicked.
01-10 08:19:52.596 21703-21703/com.example.time D/Time: Nothing Selected
01-10 08:19:55.168 21703-21703/com.example.time D/Time: Button has been clicked.
01-10 08:19:55.520 21703-21703/com.example.time D/Time: Nothing Selected

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

    <TextView
        android:id="@+id/holder_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/holder_text_view"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/collect_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/collect_button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/holder_text_view" />

</androidx.constraintlayout.widget.ConstraintLayout>
Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
nzioker
  • 35
  • 5

3 Answers3

1

Your url is wrong or what. It doesn't work. enter image description here

littlebear333
  • 710
  • 2
  • 6
  • 14
0

please check your manifest file need to add internet permission

ThavaSelvan
  • 123
  • 6
0

I've tried to pick time via ip address

As in World Time API docs to get time via IP address , need to pass device IP in GET request. but you are passing BASE_URL without ip address to request.

Do it as:

1. Get device IP address:

How to get IP address of the device from code?

2. Append IP Address in BASE_URL when calling letsDoSomeNetworking:

letsDoSomeNetworking(BASE_URL+"/"+<DEVICE_IP_ADDRESS>+".txt");
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • This is in the event where I want to get the ip address of any device. I got the logic. Tried it but it didn't work out. I didnt see why we should put double quotes on this part, "/DEVICE_IP_ADDRESS". However, with or without the quotes, the code didnt pull the ip. – nzioker Jan 11 '20 at 06:13
  • This is how I picked the ip from the thread you gave. WifiManager wifiMan = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInf = wifiMan.getConnectionInfo(); int ipAddress = wifiInf.getIpAddress(); String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff)); String finalUrl = BASE_URL + ip + ".txt"; – nzioker Jan 11 '20 at 06:14