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

Egor Shakhmin. Homework with cache #11

Open
wants to merge 4 commits 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
21 changes: 14 additions & 7 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
compileSdkVersion 28
buildToolsVersion '28.0.3'

defaultConfig {
applicationId "ru.android_2019.citycam"
minSdkVersion 14
targetSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
Expand All @@ -17,11 +17,18 @@ android {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

repositories {
jcenter()
google()
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
}
2 changes: 2 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ru.android_2019.citycam" >

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

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

import android.arch.persistence.room.Room;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import ru.android_2019.citycam.model.City;
import ru.android_2019.citycam.webcams.store.WebcamDao;
import ru.android_2019.citycam.webcams.store.WebcamDatabase;
import ru.android_2019.citycam.webcams.tasks.WebcamsTask;

/**
* Экран, показывающий веб-камеру одного выбранного города.
Expand All @@ -21,9 +26,39 @@ public class CityCamActivity extends AppCompatActivity {
public static final String EXTRA_CITY = "city";

private City city;

private ImageView camImageView;
private ProgressBar progressView;
private TextView titleImageView;
private WebcamsTask task;
private WebcamDao webcamDao;

public City getCity() {
return city;
}

public ImageView getCamImageView() {
return camImageView;
}

public ProgressBar getProgressView() {
return progressView;
}

public TextView getTitleImageView() {
return titleImageView;
}

public WebcamDao getWebcamDao() {
return webcamDao;
}

@Override
public Object onRetainCustomNonConfigurationInstance() {
if (task != null) {
task.attachActivity(null);
}
return task;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -36,15 +71,24 @@ protected void onCreate(Bundle savedInstanceState) {
}

setContentView(R.layout.activity_city_cam);
camImageView = (ImageView) findViewById(R.id.cam_image);
progressView = (ProgressBar) findViewById(R.id.progress);
camImageView = findViewById(R.id.cam_image);
progressView = findViewById(R.id.progress);
titleImageView = findViewById(R.id.cam_image_title);

getSupportActionBar().setTitle(city.name);
WebcamDatabase db = Room.databaseBuilder(getApplicationContext(),
WebcamDatabase.class, "webcam-database").build();
this.webcamDao = db.webcamDao();

progressView.setVisibility(View.VISIBLE);
getSupportActionBar().setTitle(city.name);

// Здесь должен быть код, инициирующий асинхронную загрузку изображения с веб-камеры
// в выбранном городе.
task = (WebcamsTask) getLastCustomNonConfigurationInstance();
if (task == null) {
progressView.setVisibility(View.VISIBLE);
task = new WebcamsTask();
task.execute();
}
task.attachActivity(this);
task.updateView();
}

private static final String TAG = "CityCam";
Expand Down
46 changes: 0 additions & 46 deletions app/src/main/java/ru/android_2019/citycam/webcams/Webcams.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package ru.android_2019.citycam.webcams.api;

import android.net.Uri;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
* Константы для работы с WebcamsAPI API
*/
public final class WebcamsAPI {

private static final String KEY_HEADER_NAME = "X-RapidAPI-Key";
private static final String RAPID_API_KEY = "9874e23cf2msh03710ad1d33c9bbp15fca7jsnee66756f171d";
private static final String BASE_URL = "https://webcamstravel.p.rapidapi.com";
private static final String PARAM_LAN = "lan";
private static final String PARAM_SHOW = "show";
private static final String LAN = "en";
private static final String SHOW = "webcams:base,image,location";

/**
* Возвращает HttpURLConnection для выполнения запроса WebcamsAPI API для получения
* информации о веб-камерах рядом с указанными координатами в формате JSON.
*/
public static HttpURLConnection createNearbyUrl(double latitude,
double longitude,
double radius) throws IOException {

Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendPath("webcams")
.appendPath("list")
.appendEncodedPath("nearby=" + latitude + "," + longitude + "," + radius)
.appendQueryParameter(PARAM_LAN, LAN)
.appendQueryParameter(PARAM_SHOW, SHOW)
.build();
HttpURLConnection connection = (HttpURLConnection) new URL(uri.toString()).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty(KEY_HEADER_NAME, RAPID_API_KEY);
return connection;
}

private WebcamsAPI() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ru.android_2019.citycam.webcams.exceptions;

public class BadResponseException extends Exception {

public BadResponseException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package ru.android_2019.citycam.webcams.parser;

import android.util.JsonReader;

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

import ru.android_2019.citycam.webcams.store.Webcam;
import ru.android_2019.citycam.webcams.store.Webcam.TypeImage;
import ru.android_2019.citycam.webcams.exceptions.BadResponseException;

public final class WebcamsResponseParser {

public static List<Webcam> parseWebcamsResponse(
String cityName,
InputStream in,
String charset) throws IOException, BadResponseException {

JsonReader reader = new JsonReader(new InputStreamReader(in, charset));
List<Webcam> webcams = new ArrayList<>();

reader.beginObject();
while (reader.hasNext()){
String name = reader.nextName();
if (name.equals("result")) {
webcams = readResult(cityName, reader);
} else if (name.equals("status")){
String status = reader.nextString();
if (!status.equals("OK")) {
throw new BadResponseException("Bad response with status: " + status);
}
} else {
reader.skipValue();
}
}
reader.endObject();

return webcams;
}

private static List<Webcam> readResult(
String cityName,
JsonReader reader) throws IOException {

List<Webcam> webcams = new ArrayList<>();

reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("webcams")) {
webcams = readWebcamsArray(cityName, reader);
} else {
reader.skipValue();
}
}
reader.endObject();

return webcams;
}

private static List<Webcam> readWebcamsArray(
String cityName,
JsonReader reader) throws IOException {

List<Webcam> webcams = new ArrayList<>();

reader.beginArray();
while (reader.hasNext()) {
webcams.add(readWebcam(cityName, reader));
}
reader.endArray();

return webcams;
}

private static Webcam readWebcam(
String cityName,
JsonReader reader) throws IOException {

String title = null;
String imageUrl = null;

reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("title")) {
title = reader.nextString();
} else if (name.equals("image")) {
imageUrl = readImages(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
Webcam webcam = new Webcam(cityName);
webcam.setTitle(title);
webcam.setImageUrl(imageUrl);
return webcam;
}

private static String readImages(JsonReader reader)
throws IOException {

String imageUrl = null;

reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("current")) {
imageUrl = readImageUrl(reader);
} else {
reader.skipValue();
}
}
reader.endObject();

return imageUrl;
}

private static String readImageUrl(JsonReader reader)
throws IOException {

String imageUrl = null;

reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals(TypeImage.PREVIEW.getName())) {
imageUrl = reader.nextString();
} else {
reader.skipValue();
}

}
reader.endObject();

return imageUrl;
}
}
Loading