Получите данные OpenWeathermapApi с помощью анализа JSON - PullRequest
0 голосов
/ 14 октября 2019

Мое приложение было запущено. но текст не загружен.

Я хочу получить данные из API OpenWeatherMap, используя JSON. я не знаю, где проблема.

вот мой почтальон введите описание изображения здесь

вот мой Activity.java (Мой API-ключ работает как вы можетесм. изображение выше.)

   public class WeatherActivity extends AppCompatActivity {
    TextView t1_temp,t2_city,t3_weather,t4_date;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_weather);


    t1_temp = (TextView)findViewById(R.id.w_temp);
    t2_city = (TextView)findViewById(R.id.w_cityname);
    t3_weather = (TextView)findViewById(R.id.w_weather);
    t4_date = (TextView)findViewById(R.id.w_date);

    find_weather();
}

public void find_weather(){

    String url = "api.openweathermap.org/data/2.5/weather?appid=MyopenweatherAPIKEY&units=metric&q=Seoul";

    JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONObject main_object = response.getJSONObject("main");
                JSONArray array = response.getJSONArray("weather");
                JSONObject object = array.getJSONObject(0);
                String temp = String.valueOf(main_object.getDouble("temp"));
                String weahtercondition = object.getString("description");
                String city = response.getString("name");

                t1_temp.setText(temp);

                t2_city.setText(city);
                t3_weather.setText(weahtercondition);

                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("KKKK-MM-dd");
                String formatted_date = sdf.format(calendar.getTime());

                t4_date.setText(formatted_date);

            }catch (JSONException e){
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }
    );

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(jor);
}
}

, и это моя погода. xml

<RelativeLayout
    android:id="@+id/weatherview"
    android:layout_width="match_parent"
    android:layout_height="250sp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/w_temp"
        android:layout_width="125dp"
        android:layout_height="95dp"
        android:text="30"
        android:textSize="50dp" />

    <TextView
        android:id="@+id/w_weather"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="85dp"
        android:layout_marginEnd="90dp"
        android:layout_toEndOf="@+id/w_temp"
        android:text="cond"
        android:textSize="30dp" />

    <TextView
        android:id="@+id/w_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/w_temp"
        android:layout_marginBottom="-67dp"
        android:text="2019"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/w_cityname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/w_weather"
        android:layout_marginStart="186dp"
        android:layout_marginTop="84dp"
        android:layout_toEndOf="@+id/w_date"
        android:text="city"
        android:textSize="35dp" />

Пожалуйста, дайте мне знать, где я допустил ошибку. Я понятия не имею. потому что это не дает сообщение об ошибке.

1 Ответ

0 голосов
/ 15 октября 2019

Сначала проверьте срок действия вашего токена. Добавьте http:// в начале строки url, например:

    String url = "http://api.openweathermap.org/data/2.5/weather?appid=MyopenweatherAPIKEY&units=metric&q=Seoul";

, а затем добавьте android:usesCleartextTraffic="true" в манифест следующим образом:

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...