简体   繁体   中英

World Time API call firing up the onFailure instead of onSuccess

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>

Your url is wrong or what. It doesn't work. 在此处输入图片说明

请检查您的清单文件需要添加互联网权限

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM