Skip to content

Commit

Permalink
Merge pull request #4
Browse files Browse the repository at this point in the history
Добавил работу с фрагментами в т.ч. горизонтальном режиме.
  • Loading branch information
MayMih authored Feb 27, 2023
2 parents d1c3b05 + 2c2b696 commit b044924
Show file tree
Hide file tree
Showing 16 changed files with 1,147 additions and 485 deletions.
4 changes: 3 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,16 @@
android:name=".CardActivity"
android:parentActivityName=".MainActivity"
android:exported="false"
android:configChanges="orientation|screenSize"
>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Expand Down
187 changes: 42 additions & 145 deletions app/src/main/java/org/mmu/tinkoffkinolab/CardActivity.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
package org.mmu.tinkoffkinolab;

import static org.mmu.tinkoffkinolab.Constants.ADAPTER_FILM_ID;
import static org.mmu.tinkoffkinolab.Constants.ADAPTER_TITLE;
import static org.mmu.tinkoffkinolab.Constants.LOG_TAG;

import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.snackbar.Snackbar;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;

import java.util.AbstractMap;
Expand All @@ -28,110 +41,9 @@
public class CardActivity extends AppCompatActivity
{

//region 'Поля и константы'
private static final Map<String, String> _cardData = new HashMap<>();
private ImageView imgPoster;
private String filmId;

private WebDataDownloadTask downloadTask;
private TextView txtHeader;
private TextView txtContent;
private View androidContentView;

//endregion 'Поля и константы'



//region 'Типы'

private class WebDataDownloadTask extends AsyncTask<String, Void, Void>
{
private final FilmsApi filmsApi;
private Map.Entry<Exception, String> error;

public Map.Entry<Exception, String> getError()
{
return error;
}

public WebDataDownloadTask(FilmsApi engine)
{
filmsApi = engine;
}

@Override
protected void onPreExecute()
{
super.onPreExecute();
var progBar = findViewById(R.id.progress_bar);
progBar.setVisibility(View.VISIBLE);
Log.d(Constants.LOG_TAG, "Начало загрузки веб-ресурса...");
}

@Override
protected Void doInBackground(String... request)
{
try
{
final var response = filmsApi.apiV22FilmsIdGet(Integer.parseInt(filmId));
_cardData.put(Constants.ADAPTER_TITLE, response.getNameRu());
final var geners = "\n\n Жанры: " + response.getGenres().stream()
.map(g -> g.getGenre() + ", ")
.collect(Collectors.joining())
.replaceFirst(",\\s*$", "");
final var countries = "\n\n Страны: " + response.getCountries().stream()
.map(country -> country.getCountry() + ", ")
.collect(Collectors.joining()).replaceFirst(",\\s*$", "");
final var res = response.getDescription() + geners + countries;
_cardData.put(Constants.ADAPTER_CONTENT, res);
_cardData.put(Constants.ADAPTER_POSTER_PREVIEW_URL, response.getPosterUrl());
}
catch (RuntimeException ex)
{
var mes = Objects.requireNonNullElse(ex.getMessage(), "");
error = new AbstractMap.SimpleEntry<>(ex, mes);
if (ex instanceof ApiException)
{
final var apiEx = (ApiException)ex;
final var headers = apiEx.getResponseHeaders();
final var headersText = headers == null ? "" : headers.entrySet().stream()
.map(entry -> entry.getKey() + ": " + String.join(" \n", entry.getValue()))
.collect(Collectors.joining());
mes += String.format(Locale.ROOT, " %s (ErrorCode: %d), ResponseHeaders: \n%s\n ResponseBody: \n%s\n",
Constants.KINO_API_ERROR_MES, apiEx.getCode(), headersText, apiEx.getResponseBody());
}
Log.e(Constants.LOG_TAG, mes.isEmpty() ? Constants.UNKNOWN_WEB_ERROR_MES : mes, ex);
}
return null;
}

/**
* @apiNote Этот метод выполняется в потоке интерфейса
*
* @param unused The result of the operation computed by {@link #doInBackground}.
*/
@Override
protected void onPostExecute(Void unused)
{
super.onPostExecute(unused);
var progBar = findViewById(R.id.progress_bar);
progBar.setVisibility(View.GONE);
if (downloadTask.getError() != null)
{
final var mes = downloadTask.getError().getValue();
showSnackBar(Constants.UNKNOWN_WEB_ERROR_MES);
}
else
{
Log.d(Constants.LOG_TAG, "Загрузка Веб-ресурса завершена успешно");
fillCardUI();
}
}
}

//endregion 'Типы'





//region 'Обработчики'
Expand All @@ -148,13 +60,34 @@ protected void onCreate(Bundle savedInstanceState)
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

imgPoster = findViewById(R.id.poster_image_view);
txtHeader = findViewById(R.id.card_title);
txtContent = findViewById(R.id.card_content);
androidContentView = findViewById(android.R.id.content);

filmId = getIntent().getStringExtra(Constants.ADAPTER_FILM_ID);
getFilmDataAsync();

getSupportFragmentManager().registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks()
{
private CardFragment cardFragment;
@Override
public void onFragmentViewCreated(@NonNull FragmentManager fm, @NonNull Fragment f,
@NonNull View v, @Nullable Bundle savedInstanceState)
{
super.onFragmentViewCreated(fm, f, v, savedInstanceState);
cardFragment = ((CardFragment)f);
cardFragment.setDataLoadListener(() -> onDataLoaded_Handler());
cardFragment.getFilmDataAsync(filmId, customToolBar.getTitle().toString());
}

@Override
public void onFragmentDestroyed(@NonNull FragmentManager fm, @NonNull Fragment f)
{
super.onFragmentDestroyed(fm, f);
cardFragment.removeDataLoadListener();
}
}, false);

}

public void onDataLoaded_Handler()
{
Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
}

/**
Expand All @@ -181,42 +114,6 @@ public boolean onOptionsItemSelected(@NonNull MenuItem item)



//region 'Методы'

/**
* Метод заполнения UI карточки фильма из скачанных данных
*/
private void fillCardUI()
{
// параметры fit() и centerCrop() сильно замедляют загрузку.
Picasso.get().load(_cardData.get(Constants.ADAPTER_POSTER_PREVIEW_URL)).fit().centerCrop().into(imgPoster);
txtHeader.setText(_cardData.get(Constants.ADAPTER_TITLE));
Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
txtContent.setText(_cardData.get(Constants.ADAPTER_CONTENT));
}

/**
* Метод отображения всплывющей подсказки
*/
private void showSnackBar(String message)
{
var popup = Snackbar.make(androidContentView, message, Snackbar.LENGTH_INDEFINITE);
popup.setAction(R.string.repeat_button_caption, view -> {
getFilmDataAsync();
popup.dismiss();
});
popup.show();
}

private void getFilmDataAsync()
{
if (downloadTask != null && !downloadTask.isCancelled() && (downloadTask.getStatus() == AsyncTask.Status.RUNNING))
{
downloadTask.cancel(true);
}
downloadTask = (WebDataDownloadTask)new WebDataDownloadTask(FilmsApiHelper.getFilmsApi()).execute();
}

//endregion 'Методы'


}
Loading

0 comments on commit b044924

Please sign in to comment.