public class ConvertCurrencyTask extends AsyncTask<Void, Void, Double> {
private final String fromCurrency;
private final String toCurrency;
private final double amount;
private final CurrencyRepository repository;
private final Callback callback;
public interface Callback {
void onConversionResult(Double result);
}
public ConvertCurrencyTask(String fromCurrency, String toCurrency, double amount, CurrencyRepository repository, Callback callback) {
this.fromCurrency = fromCurrency;
this.toCurrency = toCurrency;
this.amount = amount;
this.repository = repository;
this.callback = callback;
}
@Override
protected Double doInBackground(Void... voids) {
// Convert using USD as an intermediary
if (fromCurrency.equals("USD")) {
// Direct conversion from USD to the target currency
Double rateToTarget = repository.getExchangeRate("USD", toCurrency);
if (rateToTarget != null) {
return amount * rateToTarget;
}
} else if (toCurrency.equals("USD")) {
// Direct conversion from source currency to USD
Double rateFromSource = repository.getExchangeRate(fromCurrency, "USD");
if (rateFromSource != null) {
return amount * rateFromSource;
}
} else {
// Conversion from source currency to USD, then USD to target currency
Double rateFromSource = repository.getExchangeRate(fromCurrency, "USD");
Double rateToTarget = repository.getExchangeRate("USD", toCurrency);
if (rateFromSource != null && rateToTarget != null) {
// First convert amount to USD, then from USD to target currency
double amountInUSD = amount * rateFromSource;
return amountInUSD * rateToTarget;
}
}
Log.e("ConvertCurrencyTask", "Conversion rate not found for " + fromCurrency + " to " + toCurrency);
return null; // Return null if conversion is not possible
}
@Override
protected void onPostExecute(Double result) {
callback.onConversionResult(result);
}
@Entity(tableName = "currency_rates",
indices = {@Index(value = {"baseCurrency", "targetCurrency", "date"}, unique = true)})
@TypeConverters({Converters.class})
public class CurrencyRate {
@PrimaryKey(autoGenerate = true)
public int id;
public String baseCurrency;
public String targetCurrency;
public double rate;
public Date date;
public CurrencyRate(String baseCurrency, String targetCurrency, double rate, Date date) {
this.baseCurrency = baseCurrency;
this.targetCurrency = targetCurrency;
this.rate = rate;
this.date = date;
}
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertCurrencyRate(CurrencyRate rate);
@Query("SELECT DISTINCT baseCurrency FROM currency_rates")
List<String> getAllBaseCurrencies();
@Query("SELECT DISTINCT targetCurrency FROM currency_rates")
List<String> getAllTargetCurrencies();
@Query("SELECT rate FROM currency_rates WHERE baseCurrency = :fromCurrency AND targetCurrency = :toCurrency ORDER BY date DESC LIMIT 1")
Double getLatestExchangeRate(String fromCurrency, String toCurrency);
@Query("SELECT * FROM currency_rates WHERE UPPER(baseCurrency) = UPPER(:baseCurrency) AND UPPER(targetCurrency) = UPPER(:targetCurrency) AND date <= :currentDate ORDER BY date ASC")
List<CurrencyRate> getCurrencyRateHistory(String baseCurrency, String targetCurrency, Date currentDate);
public class CurrencyRepository {
private final CurrencyRateDao currencyRateDao;
public CurrencyRepository(Context context) {
AppDatabase db = AppDatabase.getDatabase(context);
currencyRateDao = db.currencyRateDao();
}
// Синхронный метод вставки курса
public void insertCurrencyRateSync(CurrencyRate rate) {
currencyRateDao.insertCurrencyRate(rate);
}
// Метод для получения списка уникальных валют
public List<String> getAllUniqueCurrencies() {
List<String> baseCurrencies = currencyRateDao.getAllBaseCurrencies();
List<String> targetCurrencies = currencyRateDao.getAllTargetCurrencies();
Set<String> allCurrencies = new HashSet<>(baseCurrencies);
allCurrencies.addAll(targetCurrencies);
return new ArrayList<>(allCurrencies);
}
// Получение последнего курса для конвертации
public Double getExchangeRate(String fromCurrency, String toCurrency) {
return currencyRateDao.getLatestExchangeRate(fromCurrency, toCurrency);
}
// Получение истории курсов для графика
public List<CurrencyRate> getCurrencyRateHistory(String baseCurrency, String targetCurrency, Date date) {
return currencyRateDao.getCurrencyRateHistory(baseCurrency, targetCurrency, date);
}
// Загрузка курсов из API
public void loadAllCurrencyRatesFromApi(LoadCurrencyRatesTask.Callback callback) {
new LoadCurrencyRatesTask(this, callback).execute();
}
public class LoadCurrencyRatesTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "LoadCurrencyRatesTask";
private static final String API_URL = "https://api.exchangerate-api.com/v4/latest/USD";
private final CurrencyRepository repository;
private final Callback callback;
public interface Callback {
void onRatesLoaded();
void onError(Exception e);
}
public LoadCurrencyRatesTask(CurrencyRepository repository, Callback callback) {
this.repository = repository;
this.callback = callback;
}
@Override
protected Void doInBackground(Void... voids) {
try {
// Загрузка текущих курсов
URL url = new URL(API_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Failed to connect to API. Response Code: " + responseCode);
if (callback != null) {
callback.onError(new Exception("Failed to connect to API. Response Code: " + responseCode));
}
return null;
}
// Чтение ответа
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream())
);
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
Log.d(TAG, "API response received.");
// Разбор JSON ответа
JSONObject jsonResponse = new JSONObject(response.toString());
JSONObject rates = jsonResponse.getJSONObject("rates");
Log.d(TAG, "Parsing JSON response.");
for (Iterator<String> it = rates.keys(); it.hasNext(); ) {
String currency = it.next().toUpperCase();
double rate = rates.getDouble(currency);
Date currentDate = new Date();
// Вставляем текущий курс
repository.insertCurrencyRateSync(new CurrencyRate("USD", currency, rate, currentDate));
repository.insertCurrencyRateSync(new CurrencyRate(currency, "USD", 1 / rate, currentDate));
// Генерируем и вставляем исторические курсы
generateMockHistory("USD", currency, rate);
generateMockHistory(currency, "USD", 1 / rate);
}
if (callback != null) {
callback.onRatesLoaded();
}
} catch (Exception e) {
Log.e(TAG, "Error loading currency rates", e);
if (callback != null) {
callback.onError(e);
}
}
return null;
}
private void generateMockHistory(String baseCurrency, String targetCurrency, double currentRate) {
Random random = new Random();
Calendar calendar = Calendar.getInstance();
// Get the current date once
Date currentDate = new Date();
calendar.setTime(currentDate);
// Generate history for the last 30 days
for (int i = 30; i >= 1; i--) {
// Reset calendar to current date at each iteration
calendar.setTime(currentDate);
calendar.add(Calendar.DAY_OF_MONTH, -i);
// Set time components to zero
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date date = calendar.getTime();
// Generate fluctuation
double fluctuation = (random.nextDouble() - 0.5) * 0.1; // ±5%
double historicalRate = currentRate * (1 + fluctuation);
CurrencyRate historyRate = new CurrencyRate(
baseCurrency,
targetCurrency,
historicalRate,
date
);
repository.insertCurrencyRateSync(historyRate);
Log.d("LoadCurrencyRatesTask", "Inserting CurrencyRate: baseCurrency=" + baseCurrency +
", targetCurrency=" + targetCurrency + ", date=" + date + ", rate=" + historicalRate);
}
}
} при запуске пишет нет данных для графика
The issue you're experiencing, where the application displays "Нет данных для отображения графика" ("No data to display the chart"), arises because the dates used in your queries do not match the dates stored in the database due to the time components (hours, minutes, seconds, milliseconds).
In your LoadCurrencyRatesTask, when you generate historical data, you set the time components of the dates to zero (midnight):
This means all your historical CurrencyRate entries have dates at 00:00:00.000 of each day.
However, in your LoadChartDataTask, when you query for the data, you use new Date() directly, which includes the current time down to milliseconds. So when you do a comparison in your SQL query date <= :currentDate, the stored dates (which are at midnight) may not be considered less than or equal to the current date and time.
Here's how you can fix it:
Modify the LoadChartDataTask in your MainActivity.java to adjust the currentDate used in the query to ensure it includes all entries up to the end of the current day.
Replace the doInBackground method in your LoadChartDataTask with the following code:
@Override
protected LineData doInBackground(Void... voids) {
List<CurrencyRate> historyList;
// Adjust current date to include the end of the day (23:59:59.999)
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
Date currentDate = calendar.getTime();
// Fetch the data using the adjusted currentDate
historyList = repository.getCurrencyRateHistory(fromCurrency, toCurrency, currentDate);
Log.d("LoadChartDataTask", "Количество записей истории: " + historyList.size());
if (historyList == null || historyList.isEmpty()) {
return null;
}
// The rest of your code remains the same...
// Create list of entries for the chart
List<Entry> entries = new ArrayList<>();
for (int i = 0; i < historyList.size(); i++) {
CurrencyRate history = historyList.get(i);
entries.add(new Entry(i, (float) history.rate));
}
LineDataSet dataSet = new LineDataSet(entries, "Курс " + fromCurrency + "/" + toCurrency);
dataSet.setColor(ColorTemplate.getHoloBlue());
dataSet.setCircleColor(ColorTemplate.getHoloBlue());
dataSet.setLineWidth(1.5f);
dataSet.setCircleRadius(3f);
dataSet.setDrawCircleHole(false);
dataSet.setValueTextSize(9f);
dataSet.setDrawFilled(true);
dataSet.setFillColor(ColorTemplate.getHoloBlue());
return new LineData(dataSet);
}
By setting the currentDate to the very end of the current day, you ensure that all historical data up to and including today is included in your query. This adjustment corrects the date comparison in your SQL query, allowing the data to be retrieved and displayed in the chart.
Additional Recommendations:
Logging: Add logging statements to your data insertion and querying methods to help trace any potential issues in the data flow.
Data Validation: Ensure that your data is being correctly inserted into the database and that there are no constraint violations causing data not to be stored.
Date Handling: Be consistent with date and time handling throughout your application to prevent similar issues in the future.
Explanation:
The root cause of your issue is the mismatch between the time components of the dates stored in the database and the dates used in your queries. By normalizing the currentDate used in your query to match the stored dates (either by setting it to midnight or the end of the day), you avoid the problem where entries are excluded due to time differences, and your chart will display the expected data.