Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Homework #3 #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ dependencies {
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
3 changes: 3 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ru.android_2019.citycam" >

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
Expand Down
260 changes: 258 additions & 2 deletions app/src/main/java/ru/android_2019/citycam/CityCamActivity.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
package ru.android_2019.citycam;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import ru.android_2019.citycam.model.City;
import ru.android_2019.citycam.webcams.Webcams;

/**
* Экран, показывающий веб-камеру одного выбранного города.
Expand All @@ -24,6 +39,15 @@ public class CityCamActivity extends AppCompatActivity {

private ImageView camImageView;
private ProgressBar progressView;
private TextView cityTextView;
private TextView regionTextView;
private TextView latTextView;
private TextView longTextView;

private static Webcam currentWebcam;
private static Bitmap photo;

private GetDataTask getDataTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -38,14 +62,246 @@ protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_city_cam);
camImageView = (ImageView) findViewById(R.id.cam_image);
progressView = (ProgressBar) findViewById(R.id.progress);
cityTextView = (TextView) findViewById(R.id.city_cam__name);
regionTextView = (TextView) findViewById(R.id.city_cam__region);
latTextView = (TextView) findViewById(R.id.city_cam__lat);
longTextView = (TextView) findViewById(R.id.city_cam__lon);

getSupportActionBar().setTitle(city.name);

progressView.setVisibility(View.VISIBLE);

// Здесь должен быть код, инициирующий асинхронную загрузку изображения с веб-камеры
// в выбранном городе.
if (savedInstanceState != null) {
getDataTask = (GetDataTask) getLastCustomNonConfigurationInstance();
}

if (getDataTask == null) {
getDataTask = new GetDataTask(this);
getDataTask.execute();
} else {
getDataTask.attachActivity(this);
}
}

@Override
public Object onRetainCustomNonConfigurationInstance() {
getDataTask.detachActivity();
return getDataTask;
}

private static final String TAG = "CityCam";

private static class GetDataTask extends AsyncTask<Void, Void, Integer> {

private CityCamActivity activity;

GetDataTask(CityCamActivity activity) {
this.activity = activity;
updateView();
}


void attachActivity(CityCamActivity activity) {
this.activity = activity;
updateView();
}

void detachActivity() {
this.activity = null;
}

@Override
protected Integer doInBackground(Void... voids) {
try {
URL nearbyUrl = Webcams.createNearbyUrl(
(int) activity.city.latitude,
(int) activity.city.longitude);
HttpsURLConnection connection = (HttpsURLConnection) nearbyUrl.openConnection();
connection.setRequestProperty("X-RapidAPI-Key", Webcams.RAPID_API_KEY);

try {
JsonReader reader = new JsonReader(new InputStreamReader((InputStream) connection.getContent()));
List<Webcam> webcams = readWebcams(reader);
if (!webcams.isEmpty()) {
currentWebcam = webcams.get(0);
try {
InputStream in = new URL(currentWebcam.imageUrl).openStream();
photo = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
updateView();
}
} catch (Exception e) {
e.printStackTrace();
}


} catch (IOException e) {
e.printStackTrace();
return 1;
}
return 0;
}

private List<Webcam> readWebcams(JsonReader reader) throws IOException {
List<Webcam> webcams = new ArrayList<>();

reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("result")) {
reader.beginObject();
while (reader.hasNext()) {
name = reader.nextName();
if (name.equals("webcams")) {
reader.beginArray();
while (reader.hasNext()) {
Log.i(TAG, "NAME IN ARRAy: " + reader.peek().name());
webcams.add(readWebcam(reader));
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
} else {
reader.skipValue();
}
}
reader.endObject();

return webcams;
}

private Webcam readWebcam(JsonReader reader) throws IOException {
Webcam webcam = new Webcam();

try {
reader.beginObject();
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, reader.toString());
}
while (reader.hasNext()) {
String name = reader.nextName();

switch (name) {
case "id":
webcam.id = reader.nextLong();
break;
case "image":
webcam.imageUrl = readImageUrl(reader);
break;
case "location":
reader.beginObject();
while (reader.hasNext()) {
name = reader.nextName();
switch (name) {
case "city":
webcam.city = reader.nextString();
break;
case "region":
webcam.region = reader.nextString();
break;
case "latitude":
webcam.latitude = reader.nextDouble();
break;
case "longitude":
webcam.longitude = reader.nextDouble();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();

Log.i(TAG, webcam.toString());
return webcam;
}

private String readImageUrl(JsonReader reader) throws IOException {
String result = null;

reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("current")) {
reader.beginObject();
while (reader.hasNext()) {
name = reader.nextName();
if (name.equals("preview")) {
result = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
} else {
reader.skipValue();
}
}
reader.endObject();
return result;
}

private void updateView() {
activity.runOnUiThread(
new Runnable() {
@Override
public void run() {
if (currentWebcam != null) {
activity.cityTextView.setText(currentWebcam.city);
activity.regionTextView.setText(currentWebcam.region);
activity.latTextView.setText(String.format("%.2f", currentWebcam.latitude));
activity.longTextView.setText(String.format("%.2f", currentWebcam.longitude));

if (photo != null) {
activity.camImageView.setImageBitmap(photo);
activity.progressView.setVisibility(View.GONE);
}
}
}
}
);

}

}

private static class Webcam {

long id;

String city;

String region;

String imageUrl;

double latitude;

double longitude;

@Override
public String toString() {
return "Webcam{" + "id=" + id +
", city='" + city + '\'' +
", region='" + region + '\'' +
", imageUrl='" + imageUrl + '\'' +
", latitude=" + latitude +
", longitude=" + longitude +
'}';
}
}
}
28 changes: 10 additions & 18 deletions app/src/main/java/ru/android_2019/citycam/webcams/Webcams.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,26 @@
*/
public final class Webcams {

// Зарегистрируйтесь на http://ru.webcams.travel/developers/
// и вставьте сюда ваш devid
private static final String DEV_ID = "Ваш devid";
public static final String RAPID_API_KEY = "1b6b2bf409msh301a3b7eec5d75fp14ec10jsne9d8f9ba2511";

private static final String BASE_URL = "http://api.webcams.travel/rest";
private static final String BASE_URL = "https://webcamstravel.p.rapidapi.com/webcams";

private static final String PARAM_DEVID = "devid";
private static final String PARAM_METHOD = "method";
private static final String PARAM_LAT = "lat";
private static final String PARAM_LON = "lng";
private static final String PARAM_FORMAT = "format";
private static final String PATH_NEARBY = "list/nearby";

private static final String METHOD_NEARBY = "wct.webcams.list_nearby";
private static final String PARAM_LANGUAGE = "lang";
private static final String PARAM_SHOW = "show";

private static final String FORMAT_JSON = "json";
private static final int RADIUS = 100;

/**
* Возвращает URL для выполнения запроса Webcams API для получения
* информации о веб-камерах рядом с указанными координатами в формате JSON.
*/
public static URL createNearbyUrl(double latitude, double longitude)
public static URL createNearbyUrl(int latitude, int longitude)
throws MalformedURLException {
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(PARAM_METHOD, METHOD_NEARBY)
.appendQueryParameter(PARAM_LAT, Double.toString(latitude))
.appendQueryParameter(PARAM_LON, Double.toString(longitude))
.appendQueryParameter(PARAM_DEVID, DEV_ID)
.appendQueryParameter(PARAM_FORMAT, FORMAT_JSON)
Uri uri = Uri.parse(BASE_URL + "/" + PATH_NEARBY + "=" + latitude + "," + longitude + "," + RADIUS).buildUpon()
.appendQueryParameter(PARAM_LANGUAGE, "ru")
.appendQueryParameter(PARAM_SHOW, "webcams:image,location")
.build();
return new URL(uri.toString());
}
Expand Down
Loading