Merge pull request #8 from TanguyHerbron/unstable

Rework SettingsActivity and RecordTransactionActivity + several fixs
This commit is contained in:
Tanguy Herbron 2018-08-20 05:10:06 +02:00 committed by GitHub
commit b22aa6bc12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
139 changed files with 7977 additions and 1901 deletions

View File

@ -3,6 +3,59 @@
<component name="WizardSettings">
<option name="children">
<map>
<entry key="imageWizard">
<value>
<PersistentState>
<option name="children">
<map>
<entry key="imageAssetPanel">
<value>
<PersistentState>
<option name="children">
<map>
<entry key="launcher">
<value>
<PersistentState>
<option name="children">
<map>
<entry key="foregroundImage">
<value>
<PersistentState>
<option name="values">
<map>
<entry key="scalingPercent" value="72" />
<entry key="trimmed" value="true" />
</map>
</option>
</PersistentState>
</value>
</entry>
</map>
</option>
<option name="values">
<map>
<entry key="backgroundAssetType" value="COLOR" />
<entry key="backgroundColor" value="004e92" />
<entry key="backgroundLayerName" value="ic_launcher_background" />
<entry key="foregroundImage" value="D:\Projets Adobe\Photoshop\Moodl_icon_white.png" />
<entry key="foregroundLayerName" value="ic_launcher_foreground" />
<entry key="outputName" value="ic_launcher_moodl" />
<entry key="previewDensity" value="MEDIUM" />
</map>
</option>
</PersistentState>
</value>
</entry>
</map>
</option>
</PersistentState>
</value>
</entry>
</map>
</option>
</PersistentState>
</value>
</entry>
<entry key="vectorWizard">
<value>
<PersistentState>
@ -18,7 +71,7 @@
<PersistentState>
<option name="values">
<map>
<entry key="url" value="jar:file:/C:/Program%20Files/Android/Android%20Studio/plugins/android/lib/android.jar!/images/material_design_icons/image/ic_panorama_fish_eye_black_24dp.xml" />
<entry key="url" value="jar:file:/C:/Program%20Files/Android/Android%20Studio/plugins/android/lib/android.jar!/images/material_design_icons/navigation/ic_arrow_drop_up_black_24dp.xml" />
</map>
</option>
</PersistentState>
@ -28,7 +81,8 @@
</option>
<option name="values">
<map>
<entry key="outputName" value="ic_panorama_fish_eye_24dp" />
<entry key="color" value="ffffff" />
<entry key="outputName" value="ic_arrow_drop_up_white_24dp" />
<entry key="sourceFile" value="C:\Users\Guitoune" />
</map>
</option>

Binary file not shown.

18
.idea/misc.xml generated
View File

@ -1,5 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavadocGenerationManager">
<option name="OUTPUT_DIRECTORY" value="F:/Export AS" />
<option name="OPTION_SCOPE" value="protected" />
<option name="OPTION_HIERARCHY" value="true" />
<option name="OPTION_NAVIGATOR" value="true" />
<option name="OPTION_INDEX" value="true" />
<option name="OPTION_SEPARATE_INDEX" value="true" />
<option name="OPTION_DOCUMENT_TAG_USE" value="false" />
<option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" />
<option name="OPTION_DOCUMENT_TAG_VERSION" value="false" />
<option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" />
<option name="OPTION_DEPRECATED_LIST" value="true" />
<option name="OTHER_OPTIONS" />
<option name="HEAP_SIZE" />
<option name="LOCALE" />
<option name="OPEN_IN_BROWSER" value="true" />
<option name="OPTION_INCLUDE_LIBS" value="false" />
</component>
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />

View File

@ -12,6 +12,10 @@ android {
vectorDrawables.useSupportLibrary = true
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
dataBinding {
enabled = true
}
@ -21,6 +25,7 @@ android {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
lintOptions {
checkReleaseBuilds false
//disable 'MissingTranslation'
}
}
@ -34,12 +39,12 @@ android {
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.mcxiaoke.volley:library:1.0.19'
implementation 'com.diogobernardino:williamchart:2.5.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:palette-v7:27.1.1'
implementation 'com.daimajia.swipelayout:library:1.2.0@aar'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
@ -51,7 +56,7 @@ dependencies {
implementation 'org.apache.commons:commons-lang3:3.6'
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
implementation 'com.mattprecious.swirl:swirl:1.1.0'
implementation 'com.wdullaer:materialdatetimepicker:3.5.2'
implementation 'com.wdullaer:materialdatetimepicker:3.6.3'
implementation 'com.jmedeisis:draglinearlayout:1.1.0'
implementation 'com.applandeo:material-file-picker:1.0.0'
implementation 'com.daasuu:EasingInterpolator:1.0.0'
@ -60,6 +65,6 @@ dependencies {
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation files('../libs/binance-api.jar')
implementation files('../libs/commons-codec-1.11.jar');
implementation files('../libs/binance-api-forked.jar')
implementation files('../libs/commons-codec-1.11.jar')
}

View File

@ -43,7 +43,7 @@
<activity
android:name=".Activities.RecordTransactionActivity"
android:screenOrientation="portrait"
android:theme="@style/RecordTransactionTheme">
android:theme="@style/InputActivityTheme">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.herbron.moodl.Activities.HomeActivity" />
@ -56,6 +56,12 @@
android:name="android.support.PARENT_ACTIVITY"
android:value="com.herbron.moodl.Activities.HomeActivity" />
</activity>
<activity
android:name=".Activities.ExchangeListActivity"
android:label="@string/title_activity_exchange_list"
android:theme="@style/InputActivityTheme"/>
<activity android:name=".Activities.AddExchangeActivity"
android:theme="@style/InputActivityTheme"></activity>
</application>
</manifest>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -0,0 +1,180 @@
package com.herbron.moodl.Activities;
import android.content.Intent;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.R;
public class AddExchangeActivity extends AppCompatActivity {
private LinearLayout setupExchangeLayout;
private Spinner exchangeSpinner;
private DatabaseManager databaseManager;
private TextInputEditText accountLabelEditText;
private TextInputEditText accountDescriptionEditText;
private TextInputEditText publicKeyEditText;
private TextInputEditText secretKeyEditText;
private AppCompatButton saveExchangeButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getApplicationContext().setTheme(R.style.InputActivityTheme);
setContentView(R.layout.activity_add_exchange);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
databaseManager = new DatabaseManager(getBaseContext());
exchangeSpinner = findViewById(R.id.exchange_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.supported_exchanges, R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
setupExchangeLayout = findViewById(R.id.exchange_setup_layout);
exchangeSpinner.setAdapter(adapter);
Intent callingIntent = getIntent();
if(callingIntent.getBooleanExtra("isEdit", false))
{
startExchangeEditionForId(callingIntent.getIntExtra("exchangeId", -1));
}
else
{
exchangeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
loadLayoutFor(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
setupBackButton();
}
private void loadLayoutFor(int exchangeType)
{
setupExchangeLayout.removeAllViews();
exchangeSpinner.setSelection(exchangeType);
switch (exchangeType)
{
case DatabaseManager.BINANCE_TYPE:
setupExchangeLayout = (LinearLayout) LayoutInflater.from(getBaseContext()).inflate(R.layout.binance_exchange_setup_layout, setupExchangeLayout, true);
bindSetupViews();
break;
case DatabaseManager.HITBTC_TYPE:
setupExchangeLayout = (LinearLayout) LayoutInflater.from(getBaseContext()).inflate(R.layout.hitbtc_exchange_setup_layout, setupExchangeLayout, true);
bindSetupViews();
break;
}
}
private void startExchangeEditionForId(int exchangeId)
{
Exchange exchangeInfos = databaseManager.getExchangeFromId(exchangeId);
loadLayoutFor(exchangeInfos.getType());
exchangeSpinner.setEnabled(false);
accountLabelEditText.setText(exchangeInfos.getName());
accountDescriptionEditText.setText(exchangeInfos.getDescription());
publicKeyEditText.setText(exchangeInfos.getPublicKey());
secretKeyEditText.setText(exchangeInfos.getPrivateKey());
saveExchangeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isEditTextFilled(accountLabelEditText) && isEditTextFilled(publicKeyEditText) && isEditTextFilled(secretKeyEditText))
{
PreferencesManager preferencesManager = new PreferencesManager(getBaseContext());
preferencesManager.setMustUpdateSummary(true);
databaseManager.deleteExchangeAccountFromId(exchangeInfos.getId());
databaseManager.addExchange(accountLabelEditText.getText().toString(), exchangeSpinner.getSelectedItemPosition()
, accountDescriptionEditText.getText().toString(), publicKeyEditText.getText().toString()
, secretKeyEditText.getText().toString());
finish();
}
}
});
}
private void bindSetupViews()
{
accountLabelEditText = findViewById(R.id.account_label_editText);
accountDescriptionEditText = findViewById(R.id.account_description_editText);
publicKeyEditText = findViewById(R.id.publicKey_editText);
secretKeyEditText = findViewById(R.id.secretKey_editText);
saveExchangeButton = findViewById(R.id.saveExchangeButton);
saveExchangeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isEditTextFilled(accountLabelEditText) && isEditTextFilled(publicKeyEditText) && isEditTextFilled(secretKeyEditText))
{
PreferencesManager preferencesManager = new PreferencesManager(getBaseContext());
preferencesManager.setMustUpdateSummary(true);
databaseManager.addExchange(accountLabelEditText.getText().toString(), exchangeSpinner.getSelectedItemPosition()
, accountDescriptionEditText.getText().toString(), publicKeyEditText.getText().toString()
, secretKeyEditText.getText().toString());
finish();
}
}
});
}
private boolean isEditTextFilled(TextInputEditText editText)
{
if(editText.getText().toString().equals("") || editText.getText().toString().equals(" "))
{
editText.setError(getResources().getString(R.string.must_be_filled));
return false;
}
return true;
}
private void setupBackButton()
{
ImageButton backButton = findViewById(R.id.back_button);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}

View File

@ -16,23 +16,23 @@ import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.herbron.moodl.DataManagers.BalanceManager;
import com.herbron.moodl.DataNotifiers.CryptocompareNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyDetailsList;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.LayoutManagers.CurrencyListAdapter;
import com.herbron.moodl.CustomAdapters.CoinWatchlistAdapter;
import com.herbron.moodl.R;
import java.util.ArrayList;
import java.util.List;
public class CurrencySelectionActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public class CurrencySelectionActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, CryptocompareNotifierInterface {
private CurrencyListAdapter adapter;
private CoinWatchlistAdapter adapter;
private ListView listView;
private android.widget.Filter filter;
private CurrencyDetailsList currencyDetailsList;
private CryptocompareApiManager cryptocompareApiManager;
private boolean isWatchList;
@Override
@ -44,7 +44,8 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear
setContentView(R.layout.activity_add_currency);
currencyDetailsList = CurrencyDetailsList.getInstance(this);
cryptocompareApiManager = CryptocompareApiManager.getInstance(this);
cryptocompareApiManager.addListener(this);
setTitle(getString(R.string.select_coin));
@ -67,8 +68,8 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear
private void setupAdapter()
{
List<String> currencyNames = currencyDetailsList.getCurrenciesName();
List<String> currencySymbols = currencyDetailsList.getCurrenciesSymbol();
List<String> currencyNames = cryptocompareApiManager.getCurrenciesName();
List<String> currencySymbols = cryptocompareApiManager.getCurrenciesSymbol();
ArrayList<Currency> currencyArrayList = new ArrayList<>();
@ -77,7 +78,7 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear
currencyArrayList.add(new Currency(currencyNames.get(i), currencySymbols.get(i)));
}
adapter = new CurrencyListAdapter(this, currencyArrayList);
adapter = new CoinWatchlistAdapter(this, currencyArrayList);
}
private void setupList()
@ -178,6 +179,16 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear
});
}
@Override
public void onDetailsUpdated() {
detailsEvent();
}
@Override
public void onExchangesUpdated() {
}
private class ListLoader extends AsyncTask<Void, Integer, Void>
{
@Override
@ -200,14 +211,9 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear
Looper.prepare();
}
if(!currencyDetailsList.isUpToDate())
if(!cryptocompareApiManager.isDetailsUpToDate())
{
currencyDetailsList.update(new BalanceManager.IconCallBack() {
@Override
public void onSuccess() {
detailsEvent();
}
});
cryptocompareApiManager.updateDetails();
}
else
{

View File

@ -2,12 +2,10 @@ package com.herbron.moodl.Activities.DetailsActivityFragments;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
@ -15,7 +13,6 @@ import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
@ -33,10 +30,11 @@ import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.herbron.moodl.CurrencyInfoUpdateNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyDataChart;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.LayoutManagers.CustomViewPager;
import com.herbron.moodl.CustomLayouts.CustomViewPager;
import com.herbron.moodl.MoodlBox;
import com.herbron.moodl.PlaceholderManager;
import com.herbron.moodl.R;
@ -51,7 +49,7 @@ import static com.herbron.moodl.MoodlBox.numberConformer;
* Created by Tiji on 13/05/2018.
*/
public class Charts extends Fragment {
public class Charts extends Fragment implements CurrencyInfoUpdateNotifierInterface {
private final static int HOUR = 0;
private final static int DAY = 1;
@ -72,20 +70,24 @@ public class Charts extends Fragment {
private Button lineChartButton;
private Button candleStickChartButton;
private Spinner timeIntervalSpinner;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_charts_detailsactivity, container, false);
view = inflater.inflate(R.layout.detailsactivity_fragment_charts, container, false);
currency = getActivity().getIntent().getParcelableExtra("currency");
currency.setListener(this);
lineChart = view.findViewById(R.id.chartPriceView);
candleStickChart = view.findViewById(R.id.chartCandleStickView);
lineChartButton = view.findViewById(R.id.lineChartButton);
candleStickChartButton = view.findViewById(R.id.candleStickChartButton);
barChart = view.findViewById(R.id.chartVolumeView);
preferencesManager = new PreferencesManager(getContext());
preferencesManager = new PreferencesManager(getActivity().getBaseContext());
displayLineChart = true;
@ -125,17 +127,17 @@ public class Charts extends Fragment {
private void initializeSpinners()
{
Spinner spinner = view.findViewById(R.id.timeIntervalSinner);
timeIntervalSpinner = view.findViewById(R.id.timeIntervalSinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(),
R.array.time_interval_string_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
timeIntervalSpinner.setAdapter(adapter);
spinner.setSelection(2);
timeIntervalSpinner.setSelection(2);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
timeIntervalSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
updateCharts(i);
@ -158,121 +160,31 @@ public class Charts extends Fragment {
switch (index)
{
case 0:
currency.updateHistoryMinutes(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.HOUR, 1);
}
});
}
});
currency.updateHistoryMinutes(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
case 1:
currency.updateHistoryMinutes(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.HOUR, 3);
}
});
}
});
currency.updateHistoryMinutes(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
case 2:
currency.updateHistoryMinutes(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.DAY, 1);
}
});
}
});
currency.updateHistoryMinutes(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
case 3:
currency.updateHistoryHours(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.DAY, 3);
}
});
}
});
currency.updateHistoryHours(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
case 4:
currency.updateHistoryHours(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.WEEK, 11);
}
});
}
});
currency.updateHistoryHours(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
case 5:
currency.updateHistoryHours(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.MONTH, 1);
}
});
}
});
currency.updateHistoryHours(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
case 6:
currency.updateHistoryDays(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.MONTH, 3);
}
});
}
});
currency.updateHistoryDays(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
case 7:
currency.updateHistoryDays(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.MONTH, 6);
}
});
}
});
currency.updateHistoryDays(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
case 8:
currency.updateHistoryDays(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateChartTab(Charts.YEAR, 1);
}
});
}
});
currency.updateHistoryDays(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency());
break;
}
}
@ -305,13 +217,20 @@ public class Charts extends Fragment {
lineChart.getLegend().setEnabled(false);
lineChart.getXAxis().setEnabled(false);
lineChart.setViewPortOffsets(0, 0, 0, 0);
lineChart.setNoDataTextColor(currency.getChartColor());
}
private void updateChartTab(int timeUnit, int amount)
{
updateChartsData(timeUnit, amount);
drawPriceLineChart();
drawPriceCandleStickChart();
if(currency.getHistoryMinutes() != null)
{
drawPriceLineChart();
drawPriceCandleStickChart();
drawVolumeChart();
updateGeneralData(lineChart.getData().getDataSets().get(0).getEntryForIndex(0).getY(), lineChart.getData().getDataSets().get(0).getEntryForIndex(lineChart.getData().getDataSets().get(0).getEntryCount() - 1).getY());
}
if(displayLineChart)
{
@ -323,9 +242,6 @@ public class Charts extends Fragment {
view.findViewById(R.id.chartCandleStickView).setVisibility(View.VISIBLE);
view.findViewById(R.id.progressLayoutChart).setVisibility(View.GONE);
}
drawVolumeChart();
updateGeneralData(lineChart.getData().getDataSets().get(0).getEntryForIndex(0).getY(), lineChart.getData().getDataSets().get(0).getEntryForIndex(lineChart.getData().getDataSets().get(0).getEntryCount() - 1).getY());
}
private void updateGeneralData(float start, float end)
@ -336,8 +252,8 @@ public class Charts extends Fragment {
updateFluctuation(start, end);
((TextView) view.findViewById(R.id.txtViewPriceStart)).setText(PlaceholderManager.getValueString(numberConformer(start), getContext()));
((TextView) view.findViewById(R.id.txtViewPriceNow)).setText(PlaceholderManager.getValueString(numberConformer(end), getContext()));
((TextView) view.findViewById(R.id.txtViewPriceStart)).setText(PlaceholderManager.getValueString(numberConformer(start), getActivity().getBaseContext()));
((TextView) view.findViewById(R.id.txtViewPriceNow)).setText(PlaceholderManager.getValueString(numberConformer(end), getActivity().getBaseContext()));
for(int i = 1; i < dataChartList.size(); i++)
{
@ -354,9 +270,9 @@ public class Charts extends Fragment {
}
}
((TextView) view.findViewById(R.id.totalVolume)).setText(PlaceholderManager.getValueString(numberConformer(totalVolume), getContext()));
((TextView) view.findViewById(R.id.highestPrice)).setText(PlaceholderManager.getValueString(numberConformer(highestPrice), getContext()));
((TextView) view.findViewById(R.id.lowestPrice)).setText(PlaceholderManager.getValueString(numberConformer(lowestPrice), getContext()));
((TextView) view.findViewById(R.id.totalVolume)).setText(PlaceholderManager.getValueString(numberConformer(totalVolume), getActivity().getBaseContext()));
((TextView) view.findViewById(R.id.highestPrice)).setText(PlaceholderManager.getValueString(numberConformer(highestPrice), getActivity().getBaseContext()));
((TextView) view.findViewById(R.id.lowestPrice)).setText(PlaceholderManager.getValueString(numberConformer(lowestPrice), getActivity().getBaseContext()));
}
private void updateFluctuation(float start, float end)
@ -541,9 +457,9 @@ public class Charts extends Fragment {
date = getDateFromTimestamp(dataChartList.get(index).getTimestamp() * 1000);
}
volumePlaceholder = PlaceholderManager.getVolumeString(numberConformer(barChart.getData().getDataSets().get(0).getEntryForIndex(index).getY()), getContext());
pricePlaceholder = PlaceholderManager.getPriceString(numberConformer((lineChart.getHighlighted())[0].getY()), getContext());
timestampPlaceholder = PlaceholderManager.getTimestampString(date, getContext());
volumePlaceholder = PlaceholderManager.getVolumeString(numberConformer(barChart.getData().getDataSets().get(0).getEntryForIndex(index).getY()), getActivity().getBaseContext());
pricePlaceholder = PlaceholderManager.getPriceString(numberConformer((lineChart.getHighlighted())[0].getY()), getActivity().getBaseContext());
timestampPlaceholder = PlaceholderManager.getTimestampString(date, getActivity().getBaseContext());
((TextView) view.findViewById(R.id.volumeHightlight)).setText(volumePlaceholder);
view.findViewById(R.id.volumeHightlight).setVisibility(View.VISIBLE);
@ -629,14 +545,14 @@ public class Charts extends Fragment {
dataSet = new CandleDataSet(values, "");
dataSet.setDrawIcons(false);
dataSet.setDrawValues(false);
dataSet.setDecreasingColor(MoodlBox.getColor(R.color.decreaseCandle, getContext()));
dataSet.setDecreasingColor(MoodlBox.getColor(R.color.decreaseCandle, getActivity().getBaseContext()));
dataSet.setShowCandleBar(true);
dataSet.setShadowColorSameAsCandle(true);
dataSet.setDecreasingPaintStyle(Paint.Style.FILL);
dataSet.setIncreasingColor(MoodlBox.getColor(R.color.increaseCandle, getContext()));
dataSet.setIncreasingColor(MoodlBox.getColor(R.color.increaseCandle, getActivity().getBaseContext()));
dataSet.setIncreasingPaintStyle(Paint.Style.STROKE);
dataSet.setNeutralColor(MoodlBox.getColor(R.color.increaseCandle, getContext()));
dataSet.setHighLightColor(MoodlBox.getColor(R.color.colorAccent, getContext()));
dataSet.setNeutralColor(MoodlBox.getColor(R.color.increaseCandle, getActivity().getBaseContext()));
dataSet.setHighLightColor(MoodlBox.getColor(R.color.colorAccent, getActivity().getBaseContext()));
dataSet.setDrawHorizontalHighlightIndicator(false);
return new CandleData(dataSet);
@ -644,12 +560,15 @@ public class Charts extends Fragment {
private void updateChartsData(int timeUnit, int amount)
{
dataChartList = new ArrayList<>();
dataChartList = null;
switch (timeUnit)
{
case HOUR:
dataChartList = currency.getHistoryMinutes().subList(currency.getHistoryMinutes().size()-(60*amount), currency.getHistoryMinutes().size());
if(currency.getHistoryMinutes() != null)
{
dataChartList = currency.getHistoryMinutes().subList(currency.getHistoryMinutes().size()-(60*amount), currency.getHistoryMinutes().size());
}
break;
case DAY:
if(amount == 1)
@ -658,11 +577,17 @@ public class Charts extends Fragment {
}
else
{
dataChartList = currency.getHistoryHours().subList(currency.getHistoryHours().size()-(24*amount), currency.getHistoryHours().size());
if(currency.getHistoryHours() != null)
{
dataChartList = currency.getHistoryHours().subList(currency.getHistoryHours().size()-(24*amount), currency.getHistoryHours().size());
}
}
break;
case WEEK:
dataChartList = currency.getHistoryHours().subList(currency.getHistoryHours().size()-168, currency.getHistoryHours().size());
if(currency.getHistoryHours() != null)
{
dataChartList = currency.getHistoryHours().subList(currency.getHistoryHours().size()-168, currency.getHistoryHours().size());
}
break;
case MONTH:
switch (amount)
@ -671,10 +596,16 @@ public class Charts extends Fragment {
dataChartList = currency.getHistoryHours();
break;
case 3:
dataChartList = currency.getHistoryDays().subList(currency.getHistoryDays().size()-93, currency.getHistoryDays().size());
if(currency.getHistoryDays() != null)
{
dataChartList = currency.getHistoryDays().subList(currency.getHistoryDays().size()-93, currency.getHistoryDays().size());
}
break;
case 6:
dataChartList = currency.getHistoryDays().subList(currency.getHistoryDays().size()-186, currency.getHistoryDays().size());
if(currency.getHistoryDays() != null)
{
dataChartList = currency.getHistoryDays().subList(currency.getHistoryDays().size()-186, currency.getHistoryDays().size());
}
break;
}
break;
@ -684,4 +615,52 @@ public class Charts extends Fragment {
}
}
@Override
public void onTimestampPriceUpdated(String price) {
}
@Override
public void onHistoryDataUpdated() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
switch (timeIntervalSpinner.getSelectedItemPosition())
{
case 0:
updateChartTab(Charts.HOUR, 1);
break;
case 1:
updateChartTab(Charts.HOUR, 3);
break;
case 2:
updateChartTab(Charts.DAY, 1);
break;
case 3:
updateChartTab(Charts.DAY, 3);
break;
case 4:
updateChartTab(Charts.WEEK, 11);
break;
case 5:
updateChartTab(Charts.MONTH, 1);
break;
case 6:
updateChartTab(Charts.MONTH, 3);
break;
case 7:
updateChartTab(Charts.MONTH, 6);
break;
case 8:
updateChartTab(Charts.YEAR, 1);
break;
}
}
});
}
@Override
public void onPriceUpdated(Currency currency) {
}
}

View File

@ -38,13 +38,13 @@ public class Informations extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_informations_detailsactivity, container, false);
view = inflater.inflate(R.layout.detailsactivity_fragment_informations, container, false);
isSnapshotUpdated = false;
isTickerUpdated = false;
currency = getActivity().getIntent().getParcelableExtra("currency");
preferencesManager = new PreferencesManager(getContext());
preferencesManager = new PreferencesManager(getActivity().getBaseContext());
updateInfoTab();
@ -53,7 +53,7 @@ public class Informations extends Fragment {
private void updateInfoTab()
{
currency.updateSnapshot(getContext(), new Currency.CurrencyCallBack() {
currency.updateSnapshot(getActivity().getBaseContext(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(final Currency currency) {
isSnapshotUpdated = true;
@ -61,7 +61,7 @@ public class Informations extends Fragment {
}
});
currency.updateTicker(getContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
currency.updateTicker(getActivity().getBaseContext(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
isTickerUpdated = true;
@ -120,12 +120,12 @@ public class Informations extends Fragment {
((TextView) view.findViewById(R.id.txtViewDescription))
.setMovementMethod(LinkMovementMethod.getInstance());
((TextView) view.findViewById(R.id.txtViewPercentageCoinEmited))
.setText(PlaceholderManager.getEmitedPercentageString(numberConformer(currency.getMinedCoinSupply() / currency.getMaxCoinSupply() * 100), getContext()));
.setText(PlaceholderManager.getEmitedPercentageString(numberConformer(currency.getMinedCoinSupply() / currency.getMaxCoinSupply() * 100), getActivity().getBaseContext()));
if(currency.getMarketCapitalization() != 0)
{
((TextView) view.findViewById(R.id.txtViewMarketCapitalization))
.setText(PlaceholderManager.getValueString(numberConformer(currency.getMarketCapitalization()), getContext()));
.setText(PlaceholderManager.getValueString(numberConformer(currency.getMarketCapitalization()), getActivity().getBaseContext()));
view.findViewById(R.id.linearMarketCap).setVisibility(View.VISIBLE);
}

View File

@ -16,14 +16,15 @@ import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.herbron.moodl.DataNotifiers.BinanceUpdateNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.Trade;
import com.herbron.moodl.DataManagers.CurrencyData.Transaction;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.ExchangeManager.BinanceManager;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.LayoutManagers.TradeListAdapter;
import com.herbron.moodl.LayoutManagers.TransactionListAdapter;
import com.herbron.moodl.CustomAdapters.TradeListAdapter;
import com.herbron.moodl.CustomAdapters.TransactionListAdapter;
import com.herbron.moodl.R;
import java.util.ArrayList;
@ -48,13 +49,13 @@ public class Transactions extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_transactions_detailsactivity, container, false);
view = inflater.inflate(R.layout.detailsactivity_fragment_transactions, container, false);
PreferencesManager preferencesManager = new PreferencesManager(getContext());
PreferencesManager preferencesManager = new PreferencesManager(getActivity().getBaseContext());
currency = getActivity().getIntent().getParcelableExtra("currency");
databaseManager = new DatabaseManager(getContext());
binanceManager = new BinanceManager(preferencesManager.getBinancePublicKey(), preferencesManager.getBinancePrivateKey());
databaseManager = new DatabaseManager(getActivity().getBaseContext());
//binanceManager = new BinanceManager(preferencesManager.getBinancePublicKey(), preferencesManager.getBinancePrivateKey());
tradeLayout = view.findViewById(R.id.listTrades);
transactionLayout = view.findViewById(R.id.listTransactions);
@ -63,15 +64,15 @@ public class Transactions extends Fragment {
TransactionUpdater transactionUpdater = new TransactionUpdater();
transactionUpdater.execute();
TradeUpdater updater = new TradeUpdater();
updater.execute();
/*TradeUpdater updater = new TradeUpdater();
updater.execute();*/
return view;
}
private void loadingIndicatorGenerator()
{
loadingFooter = LayoutInflater.from(getContext()).inflate(R.layout.listview_loading_indicator, null, false);
loadingFooter = LayoutInflater.from(getActivity().getBaseContext()).inflate(R.layout.listview_loading_indicator, null, false);
Drawable drawable = ((ProgressBar) loadingFooter.findViewById(R.id.progressIndicator)).getIndeterminateDrawable();
drawable.mutate();
@ -107,7 +108,7 @@ public class Transactions extends Fragment {
});
}
tradeListAdapter = new TradeListAdapter(getContext(), trades);
tradeListAdapter = new TradeListAdapter(getActivity().getBaseContext(), trades);
tradeLayout.setAdapter(tradeListAdapter);
tradeLayout.setTextFilterEnabled(false);
@ -179,7 +180,7 @@ public class Transactions extends Fragment {
private void drawTransactionList(ArrayList<Transaction> transactions)
{
TransactionListAdapter transactionListAdapter = new TransactionListAdapter(getContext(), transactions);
TransactionListAdapter transactionListAdapter = new TransactionListAdapter(getActivity(), transactions);
transactionLayout.setAdapter(transactionListAdapter);
transactionLayout.setTextFilterEnabled(false);
@ -209,7 +210,7 @@ public class Transactions extends Fragment {
}
}
private class TradeUpdater extends AsyncTask<Void, Integer, Void>
private class TradeUpdater extends AsyncTask<Void, Integer, Void> implements BinanceUpdateNotifierInterface
{
@Override
protected void onPreExecute()
@ -226,41 +227,8 @@ public class Transactions extends Fragment {
@Override
protected Void doInBackground(Void... params)
{
binanceManager.updateTrades(new BinanceManager.BinanceCallBack() {
@Override
public void onSuccess() {
ArrayList<Trade> trades = binanceManager.getTrades();
returnedTrades = new ArrayList<>();
for(int i = trades.size() - 1; i >= 0 ; i--)
{
returnedTrades.add(trades.get(i));
}
try {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayList<Trade> trades = new ArrayList<>();
for(int i = 0; i < 20 && i < returnedTrades.size(); i++)
{
trades.add(returnedTrades.get(i));
}
drawTradeList(trades);
}
});
} catch (NullPointerException e) {
Log.d("moodl", "Transactions do not need to be updated anymore");
}
}
@Override
public void onError(String error) {
}
}, currency.getSymbol());
binanceManager.updateTrades(currency.getSymbol());
return null;
}
@ -270,5 +238,44 @@ public class Transactions extends Fragment {
{
}
@Override
public void onBinanceTradesUpdated() {
ArrayList<Trade> trades = binanceManager.getTrades();
returnedTrades = new ArrayList<>();
for(int i = trades.size() - 1; i >= 0 ; i--)
{
returnedTrades.add(trades.get(i));
}
try {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayList<Trade> trades = new ArrayList<>();
for(int i = 0; i < 20 && i < returnedTrades.size(); i++)
{
trades.add(returnedTrades.get(i));
}
drawTradeList(trades);
}
});
} catch (NullPointerException e) {
Log.d("moodl", "Transactions do not need to be updated anymore");
}
}
@Override
public void onBinanceBalanceUpdateSuccess() {
}
@Override
public void onBinanceBalanceUpdateError(int accountId, String error) {
}
}
}

View File

@ -0,0 +1,66 @@
package com.herbron.moodl.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.CustomAdapters.ExchangeDescriptionListAdapter;
import com.herbron.moodl.R;
public class ExchangeListActivity extends AppCompatActivity {
private DatabaseManager databaseManager;
private ListView exchangeListView;
private ExchangeDescriptionListAdapter exchangeDescriptionListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exchange_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
databaseManager = new DatabaseManager(this);
exchangeListView = findViewById(R.id.exchange_listView);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ExchangeListActivity.this, AddExchangeActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onResume() {
super.onResume();
exchangeDescriptionListAdapter = new ExchangeDescriptionListAdapter(getApplicationContext(), databaseManager.getExchanges());
exchangeListView.setAdapter(exchangeDescriptionListAdapter);
exchangeDescriptionListAdapter.notifyDataSetChanged();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}

View File

@ -4,6 +4,7 @@ import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
@ -17,12 +18,15 @@ import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
@ -49,6 +53,10 @@ import static com.herbron.moodl.MoodlBox.numberConformer;
public class HomeActivity extends AppCompatActivity implements BalanceUpdateInterface {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
private DrawerLayout drawerLayout;
private Fragment watchlistFragment;
private Fragment holdingsFragment;
@ -56,6 +64,8 @@ public class HomeActivity extends AppCompatActivity implements BalanceUpdateInte
private Fragment overviewFragment;
private Fragment currentFragment;
private DatabaseManager databaseManager;
private TextView alertTextView;
private BalanceSwitchManagerInterface switchInterface;
@ -76,6 +86,7 @@ public class HomeActivity extends AppCompatActivity implements BalanceUpdateInte
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
databaseManager = new DatabaseManager(this);
setListener((BalanceSwitchManagerInterface) holdingsFragment);
@ -118,9 +129,35 @@ public class HomeActivity extends AppCompatActivity implements BalanceUpdateInte
}
});
setupSettingsAlert(navigationView);
setupBalanceSwitch();
}
private void setupSettingsAlert(NavigationView navigationView)
{
alertTextView = (TextView) navigationView.getMenu().findItem(R.id.navigation_settings).getActionView();
alertTextView.setTextColor(getResources().getColor(R.color.decreaseCandle));
alertTextView.setGravity(Gravity.CENTER);
alertTextView.setTypeface(null, Typeface.BOLD);
updateSettingsAlertNumber();
}
private void updateSettingsAlertNumber()
{
int disabledNumber = databaseManager.getDisabledExchangeAccountsNumber();
if(disabledNumber > 0)
{
alertTextView.setText(String.valueOf(disabledNumber));
}
else
{
alertTextView.setText("");
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void setStatusBarGradiant(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
@ -192,6 +229,7 @@ public class HomeActivity extends AppCompatActivity implements BalanceUpdateInte
protected void onResume() {
super.onResume();
updateSettingsAlertNumber();
}
@Override
@ -216,9 +254,4 @@ public class HomeActivity extends AppCompatActivity implements BalanceUpdateInte
drawerBalanceTextView.setText(PlaceholderManager.getValueString(numberConformer(value), getApplicationContext()));
}
}
public interface IconCallBack
{
void onSuccess(Bitmap bitmap);
}
}

View File

@ -27,19 +27,19 @@ import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.DataManagers.BalanceManager;
import com.herbron.moodl.DataNotifiers.CoinmarketcapNotifierInterface;
import com.herbron.moodl.DataNotifiers.CryptocompareNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyDetailsList;
import com.herbron.moodl.DataManagers.MarketCapManager;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CoinmarketCapAPIManager;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.LayoutManagers.CustomPieChart;
import com.herbron.moodl.CustomLayouts.CustomPieChart;
import com.herbron.moodl.MoodlBox;
import com.herbron.moodl.DataNotifiers.MoodlboxNotifierInterface;
import com.herbron.moodl.PlaceholderManager;
import com.herbron.moodl.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.herbron.moodl.MoodlBox.getColor;
@ -49,15 +49,14 @@ import static java.lang.Math.abs;
* Created by Tiji on 13/04/2018.
*/
public class MarketCapitalization extends Fragment {
public class MarketCapitalization extends Fragment implements CryptocompareNotifierInterface, CoinmarketcapNotifierInterface {
private PreferencesManager preferencesManager;
private MarketCapManager marketCapManager;
private HashMap<String, Integer> dominantCurrenciesColors;
private CoinmarketCapAPIManager coinmarketCapAPIManager;
private SwipeRefreshLayout refreshLayout;
private long lastTimestamp;
private String defaultCurrency;
private CurrencyDetailsList currencyDetailsList;
private CryptocompareApiManager cryptocompareApiManager;
private boolean isDetailsUpdated;
private boolean isTopCurrenciesUpdated;
private boolean isMarketpCapUpdated;
@ -68,22 +67,18 @@ public class MarketCapitalization extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_marketcap_homeactivity, container, false);
view = inflater.inflate(R.layout.homeactivity_fragment_marketcap, container, false);
preferencesManager = new PreferencesManager(getContext());
marketCapManager = new MarketCapManager(getContext());
preferencesManager = new PreferencesManager(getActivity().getBaseContext());
coinmarketCapAPIManager = CoinmarketCapAPIManager.getInstance(getActivity().getBaseContext());
coinmarketCapAPIManager.addListener(this);
currencyDetailsList = CurrencyDetailsList.getInstance(getContext());
cryptocompareApiManager = CryptocompareApiManager.getInstance(getActivity().getBaseContext());
cryptocompareApiManager.addListener(this);
if(!currencyDetailsList.isUpToDate())
if(!cryptocompareApiManager.isDetailsUpToDate())
{
currencyDetailsList.update(new BalanceManager.IconCallBack() {
@Override
public void onSuccess() {
isDetailsUpdated = true;
countCompletedMarketCapRequest();
}
});
cryptocompareApiManager.updateDetails();
}
else
{
@ -152,7 +147,6 @@ public class MarketCapitalization extends Fragment {
{
updateMarketCap(false);
}
}
private void updateMarketCap(boolean mustUpdate)
@ -171,22 +165,9 @@ public class MarketCapitalization extends Fragment {
lastTimestamp = System.currentTimeMillis() / 1000;
marketCapManager.updateTopCurrencies(new MarketCapManager.VolleyCallBack() {
@Override
public void onSuccess()
{
isTopCurrenciesUpdated = true;
countCompletedMarketCapRequest();
}
}, preferencesManager.getDefaultCurrency());
coinmarketCapAPIManager.updateTopCurrencies(preferencesManager.getDefaultCurrency());
marketCapManager.updateMarketCap(new MarketCapManager.VolleyCallBack() {
@Override
public void onSuccess() {
isMarketpCapUpdated = true;
countCompletedMarketCapRequest();
}
}, preferencesManager.getDefaultCurrency());
coinmarketCapAPIManager.updateMarketCap(preferencesManager.getDefaultCurrency());
}
else
{
@ -217,14 +198,14 @@ public class MarketCapitalization extends Fragment {
private PieDataSet getMarketDominanceDataSet()
{
List<PieEntry> entries = new ArrayList<>();
List<Currency> topCurrencies = marketCapManager.getTopCurrencies();
List<Currency> topCurrencies = coinmarketCapAPIManager.getTopCurrencies();
ArrayList<Integer> colors = new ArrayList<>();
float topCurrenciesDominance = 0;
for(int i = 0; i < topCurrencies.size(); i++)
{
PieEntry pieEntry = new PieEntry(topCurrencies.get(i).getDominance(marketCapManager.getMarketCap()), topCurrencies.get(i).getSymbol(), topCurrencies.get(i).getSymbol());
PieEntry pieEntry = new PieEntry(topCurrencies.get(i).getDominance(coinmarketCapAPIManager.getMarketCap()), topCurrencies.get(i).getSymbol(), topCurrencies.get(i).getSymbol());
if(pieEntry.getValue() < 3)
{
@ -232,7 +213,7 @@ public class MarketCapitalization extends Fragment {
}
entries.add(pieEntry);
topCurrenciesDominance += topCurrencies.get(i).getDominance(marketCapManager.getMarketCap());
topCurrenciesDominance += topCurrencies.get(i).getDominance(coinmarketCapAPIManager.getMarketCap());
colors.add(topCurrencies.get(i).getChartColor());
}
@ -260,7 +241,7 @@ public class MarketCapitalization extends Fragment {
{
iconCounter++;
if(iconCounter >= marketCapManager.getTopCurrencies().size())
if(iconCounter >= coinmarketCapAPIManager.getTopCurrencies().size())
{
refreshDisplayedData();
}
@ -268,24 +249,25 @@ public class MarketCapitalization extends Fragment {
private void updateIcons()
{
for(int i = 0; i < marketCapManager.getTopCurrencies().size(); i++)
for(int i = 0; i < coinmarketCapAPIManager.getTopCurrencies().size(); i++)
{
final Currency localCurrency = marketCapManager.getTopCurrencies().get(i);
final Currency localCurrency = coinmarketCapAPIManager.getTopCurrencies().get(i);
final int index = i;
String iconUrl = MoodlBox.getIconUrl(marketCapManager.getTopCurrencies().get(i).getSymbol(), 500, currencyDetailsList);
String iconUrl = MoodlBox.getIconUrl(coinmarketCapAPIManager.getTopCurrencies().get(i).getSymbol(), 500, cryptocompareApiManager);
if(iconUrl != null)
{
MoodlBox.getBitmapFromURL(iconUrl, localCurrency.getSymbol(), getResources(), getContext(), new HomeActivity.IconCallBack() {
MoodlBox.getBitmapFromURL(iconUrl, localCurrency.getSymbol(), getResources(), getActivity().getBaseContext(), new MoodlboxNotifierInterface() {
@Override
public void onSuccess(Bitmap bitmapIcon) {
public void onBitmapDownloaded(Bitmap bitmapIcon) {
Palette.Builder builder = Palette.from(bitmapIcon);
marketCapManager.getTopCurrencies().get(index).setIcon(bitmapIcon);
marketCapManager.getTopCurrencies().get(index).setChartColor(builder.generate().getDominantColor(getColor(R.color.default_color, getContext())));
coinmarketCapAPIManager.getTopCurrencies().get(index).setIcon(bitmapIcon);
coinmarketCapAPIManager.getTopCurrencies().get(index).setChartColor(builder.generate().getDominantColor(getColor(R.color.default_color, getActivity().getBaseContext())));
countIcons();
}
});
}
@ -310,11 +292,11 @@ public class MarketCapitalization extends Fragment {
pieChart.setTouchEnabled(true);
pieChart.setEntryLabelColor(Color.WHITE);
updateDetails(marketCapManager.getMarketCap(), marketCapManager.getDayVolume(), getString(R.string.global), 0);
updateDetails(coinmarketCapAPIManager.getMarketCap(), coinmarketCapAPIManager.getDayVolume(), getString(R.string.global), 0);
((TextView) view.findViewById(R.id.textViewActiveCrypto))
.setText(marketCapManager.getActive_crypto());
.setText(coinmarketCapAPIManager.getActive_crypto());
((TextView) view.findViewById(R.id.textViewActiveMarkets))
.setText(marketCapManager.getActive_markets());
.setText(coinmarketCapAPIManager.getActive_markets());
pieChart.setOnTouchListener(new View.OnTouchListener() {
@Override
@ -349,7 +331,7 @@ public class MarketCapitalization extends Fragment {
if(!e.getData().equals("others"))
{
Currency currency = marketCapManager.getCurrencyFromSymbol((String) e.getData());
Currency currency = coinmarketCapAPIManager.getCurrencyFromSymbol((String) e.getData());
view.findViewById(R.id.currencyIcon).setVisibility(View.VISIBLE);
view.findViewById(R.id.layoutPercentageDominance).setVisibility(View.VISIBLE);
@ -362,13 +344,13 @@ public class MarketCapitalization extends Fragment {
}
else
{
double othersMarketCap = marketCapManager.getMarketCap();
double othersVolume = marketCapManager.getDayVolume();
double othersMarketCap = coinmarketCapAPIManager.getMarketCap();
double othersVolume = coinmarketCapAPIManager.getDayVolume();
for(int i = 0; i < marketCapManager.getTopCurrencies().size(); i++)
for(int i = 0; i < coinmarketCapAPIManager.getTopCurrencies().size(); i++)
{
othersMarketCap -= marketCapManager.getTopCurrencies().get(i).getMarketCapitalization();
othersVolume -= marketCapManager.getTopCurrencies().get(i).getVolume24h();
othersMarketCap -= coinmarketCapAPIManager.getTopCurrencies().get(i).getMarketCapitalization();
othersVolume -= coinmarketCapAPIManager.getTopCurrencies().get(i).getVolume24h();
}
view.findViewById(R.id.currencyIcon).setVisibility(View.GONE);
@ -390,7 +372,7 @@ public class MarketCapitalization extends Fragment {
view.findViewById(R.id.layoutActiveCrypto).setVisibility(View.VISIBLE);
view.findViewById(R.id.layoutActiveMarkets).setVisibility(View.VISIBLE);
updateDetails(marketCapManager.getMarketCap(), marketCapManager.getDayVolume(), getString(R.string.global), 0);
updateDetails(coinmarketCapAPIManager.getMarketCap(), coinmarketCapAPIManager.getDayVolume(), getString(R.string.global), 0);
pieChart.setDrawCenterText(true);
}
@ -405,13 +387,13 @@ public class MarketCapitalization extends Fragment {
private void updateDetails(double marketCap, double volume, String title, double percentage)
{
((TextView) view.findViewById(R.id.textViewMarketCap))
.setText(PlaceholderManager.getValueString(MoodlBox.numberConformer(marketCap), getContext()));
.setText(PlaceholderManager.getValueString(MoodlBox.numberConformer(marketCap), getActivity().getBaseContext()));
((TextView) view.findViewById(R.id.textViewVolume))
.setText(PlaceholderManager.getValueString(MoodlBox.numberConformer(volume), getContext()));
.setText(PlaceholderManager.getValueString(MoodlBox.numberConformer(volume), getActivity().getBaseContext()));
((TextView) view.findViewById(R.id.textViewTitle))
.setText(title);
((TextView) view.findViewById(R.id.textViewDominancePercentage))
.setText(PlaceholderManager.getPercentageString(MoodlBox.numberConformer(percentage), getContext()));
.setText(PlaceholderManager.getPercentageString(MoodlBox.numberConformer(percentage), getActivity().getBaseContext()));
}
private SpannableString generateCenterSpannableText() {
@ -419,4 +401,37 @@ public class MarketCapitalization extends Fragment {
SpannableString spannableString = new SpannableString(getString(R.string.market_dominance));
return spannableString;
}
@Override
public void onDetailsUpdated() {
isDetailsUpdated = true;
countCompletedMarketCapRequest();
}
@Override
public void onExchangesUpdated() {
}
@Override
public void onCurrenciesRetrieved(List<Currency> currencyList) {
}
@Override
public void onTopCurrenciesUpdated() {
isTopCurrenciesUpdated = true;
countCompletedMarketCapRequest();
}
@Override
public void onMarketCapUpdated() {
isMarketpCapUpdated = true;
countCompletedMarketCapRequest();
}
@Override
public void onListingUpdated() {
}
}

View File

@ -1,7 +1,6 @@
package com.herbron.moodl.Activities.HomeActivityFragments;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
@ -18,13 +17,14 @@ import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ListView;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.DataNotifiers.CoinmarketcapNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyDetailsList;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyTickerList;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CoinmarketCapAPIManager;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.LayoutManagers.OverviewListAdapter;
import com.herbron.moodl.CustomAdapters.OverviewListAdapter;
import com.herbron.moodl.MoodlBox;
import com.herbron.moodl.DataNotifiers.MoodlboxNotifierInterface;
import com.herbron.moodl.R;
import java.util.List;
@ -35,10 +35,10 @@ import static com.herbron.moodl.MoodlBox.getDrawable;
* Created by Administrator on 27/05/2018.
*/
public class Overview extends Fragment {
public class Overview extends Fragment implements CoinmarketcapNotifierInterface {
private CurrencyTickerList currencyTickerList;
private CurrencyDetailsList currencyDetailsList;
private CoinmarketCapAPIManager coinmarketCapAPIManager;
private CryptocompareApiManager cryptocompareApiManager;
private PreferencesManager preferenceManager;
private OverviewListAdapter overviewListAdapter;
@ -52,14 +52,16 @@ public class Overview extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View fragmentView = inflater.inflate(R.layout.fragment_overview_homeactivity, container, false);
View fragmentView = inflater.inflate(R.layout.homeactivity_fragment_overview, container, false);
currencyTickerList = CurrencyTickerList.getInstance(getContext());
currencyDetailsList = CurrencyDetailsList.getInstance(getContext());
coinmarketCapAPIManager = CoinmarketCapAPIManager.getInstance(getActivity().getBaseContext());
cryptocompareApiManager = CryptocompareApiManager.getInstance(getActivity().getBaseContext());
coinmarketCapAPIManager.addListener(this);
fragmentView.findViewById(R.id.toolbar).bringToFront();
preferenceManager = new PreferencesManager(getContext());
preferenceManager = new PreferencesManager(getActivity().getBaseContext());
listLayout = fragmentView.findViewById(R.id.linearLayoutOverview);
@ -92,6 +94,7 @@ public class Overview extends Fragment {
return fragmentView;
}
private void setupDrawerButton(View view)
{
ImageButton drawerButton = view.findViewById(R.id.drawer_button);
@ -132,18 +135,34 @@ public class Overview extends Fragment {
}
}
public interface UpdateCallBack
{
void onSuccess(List<Currency> currencyList);
}
private void loadingIndicatorGenerator()
{
loadingFooter = LayoutInflater.from(getContext()).inflate(R.layout.listview_loading_indicator, null, false);
loadingFooter = LayoutInflater.from(getActivity().getBaseContext()).inflate(R.layout.listview_loading_indicator, null, false);
listLayout.addFooterView(loadingFooter);
}
@Override
public void onCurrenciesRetrieved(List<Currency> currencyList) {
IconDownloader iconDownloader = new IconDownloader();
iconDownloader.execute(currencyList);
}
@Override
public void onTopCurrenciesUpdated() {
}
@Override
public void onMarketCapUpdated() {
}
@Override
public void onListingUpdated() {
}
private class CurrencyLoader extends AsyncTask<Void, Void, Void>
{
@Override
@ -155,14 +174,7 @@ public class Overview extends Fragment {
@Override
protected Void doInBackground(Void... voids) {
currencyTickerList.getCurrenciesFrom(listLayout.getCount(), preferenceManager.getDefaultCurrency(), new UpdateCallBack() {
@Override
public void onSuccess(List<Currency> currencyList)
{
IconDownloader iconDownloader = new IconDownloader();
iconDownloader.execute(currencyList);
}
});
coinmarketCapAPIManager.getCurrenciesFrom(listLayout.getCount(), preferenceManager.getDefaultCurrency());
return null;
}
}
@ -174,15 +186,17 @@ public class Overview extends Fragment {
@Override
protected Void doInBackground(List<Currency>... currencies) {
iconCounter = 0;
for(Currency currency : currencies[0])
{
String iconUrl = MoodlBox.getIconUrl(currency.getSymbol(), currencyDetailsList);
String iconUrl = MoodlBox.getIconUrl(currency.getSymbol(), cryptocompareApiManager);
if(iconUrl != null)
{
MoodlBox.getBitmapFromURL(iconUrl, currency.getSymbol(), getResources(), getContext(), new HomeActivity.IconCallBack() {
MoodlBox.getBitmapFromURL(iconUrl, currency.getSymbol(), getResources(), getActivity().getBaseContext(), new MoodlboxNotifierInterface() {
@Override
public void onSuccess(Bitmap bitmap) {
public void onBitmapDownloaded(Bitmap bitmap) {
currency.setIcon(bitmap);
updateChartColor(currency);
countIcons(currencies[0]);
@ -191,7 +205,7 @@ public class Overview extends Fragment {
}
else
{
Drawable drawable = getDrawable(R.drawable.ic_panorama_fish_eye_24dp, getContext());
Drawable drawable = getDrawable(R.drawable.ic_panorama_fish_eye_24dp, getActivity().getBaseContext());
Bitmap icon = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
@ -219,9 +233,10 @@ public class Overview extends Fragment {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(overviewListAdapter == null)
{
overviewListAdapter = new OverviewListAdapter(getContext(), currencyList, getActivity());
overviewListAdapter = new OverviewListAdapter(Overview.this.getContext(), currencyList, getActivity());
listLayout.setAdapter(overviewListAdapter);
listLayout.setTextFilterEnabled(false);

View File

@ -9,7 +9,6 @@ import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
@ -33,22 +32,25 @@ import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.daasuu.ei.Ease;
import com.daasuu.ei.EasingInterpolator;
import com.herbron.moodl.Activities.CurrencySelectionActivity;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.Activities.RecordTransactionActivity;
import com.herbron.moodl.BalanceUpdateInterface;
import com.herbron.moodl.DataNotifiers.CoinmarketcapNotifierInterface;
import com.herbron.moodl.DataNotifiers.CryptocompareNotifierInterface;
import com.herbron.moodl.CurrencyInfoUpdateNotifierInterface;
import com.herbron.moodl.DataManagers.BalanceManager;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyCardview;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyTickerList;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CoinmarketCapAPIManager;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.BalanceSwitchManagerInterface;
import com.herbron.moodl.DataNotifierInterface;
import com.herbron.moodl.DataNotifiers.BalanceUpdateNotifierInterface;
import com.herbron.moodl.MoodlBox;
import com.herbron.moodl.DataNotifiers.MoodlboxNotifierInterface;
import com.herbron.moodl.PlaceholderManager;
import com.herbron.moodl.R;
@ -66,7 +68,7 @@ import static java.lang.Math.abs;
* Created by Tiji on 13/04/2018.
*/
public class Summary extends Fragment implements BalanceSwitchManagerInterface, DataNotifierInterface {
public class Summary extends Fragment implements BalanceSwitchManagerInterface, BalanceUpdateNotifierInterface, CryptocompareNotifierInterface, CoinmarketcapNotifierInterface {
private LinearLayout currencyLayout;
private PreferencesManager preferencesManager;
@ -74,7 +76,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
private SwipeRefreshLayout refreshLayout;
private Dialog loadingDialog;
private String defaultCurrency;
private CurrencyTickerList currencyTickerList;
private CoinmarketCapAPIManager coinmarketCapAPIManager;
private TextView toolbarSubtitle;
private CollapsingToolbarLayout toolbarLayout;
@ -92,16 +94,18 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
private long lastTimestamp;
private BalanceUpdateInterface balanceUpdateInterface;
private CryptocompareApiManager cryptocompareApiManager;
@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View fragmentView = inflater.inflate(R.layout.fragment_summary_homeactivity, container, false);
View fragmentView = inflater.inflate(R.layout.homeactivity_fragment_summary, container, false);
preferencesManager = new PreferencesManager(getActivity());
balanceManager = new BalanceManager(getContext());
currencyTickerList = CurrencyTickerList.getInstance(getActivity());
balanceManager = new BalanceManager(getActivity());
coinmarketCapAPIManager = CoinmarketCapAPIManager.getInstance(getActivity());
cryptocompareApiManager = CryptocompareApiManager.getInstance(getActivity());
currencyLayout = fragmentView.findViewById(R.id.currencyListLayout);
refreshLayout = fragmentView.findViewById(R.id.swiperefreshsummary);
@ -113,6 +117,9 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
defaultCurrency = preferencesManager.getDefaultCurrency();
cryptocompareApiManager.addListener(this);
coinmarketCapAPIManager.addListener(this);
handler = new Handler();
initiateUpdateRunnable();
@ -180,6 +187,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
refreshLayout.setRefreshing(false);
showErrorSnackbar();
Log.d("moodl", "Error > Refresh out of time");
}
if (loadingDialog.isShowing())
@ -187,6 +195,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
loadingDialog.dismiss();
showErrorSnackbar();
Log.d("moodl", "Error > Refresh out of time");
}
}
};
@ -197,7 +206,6 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
layoutRefresherRunnable = new Runnable() {
@Override
public void run() {
final List<View> currencyView = new ArrayList<>();
final List<Currency> renderedCurrencies = new ArrayList<>();
if (balanceManager.getTotalBalance() != null)
@ -205,7 +213,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
for (int i = 0; i < balanceManager.getTotalBalance().size(); i++) {
final Currency currency = balanceManager.getTotalBalance().get(i);
if (!currency.getSymbol().equals("USD") && ((currency.getBalance() * currency.getValue()) >= preferencesManager.getMinimumAmount())) {
if (!currency.getSymbol().equals("USD") && (Math.abs(currency.getBalance() * currency.getValue()) >= preferencesManager.getMinimumAmount())) {
//currencyView.add(layoutGenerator.getInfoLayout(currency, totalValue, preferencesManager.isBalanceHidden()));
renderedCurrencies.add(currency);
}
@ -220,7 +228,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
for(int i = 0; i < renderedCurrencies.size(); i++)
{
//currencyLayout.addView(currencyView.get(i));
currencyLayout.addView(new CurrencyCardview(getActivity(), renderedCurrencies.get(i), totalValue, preferencesManager.isBalanceHidden()));
currencyLayout.addView(new CurrencyCardview(getActivity(), renderedCurrencies.get(i), getActivity(), totalValue, preferencesManager.isBalanceHidden()));
}
if(loadingDialog.isShowing())
@ -242,7 +250,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
addCurrencyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent addIntent = new Intent(getActivity(), CurrencySelectionActivity.class);
Intent addIntent = new Intent(getActivity(), RecordTransactionActivity.class);
startActivity(addIntent);
}
@ -255,10 +263,10 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
Random random = new Random();
LinearLayout splashLayout = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.splash_screen, null, true);
LinearLayout splashLayout = (LinearLayout) LayoutInflater.from(getActivity().getBaseContext()).inflate(R.layout.splash_screen, null, true);
LinearLayout animatedLayout = splashLayout.findViewById(R.id.animatedViewsLayout);
File cacheDir = new File(getContext().getCacheDir().getAbsolutePath());
File cacheDir = new File(getActivity().getBaseContext().getCacheDir().getAbsolutePath());
File[] cacheFiles = cacheDir.listFiles();
if(cacheFiles.length > 4)
@ -278,7 +286,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(ContextCompat.getColor(getContext(), R.color.white));
paint.setColor(ContextCompat.getColor(getActivity().getBaseContext(), R.color.white));
Canvas canvas = new Canvas(result);
canvas.drawCircle(result.getHeight()/2, result.getWidth()/2, 75, paint);
@ -333,7 +341,6 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
}
lastTimestamp = System.currentTimeMillis() / 1000;
balanceManager.updateExchangeKeys();
resetCounters();
DataUpdater updater = new DataUpdater();
@ -542,16 +549,6 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
displayBalance(preferencesManager.isBalanceHidden());
}
@Override
public void onTickerListUpdated() {
}
@Override
public void onDetailsUpdated() {
}
@Override
public void onBalanceDataUpdated() {
final List<Currency> balance = balanceManager.getTotalBalance();
@ -560,10 +557,21 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
{
for(int i = 0; i < balance.size(); i++)
{
balance.get(i).updatePrice(getActivity(), defaultCurrency, new Currency.CurrencyCallBack() {
balance.get(i).updatePrice(getActivity(), defaultCurrency, new CurrencyInfoUpdateNotifierInterface() {
@Override
public void onSuccess(Currency currency) {
public void onTimestampPriceUpdated(String price) {
}
@Override
public void onHistoryDataUpdated() {
}
@Override
public void onPriceUpdated(Currency currency) {
countCoins(true, false, false);
}
});
}
@ -582,7 +590,12 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
@Override
public void onBalanceError(String error)
{
generateSnackBarError(error);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
generateSnackBarError(error);
}
});
}
private void generateSnackBarError(String error)
@ -623,6 +636,36 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
}
}
@Override
public void onDetailsUpdated() {
countCoins(false, true, false);
}
@Override
public void onExchangesUpdated() {
}
@Override
public void onCurrenciesRetrieved(List<Currency> currencyList) {
}
@Override
public void onTopCurrenciesUpdated() {
}
@Override
public void onMarketCapUpdated() {
}
@Override
public void onListingUpdated() {
countCoins(false, false, true);
}
private class UiHeavyLoadCalculator extends AsyncTask<Void, Integer, Void>
{
@ -647,11 +690,11 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
{
Palette.Builder builder = Palette.from(currency.getIcon());
currency.setChartColor(builder.generate().getDominantColor(getColor(R.color.default_color, getContext())));
currency.setChartColor(builder.generate().getDominantColor(getColor(R.color.default_color, getActivity().getBaseContext())));
}
else
{
currency.setChartColor(getColor(R.color.default_color, getContext()));
currency.setChartColor(getColor(R.color.default_color, getActivity().getBaseContext()));
}
}
@ -680,7 +723,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
{
final Currency localCurrency = balanceManager.getTotalBalance().get(i);
localCurrency.setTickerId(currencyTickerList.getTickerIdForSymbol(localCurrency.getSymbol()));
localCurrency.setTickerId(coinmarketCapAPIManager.getTickerIdForSymbol(localCurrency.getSymbol()));
updateChartColor(localCurrency);
@ -764,13 +807,13 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
{
final Currency localCurrency = balanceManager.getTotalBalance().get(i);
String iconUrl = MoodlBox.getIconUrl(localCurrency.getSymbol(), balanceManager.getCurrencyDetailList());
String iconUrl = MoodlBox.getIconUrl(localCurrency.getSymbol(), balanceManager.getCryptocompareApiManager());
if(iconUrl != null)
{
MoodlBox.getBitmapFromURL(iconUrl, localCurrency.getSymbol(), getResources(), getContext(), new HomeActivity.IconCallBack() {
MoodlBox.getBitmapFromURL(iconUrl, localCurrency.getSymbol(), getResources(), getActivity().getBaseContext(), new MoodlboxNotifierInterface() {
@Override
public void onSuccess(Bitmap bitmapIcon) {
public void onBitmapDownloaded(Bitmap bitmapIcon) {
localCurrency.setIcon(bitmapIcon);
countIcons();
}
@ -778,7 +821,7 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
}
else
{
Drawable drawable = getDrawable(R.drawable.ic_panorama_fish_eye_24dp, getContext());
Drawable drawable = getDrawable(R.drawable.ic_panorama_fish_eye_24dp, getActivity().getBaseContext());
Bitmap icon = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
@ -803,27 +846,23 @@ public class Summary extends Fragment implements BalanceSwitchManagerInterface,
@Override
protected Void doInBackground(Void... params)
{
if(!currencyTickerList.isUpToDate())
if(!coinmarketCapAPIManager.isUpToDate())
{
currencyTickerList.updateListing(new com.herbron.moodl.DataManagers.BalanceManager.IconCallBack() {
@Override
public void onSuccess() {
countCoins(false, false, true);
}
});
coinmarketCapAPIManager.updateListing();
}
else
{
countCoins(false, false, true);
}
balanceManager.updateDetails(new com.herbron.moodl.DataManagers.BalanceManager.IconCallBack() {
@Override
public void onSuccess()
{
countCoins(false, true, false);
}
});
if(!cryptocompareApiManager.isDetailsUpToDate())
{
cryptocompareApiManager.updateDetails();
}
else
{
countCoins(false, true, false);
}
balanceManager.updateTotalBalance();

View File

@ -13,53 +13,53 @@ import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.graphics.Palette;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.herbron.moodl.Activities.CurrencySelectionActivity;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.DataManagers.BalanceManager;
import com.herbron.moodl.DataNotifiers.CoinmarketcapNotifierInterface;
import com.herbron.moodl.DataNotifiers.CryptocompareNotifierInterface;
import com.herbron.moodl.CurrencyInfoUpdateNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyCardview;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyDetailsList;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyTickerList;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CoinmarketCapAPIManager;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.DataManagers.WatchlistManager;
import com.herbron.moodl.MoodlBox;
import com.herbron.moodl.DataNotifiers.MoodlboxNotifierInterface;
import com.herbron.moodl.R;
import com.jmedeisis.draglinearlayout.DragLinearLayout;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import static com.herbron.moodl.MoodlBox.collapseW;
import static com.herbron.moodl.MoodlBox.expandW;
import static com.herbron.moodl.MoodlBox.getColor;
import static java.lang.Math.abs;
/**
* Created by Tiji on 13/04/2018.
*/
public class Watchlist extends Fragment {
public class Watchlist extends Fragment implements CryptocompareNotifierInterface {
private WatchlistManager watchlistManager;
private View view;
private int watchlistCounter;
private CurrencyDetailsList currencyDetailsList;
private CryptocompareApiManager cryptocompareApiManager;
private SwipeRefreshLayout refreshLayout;
private DragLinearLayout dragLinearLayout;
private long lastTimestamp;
private PreferencesManager preferencesManager;
private String defaultCurrency;
private CurrencyTickerList currencyTickerList;
private CoinmarketCapAPIManager coinmarketCapAPIManager;
private boolean tickerUpdated;
private boolean detailsUpdated;
private boolean editModeEnabled;
@ -69,18 +69,19 @@ public class Watchlist extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_watchlist_homeactivity, container, false);
view = inflater.inflate(R.layout.homeactivity_fragment_watchlist, container, false);
refreshLayout = view.findViewById(R.id.swiperefreshwatchlist);
dragLinearLayout = view.findViewById(R.id.linearLayoutWatchlist);
currencyDetailsList = CurrencyDetailsList.getInstance(getContext());
preferencesManager = new PreferencesManager(getContext());
databaseManager = new DatabaseManager(getContext());
cryptocompareApiManager = CryptocompareApiManager.getInstance(getActivity().getBaseContext());
preferencesManager = new PreferencesManager(getActivity().getBaseContext());
databaseManager = new DatabaseManager(getActivity().getBaseContext());
lastTimestamp = 0;
defaultCurrency = preferencesManager.getDefaultCurrency();
currencyTickerList = CurrencyTickerList.getInstance(getActivity());
coinmarketCapAPIManager = CoinmarketCapAPIManager.getInstance(getActivity());
tickerUpdated = false;
cryptocompareApiManager.addListener(this);
updateTickerList();
dragLinearLayout.setOnViewSwapListener(new DragLinearLayout.OnViewSwapListener() {
@ -96,7 +97,7 @@ public class Watchlist extends Fragment {
editModeEnabled = false;
watchlistManager = new WatchlistManager(getContext());
watchlistManager = new WatchlistManager(getActivity().getBaseContext());
updateWatchlist(true);
@ -118,35 +119,59 @@ public class Watchlist extends Fragment {
private void updateTickerList()
{
AsyncTask<Void, Integer, Void> updater = new AsyncTask<Void, Integer, Void>() {
@Override
protected Void doInBackground(Void... voids) {
if(!currencyTickerList.isUpToDate())
{
currencyTickerList.updateListing(new BalanceManager.IconCallBack() {
@Override
public void onSuccess() {
tickerUpdated = true;
checkUpdatedData();
}
});
}
else
{
tickerUpdated = true;
checkUpdatedData();
}
ListingUpdater listingUpdater = new ListingUpdater();
listingUpdater.execute();
}
return null;
private class ListingUpdater extends AsyncTask<Void, Integer, Void> implements CoinmarketcapNotifierInterface {
@Override
protected Void doInBackground(Void... voids) {
coinmarketCapAPIManager.addListener(this);
if(!coinmarketCapAPIManager.isUpToDate())
{
coinmarketCapAPIManager.updateListing();
}
};
else
{
tickerUpdated = true;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
checkUpdatedData();
}
});
}
return null;
}
updater.execute();
@Override
public void onCurrenciesRetrieved(List<Currency> currencyList) {
}
@Override
public void onTopCurrenciesUpdated() {
}
@Override
public void onMarketCapUpdated() {
}
@Override
public void onListingUpdated() {
tickerUpdated = true;
checkUpdatedData();
}
}
private void disableEdition()
{
editButton.setBackground(MoodlBox.getDrawable(R.drawable.check_to_edit, getContext()));
editButton.setBackground(MoodlBox.getDrawable(R.drawable.check_to_edit, getActivity().getBaseContext()));
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
@ -171,7 +196,7 @@ public class Watchlist extends Fragment {
private void enableEdition()
{
editButton.setBackground(MoodlBox.getDrawable(R.drawable.edit_to_check, getContext()));
editButton.setBackground(MoodlBox.getDrawable(R.drawable.edit_to_check, getActivity().getBaseContext()));
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
@ -284,15 +309,9 @@ public class Watchlist extends Fragment {
protected Void doInBackground(Void... voids) {
watchlistManager.updateWatchlist();
if(!currencyDetailsList.isUpToDate())
if(!cryptocompareApiManager.isDetailsUpToDate())
{
currencyDetailsList.update(new BalanceManager.IconCallBack() {
@Override
public void onSuccess() {
detailsUpdated = true;
checkUpdatedData();
}
});
cryptocompareApiManager.updateDetails();
}
else
{
@ -338,7 +357,7 @@ public class Watchlist extends Fragment {
for(Currency currency : watchlistManager.getWatchlist())
{
View addedView = new CurrencyCardview(getContext(), currency, getActivity());
View addedView = new CurrencyCardview(getActivity().getBaseContext(), currency, getActivity());
dragLinearLayout.addDragView(addedView, addedView.findViewById(R.id.dragCardWatchlist));
}
@ -361,35 +380,17 @@ public class Watchlist extends Fragment {
}
}
private String getIconUrl(String symbol)
{
String url;
try {
JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol));
url = "https://www.cryptocompare.com" + jsonObject.getString("ImageUrl") + "?width=50";
} catch (NullPointerException e) {
Log.d(getContext().getResources().getString(R.string.debug), symbol + " has no icon URL");
url = null;
} catch (JSONException e) {
Log.d(getContext().getResources().getString(R.string.debug), "Url parsing error for " + symbol);
url = null;
}
return url;
}
private void updateChartColor(Currency currency)
{
if(currency.getIcon() != null)
{
Palette.Builder builder = Palette.from(currency.getIcon());
currency.setChartColor(builder.generate().getDominantColor(getColor(R.color.default_color, getContext())));
currency.setChartColor(builder.generate().getDominantColor(getColor(R.color.default_color, getActivity().getBaseContext())));
}
else
{
currency.setChartColor(getColor(R.color.default_color, getContext()));
currency.setChartColor(getColor(R.color.default_color, getActivity().getBaseContext()));
}
}
@ -398,7 +399,7 @@ public class Watchlist extends Fragment {
int id = 0;
try {
JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol));
JSONObject jsonObject = new JSONObject(cryptocompareApiManager.getCoinInfosHashmap().get(symbol));
id = jsonObject.getInt("Id");
} catch (JSONException e) {
e.printStackTrace();
@ -407,6 +408,17 @@ public class Watchlist extends Fragment {
return id;
}
@Override
public void onDetailsUpdated() {
detailsUpdated = true;
checkUpdatedData();
}
@Override
public void onExchangesUpdated() {
}
private class WatchlistUpdater extends AsyncTask<Void, Integer, Void>
{
@Override
@ -419,22 +431,32 @@ public class Watchlist extends Fragment {
protected Void doInBackground(Void... voids) {
for(final Currency currency : watchlistManager.getWatchlist())
{
currency.setTickerId(currencyTickerList.getTickerIdForSymbol(currency.getSymbol()));
currency.setTickerId(coinmarketCapAPIManager.getTickerIdForSymbol(currency.getSymbol()));
currency.setId(getCurrencyId(currency.getSymbol()));
currency.updatePrice(getActivity(), preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
currency.updatePrice(getActivity(), preferencesManager.getDefaultCurrency(), new CurrencyInfoUpdateNotifierInterface() {
@Override
public void onSuccess(final Currency sucessCurrency) {
public void onTimestampPriceUpdated(String price) {
String iconUrl = MoodlBox.getIconUrl(sucessCurrency.getSymbol(), currencyDetailsList);
}
@Override
public void onHistoryDataUpdated() {
}
@Override
public void onPriceUpdated(Currency successCurrency) {
String iconUrl = MoodlBox.getIconUrl(currency.getSymbol(), cryptocompareApiManager);
if(iconUrl != null)
{
MoodlBox.getBitmapFromURL(iconUrl, sucessCurrency.getSymbol(), getResources(), getContext(), new HomeActivity.IconCallBack() {
MoodlBox.getBitmapFromURL(iconUrl, currency.getSymbol(), getResources(), getActivity().getBaseContext(), new MoodlboxNotifierInterface() {
@Override
public void onSuccess(Bitmap bitmapIcon) {
sucessCurrency.setIcon(bitmapIcon);
public void onBitmapDownloaded(Bitmap bitmapIcon) {
currency.setIcon(bitmapIcon);
updateChartColor(currency);
countWatchlist();
}
});
}
@ -443,7 +465,7 @@ public class Watchlist extends Fragment {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_moodl);
icon = Bitmap.createScaledBitmap(icon, 50, 50, false);
sucessCurrency.setIcon(icon);
currency.setIcon(icon);
updateChartColor(currency);
countWatchlist();
}

View File

@ -1,173 +1,684 @@
package com.herbron.moodl.Activities;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import com.herbron.moodl.Activities.RecordTransactionFragments.BuyFragment;
import com.herbron.moodl.Activities.RecordTransactionFragments.SellFragment;
import com.herbron.moodl.CurrencyInfoUpdateNotifierInterface;
import com.herbron.moodl.CustomAdapters.PairRecordListAdapter;
import com.herbron.moodl.CustomLayouts.CustomRecordFragment;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.Transaction;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.InfoAPIManagers.Pair;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.DataNotifiers.CryptocompareNotifierInterface;
import com.herbron.moodl.CustomAdapters.CoinRecordListAdapter;
import com.herbron.moodl.CustomLayouts.CustomTabLayout;
import com.herbron.moodl.CustomAdapters.ExchangeRecordListAdapter;
import com.herbron.moodl.CustomAdapters.RecordTransactionPageAdapter;
import com.herbron.moodl.MoodlBox;
import com.herbron.moodl.DataNotifiers.MoodlboxNotifierInterface;
import com.herbron.moodl.PlaceholderManager;
import com.herbron.moodl.R;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class RecordTransactionActivity extends AppCompatActivity {
public class RecordTransactionActivity extends AppCompatActivity implements CurrencyInfoUpdateNotifierInterface, CryptocompareNotifierInterface {
private Toolbar toolbar;
private ImageView currencyIconImageView;
private String coin;
private String symbol;
private TextView symbolTxtView;
private TextInputLayout purchasedDateLayout;
private EditText purchaseDate;
private TextView feesTxtView;
private EditText amountTxtView;
private Button buyButton;
private Button sellButton;
private Button transferButton;
private DatabaseManager databaseManager;
private Calendar calendar;
private SimpleDateFormat sdf;
private PreferencesManager preferenceManager;
private EditText purchasedPriceEditText;
private Currency currency;
private int transactionId;
private Exchange exchange;
private Pair pair;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_record_action, menu);
return true;
}
private CryptocompareApiManager cryptocompareApiManager;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_record:
private AutoCompleteTextView coin_autoCompleteTextView;
private AutoCompleteTextView exchange_autoCompleteTextView;
private AutoCompleteTextView pair_autoCompleteTextView;
if(checkAmountText() && checkPriceText())
{
double amount = Double.parseDouble(amountTxtView.getText().toString());
double purchasedPrice = Double.parseDouble(purchasedPriceEditText.getText().toString());
double fees = Double.parseDouble(feesTxtView.getText().toString());
private CustomTabLayout tabLayout;
private ViewPager viewPager;
if(!sellButton.isEnabled())
{
amount *= -1;
}
private RecordTransactionPageAdapter pageAdapter;
if(transactionId != -1)
{
databaseManager.updateTransactionWithId(transactionId, amount, calendar.getTime(), purchasedPrice, fees);
}
else
{
databaseManager.addCurrencyToManualCurrency(symbol, amount, calendar.getTime(), purchasedPrice, fees);
}
private Animation revealAnimation;
private Animation dismissAnimation;
private LinearLayout globalTabLayouts;
private boolean isGlobalLayoutVisible;
private Intent callingIntent;
private TextWatcher coinTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
preferenceManager.setMustUpdateSummary(true);
Intent intent = new Intent(RecordTransactionActivity.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
break;
case android.R.id.home:
//NavUtils.navigateUpFromSameTask(this);
finish();
break;
default:
break;
}
return true;
}
private boolean checkPriceText()
{
String purchasedPriceText = purchasedPriceEditText.getText().toString();
double purchasedPrice;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
currencyIconImageView.setImageBitmap(null);
exchange_autoCompleteTextView.setEnabled(false);
exchange_autoCompleteTextView.setText("");
try {
purchasedPrice = Double.parseDouble(purchasedPriceText);
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(2).setEnabled(false);
((TextView) tabLayout.getTabAt(2).getCustomView()).setTextColor(getResources().getColor(R.color.separationColor));
if(purchasedPrice < 0)
if(isGlobalLayoutVisible && globalTabLayouts.getAnimation().hasEnded())
{
purchasedPriceEditText.setError(getResources().getString(R.string.field_negative));
globalTabLayouts.startAnimation(dismissAnimation);
}
} catch (NumberFormatException e) {
purchasedPriceEditText.setError(getResources().getString(R.string.field_nan));
return false;
}
if(purchasedPriceText.equals(""))
{
purchasedPriceEditText.setError(getResources().getString(R.string.field_empty));
@Override
public void afterTextChanged(Editable s) {
return false;
}
return true;
}
private boolean checkAmountText()
{
String amountText = amountTxtView.getText().toString();
try {
Double.parseDouble(amountText);
} catch (NumberFormatException e) {
amountTxtView.setError(getResources().getString(R.string.field_nan));
return false;
}
if(amountText.equals(""))
{
amountTxtView.setError(getResources().getString(R.string.field_empty));
return false;
}
return true;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_transaction);
Intent intent = getIntent();
toolbar = findViewById(R.id.toolbar);
sdf = new SimpleDateFormat(" HH:mm dd/MM/yyyy", Locale.UK);
currencyIconImageView = findViewById(R.id.currencyIconImageView);
cryptocompareApiManager = CryptocompareApiManager.getInstance(this);
calendar = Calendar.getInstance();
cryptocompareApiManager.addListener(this);
databaseManager = new DatabaseManager(this);
preferenceManager = new PreferencesManager(this);
cryptocompareApiManager.updateExchangeList();
initializeViewElements();
coin_autoCompleteTextView = findViewById(R.id.coin_autoCompleteTextView);
exchange_autoCompleteTextView = findViewById(R.id.exchange_autoCompleteTextView);
pair_autoCompleteTextView = findViewById(R.id.pair_autoCompleteTextView);
coin = intent.getStringExtra("coin");
symbol = intent.getStringExtra("symbol");
setSupportActionBar(toolbar);
transactionId = intent.getIntExtra("transactionId", -1);
setupTabLayout();
setupCoinAutoCompleteTextView();
setupExchangeAutoCompleteTextView();
setupPairAutoCompleteTextView();
setupBackButton();
}
@Override
protected void onStop() {
super.onStop();
if(callingIntent != null)
{
callingIntent.removeExtra("transactionId");
}
}
private void checkCallingIntent()
{
callingIntent = getIntent();
int transactionId = callingIntent.getIntExtra("transactionId", -1);
if(transactionId != -1)
{
List<Exchange> exchangeList;
List<Pair> pairList;
DatabaseManager databaseManager = new DatabaseManager(getBaseContext());
Transaction transaction = databaseManager.getCurrencyTransactionById(transactionId);
List<Currency> denominationList = cryptocompareApiManager.getCurrenciesDenomination();
boolean found = false;
int index = 0;
while(index < denominationList.size() && !found)
{
if(denominationList.get(index).getSymbol().equals(transaction.getSymbol()))
{
currency = denominationList.get(index);
found = true;
currency.setListener(RecordTransactionActivity.this);
updateExchangeAdapter(currency.getSymbol());
exchange_autoCompleteTextView.setEnabled(true);
IconDownloaderTask iconDownloaderTask = new IconDownloaderTask();
iconDownloaderTask.execute();
coin_autoCompleteTextView.removeTextChangedListener(coinTextWatcher);
coin_autoCompleteTextView.setText(PlaceholderManager.getDenomination(currency.getName(), currency.getSymbol(), getBaseContext()));
coin_autoCompleteTextView.setEnabled(false);
if(globalTabLayouts.getVisibility() == View.GONE)
{
globalTabLayouts.setVisibility(View.VISIBLE);
}
globalTabLayouts.startAnimation(revealAnimation);
isGlobalLayoutVisible = true;
updateCurrencyData();
}
index++;
}
found = false;
index = 0;
switch (transaction.getType())
{
case "b":
exchangeList = cryptocompareApiManager.getExchangeList(currency.getSymbol());
while(index < exchangeList.size() && !found)
{
if(exchangeList.get(index).getName().equals(transaction.getSource()))
{
exchange = exchangeList.get(index);
exchange_autoCompleteTextView.setText(exchange.getName());
exchange_autoCompleteTextView.setEnabled(true);
updateExchangeData();
updatePairAdapter();
found = true;
}
index++;
}
pairList = exchange.getPairsFor(currency.getSymbol());
found = false;
index = 0;
while(index < pairList.size() && !found)
{
if(pairList.get(index).contains(currency.getSymbol()) && pairList.get(index).contains(transaction.getSymPair()))
{
pair = pairList.get(index);
pair_autoCompleteTextView.setText(PlaceholderManager.getPairString(pair.getFrom(), pair.getTo(), getBaseContext()));
pair_autoCompleteTextView.setEnabled(true);
((BuyFragment) pageAdapter.getItem(0)).updatePair(pair);
updatePairData();
found = true;
}
index++;
}
tabLayout.getTabAt(0).select();
break;
case "s":
exchangeList = cryptocompareApiManager.getExchangeList(currency.getSymbol());
while(index < exchangeList.size() && !found)
{
if(exchangeList.get(index).getName().equals(transaction.getSource()))
{
exchange = exchangeList.get(index);
exchange_autoCompleteTextView.setText(exchange.getName());
exchange_autoCompleteTextView.setEnabled(true);
updateExchangeData();
updatePairAdapter();
found = true;
}
index++;
}
pairList = exchange.getPairsFor(currency.getSymbol());
found = false;
index = 0;
while(index < pairList.size() && !found)
{
if(pairList.get(index).contains(currency.getSymbol()) && pairList.get(index).contains(transaction.getSymPair()))
{
pair = pairList.get(index);
pair_autoCompleteTextView.setText(PlaceholderManager.getPairString(pair.getFrom(), pair.getTo(), getBaseContext()));
pair_autoCompleteTextView.setEnabled(true);
((SellFragment) pageAdapter.getItem(1)).updatePair(pair);
updatePairData();
found = true;
}
index++;
}
tabLayout.getTabAt(1).select();
break;
case "t":
tabLayout.getTabAt(2).select();
break;
}
}
}
public Currency getCurrency()
{
return currency;
}
private void setupTabLayout()
{
globalTabLayouts = findViewById(R.id.globalTabLayouts);
tabLayout = findViewById(R.id.transactionsTabLayout);
tabLayout.addTab(0, getResources().getString(R.string.buyText));
tabLayout.addTab(1, getResources().getString(R.string.sellText));
tabLayout.addTab(2, getResources().getString(R.string.transferText));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = findViewById(R.id.transactionsViewPager);
pageAdapter = new RecordTransactionPageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pageAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
LinearLayout tabLayoutChildren = (LinearLayout) tabLayout.getChildAt(0);
for(int i = 0; i < tabLayoutChildren.getChildCount(); i++)
{
tabLayoutChildren.getChildAt(i).setEnabled(false);
((TextView) tabLayout.getTabAt(i).getCustomView()).setTextColor(getResources().getColor(R.color.separationColor));
}
revealAnimation = AnimationUtils.loadAnimation(this, R.anim.reveal);
dismissAnimation = AnimationUtils.loadAnimation(this, R.anim.dismiss);
dismissAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
isGlobalLayoutVisible = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
private void setupPairAutoCompleteTextView()
{
pair_autoCompleteTextView.setThreshold(0);
pair_autoCompleteTextView.setTextColor(getResources().getColor(R.color.white));
pair_autoCompleteTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(0).setEnabled(false);
((TextView) tabLayout.getTabAt(0).getCustomView()).setTextColor(getResources().getColor(R.color.separationColor));
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(1).setEnabled(false);
((TextView) tabLayout.getTabAt(1).getCustomView()).setTextColor(getResources().getColor(R.color.separationColor));
tabLayout.getTabAt(2).select();
}
@Override
public void afterTextChanged(Editable s) {
}
});
pair_autoCompleteTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pair_autoCompleteTextView.showDropDown();
}
});
pair_autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
{
pair_autoCompleteTextView.showDropDown();
}
else
{
pair_autoCompleteTextView.dismissDropDown();
}
}
});
pair_autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pair = (Pair) pair_autoCompleteTextView.getAdapter().getItem(position);
pair_autoCompleteTextView.setText(PlaceholderManager.getPairString(pair.getFrom(), pair.getTo(), getBaseContext()));
toolbar.requestFocus();
hideSoftKeyboard(RecordTransactionActivity.this);
updatePairData();
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(0).setEnabled(true);
((TextView) tabLayout.getTabAt(0).getCustomView()).setTextColor(getResources().getColor(R.color.white));
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(1).setEnabled(true);
((TextView) tabLayout.getTabAt(1).getCustomView()).setTextColor(getResources().getColor(R.color.white));
tabLayout.getTabAt(0).select();
}
});
}
private void setupExchangeAutoCompleteTextView()
{
exchange_autoCompleteTextView.setThreshold(0);
exchange_autoCompleteTextView.setTextColor(getResources().getColor(R.color.white));
exchange_autoCompleteTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
pair_autoCompleteTextView.setEnabled(false);
pair_autoCompleteTextView.setText("");
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(0).setEnabled(false);
((TextView) tabLayout.getTabAt(0).getCustomView()).setTextColor(getResources().getColor(R.color.separationColor));
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(1).setEnabled(false);
((TextView) tabLayout.getTabAt(1).getCustomView()).setTextColor(getResources().getColor(R.color.separationColor));
tabLayout.getTabAt(2).select();
}
@Override
public void afterTextChanged(Editable s) {
}
});
exchange_autoCompleteTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
exchange_autoCompleteTextView.showDropDown();
}
});
exchange_autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
{
exchange_autoCompleteTextView.showDropDown();
}
else
{
exchange_autoCompleteTextView.dismissDropDown();
}
}
});
exchange_autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
exchange = (Exchange) exchange_autoCompleteTextView.getAdapter().getItem(position);
exchange_autoCompleteTextView.setText(exchange.getName());
toolbar.requestFocus();
hideSoftKeyboard(RecordTransactionActivity.this);
updatePairAdapter();
pair_autoCompleteTextView.setEnabled(true);
updateExchangeData();
}
});
}
private void updatePairAdapter()
{
PairRecordListAdapter pairAdapter = new PairRecordListAdapter(this, android.R.layout.simple_list_item_1, new ArrayList<>(exchange.getPairsFor(currency.getSymbol())));
pair_autoCompleteTextView.setAdapter(pairAdapter);
}
private void updateExchangeAdapter(String symbol)
{
ExchangeRecordListAdapter exchangeAdapter = new ExchangeRecordListAdapter(this, android.R.layout.simple_list_item_1, new ArrayList<>(cryptocompareApiManager.getExchangeList(symbol)));
exchange_autoCompleteTextView.setAdapter(exchangeAdapter);
}
private void setupCoinAutoCompleteTextView()
{
CoinRecordListAdapter adapter = new CoinRecordListAdapter(getBaseContext(), R.layout.custom_summary_coin_row, new ArrayList<>(cryptocompareApiManager.getCurrenciesDenomination()));
coin_autoCompleteTextView.setThreshold(0);
coin_autoCompleteTextView.setAdapter(adapter);
coin_autoCompleteTextView.setTextColor(getResources().getColor(R.color.white));
coin_autoCompleteTextView.addTextChangedListener(coinTextWatcher);
coin_autoCompleteTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
coin_autoCompleteTextView.showDropDown();
}
});
coin_autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
{
coin_autoCompleteTextView.showDropDown();
}
else
{
coin_autoCompleteTextView.dismissDropDown();
}
}
});
coin_autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currency = (Currency) coin_autoCompleteTextView.getAdapter().getItem(position);
coin_autoCompleteTextView.setText(PlaceholderManager.getDenomination(currency.getName(), currency.getSymbol(), getBaseContext()));
toolbar.requestFocus();
hideSoftKeyboard(RecordTransactionActivity.this);
currency.setListener(RecordTransactionActivity.this);
updateExchangeAdapter(currency.getSymbol());
exchange_autoCompleteTextView.setEnabled(true);
IconDownloaderTask iconDownloaderTask = new IconDownloaderTask();
iconDownloaderTask.execute();
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(0).setEnabled(false);
((TextView) tabLayout.getTabAt(0).getCustomView()).setTextColor(getResources().getColor(R.color.separationColor));
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(1).setEnabled(false);
((TextView) tabLayout.getTabAt(1).getCustomView()).setTextColor(getResources().getColor(R.color.separationColor));
((LinearLayout) tabLayout.getChildAt(0)).getChildAt(2).setEnabled(true);
((TextView) tabLayout.getTabAt(2).getCustomView()).setTextColor(getResources().getColor(R.color.white));
tabLayout.getTabAt(2).select();
updateCurrencyData();
if(globalTabLayouts.getVisibility() == View.GONE)
{
globalTabLayouts.setVisibility(View.VISIBLE);
}
globalTabLayouts.startAnimation(revealAnimation);
isGlobalLayoutVisible = true;
}
});
}
private void updateCurrencyData()
{
for(int i = 0; i < pageAdapter.getCount(); i++)
{
((CustomRecordFragment) pageAdapter.getItem(i)).setCurrency(currency);
}
}
private void updateExchangeData()
{
for(int i = 0; i < pageAdapter.getCount(); i++)
{
((CustomRecordFragment) pageAdapter.getItem(i)).setExchange(exchange);
}
}
private void updatePairData()
{
for(int i = 0; i < pageAdapter.getCount(); i++)
{
((CustomRecordFragment) pageAdapter.getItem(i)).setPair(pair);
}
}
@Override
public void onTimestampPriceUpdated(String price) {
//purchasedPriceEditText.setText(price);
}
@Override
public void onHistoryDataUpdated() {
}
@Override
public void onPriceUpdated(Currency currency) {
}
@Override
public void onDetailsUpdated() {
}
@Override
public void onExchangesUpdated() {
checkCallingIntent();
}
private class IconDownloaderTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
String iconUrl = MoodlBox.getIconUrl(currency.getSymbol(), 500, cryptocompareApiManager);
if(iconUrl != null)
{
MoodlBox.getBitmapFromURL(iconUrl, currency.getSymbol(), getResources(), getBaseContext(), new MoodlboxNotifierInterface() {
@Override
public void onBitmapDownloaded(Bitmap bitmapIcon) {
runOnUiThread(new Runnable() {
@Override
public void run() {
currencyIconImageView.setImageBitmap(bitmapIcon);
}
});
}
});
}
else
{
runOnUiThread(new Runnable() {
@Override
public void run() {
currencyIconImageView.setBackground(getResources().getDrawable(R.mipmap.ic_launcher_moodl));
}
});
}
return null;
}
}
/*if(transactionId != -1)
{
setTitle(PlaceholderManager.getEditTransactionString(coin, getBaseContext()));
@ -206,106 +717,31 @@ public class RecordTransactionActivity extends AppCompatActivity {
}
});
initializeButtons();
//initializeButtons();
currency.getTimestampPrice(this, preferenceManager.getDefaultCurrency(), new Currency.PriceCallBack() {
@Override
public void onSuccess(String price) {
purchasedPriceEditText.setText(price);
}
}, calendar.getTimeInMillis() / 1000);
}, calendar.getTimeInMillis() / 1000);*/
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
private void initializeButtons()
private void setupBackButton()
{
buyButton.setOnClickListener(new View.OnClickListener() {
ImageButton backButton = findViewById(R.id.back_button);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buyButton.setEnabled(false);
sellButton.setEnabled(true);
transferButton.setEnabled(true);
findViewById(R.id.input_purchase_price).setVisibility(View.VISIBLE);
findViewById(R.id.input_fees).setVisibility(View.GONE);
public void onClick(View v) {
finish();
}
});
sellButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buyButton.setEnabled(true);
sellButton.setEnabled(false);
transferButton.setEnabled(true);
findViewById(R.id.input_purchase_price).setVisibility(View.GONE);
findViewById(R.id.input_fees).setVisibility(View.VISIBLE);
}
});
transferButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buyButton.setEnabled(true);
sellButton.setEnabled(true);
transferButton.setEnabled(false);
// Prepare transfer interface
}
});
}
private void initializeViewElements()
{
symbolTxtView = findViewById(R.id.currencySymbol);
amountTxtView = findViewById(R.id.currencyAmount);
feesTxtView = findViewById(R.id.feesTextView);
purchasedDateLayout = findViewById(R.id.input_purchase_date);
purchaseDate = findViewById(R.id.purchaseDate);
purchasedPriceEditText = findViewById(R.id.purchasePrice);
buyButton = findViewById(R.id.buyButton);
sellButton = findViewById(R.id.sellButton);
transferButton = findViewById(R.id.transfertButton);
}
private void createDatePicker()
{
new android.app.DatePickerDialog(
RecordTransactionActivity.this,
new android.app.DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
purchaseDate.setText(sdf.format(calendar.getTime()));
createTimePicker();
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
).show();
}
private void createTimePicker()
{
new android.app.TimePickerDialog(
RecordTransactionActivity.this,
new android.app.TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
purchaseDate.setText(sdf.format(calendar.getTime()));
currency.getTimestampPrice(RecordTransactionActivity.this, preferenceManager.getDefaultCurrency(), new Currency.PriceCallBack() {
@Override
public void onSuccess(String price) {
purchasedPriceEditText.setText(price);
}
}, calendar.getTimeInMillis() / 1000);
}
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
true
).show();
}
}

View File

@ -0,0 +1,558 @@
package com.herbron.moodl.Activities.RecordTransactionFragments;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.AppCompatButton;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TimePicker;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.CustomLayouts.CustomRecordFragment;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.Transaction;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.DataManagers.InfoAPIManagers.Pair;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.PlaceholderManager;
import com.herbron.moodl.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class BuyFragment extends CustomRecordFragment {
private TextInputEditText amoutEditText;
private TextInputEditText buyPriceEditText;
private TextInputEditText buyDateEditText;
private TextInputEditText totalValueEditText;
private TextInputEditText fees_editText;
private TextInputEditText note_editText;
private AppCompatButton saveBuyButton;
private static Spinner feesCurrencySpinner;
private static View view;
private Switch deductHoldingsSwitch;
private ArrayAdapter<String> currencyFeeAdapter;
private SimpleDateFormat sdf;
private Calendar calendar;
private PreferencesManager preferenceManager;
private static Context context;
private static Currency fragmentCurrency;
private static Exchange fragmentExchange;
private static Pair fragmentPair;
private List<String> symbolStrings;
private int transactionId;
private Transaction transaction;
private boolean isAmountLastUpdated;
private TextWatcher amountTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
totalValueEditText.removeTextChangedListener(totalValueTextWatcher);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(isFieldCorrectlyFilled(buyPriceEditText, false) && isFieldCorrectlyFilled(amoutEditText, false))
{
if(Double.parseDouble(amoutEditText.getText().toString()) > 0)
{
Double totalValue = Double.parseDouble(buyPriceEditText.getText().toString()) * Double.parseDouble(s.toString());
totalValueEditText.setText(String.format("%f", totalValue));
}
else
{
totalValueEditText.setText("0");
}
}
else
{
totalValueEditText.setText("");
}
}
@Override
public void afterTextChanged(Editable s) {
totalValueEditText.addTextChangedListener(totalValueTextWatcher);
isAmountLastUpdated = true;
}
};
private TextWatcher totalValueTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
amoutEditText.removeTextChangedListener(amountTextWatcher);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(isFieldCorrectlyFilled(buyPriceEditText, false) && isFieldCorrectlyFilled(totalValueEditText, false))
{
if(Double.parseDouble(totalValueEditText.getText().toString()) > 0)
{
Double amount = Double.parseDouble(s.toString()) / Double.parseDouble(buyPriceEditText.getText().toString());
amoutEditText.setText(String.format("%f", amount));
}
else
{
amoutEditText.setText("0");
}
}
else
{
amoutEditText.setText("");
}
}
@Override
public void afterTextChanged(Editable s) {
amoutEditText.addTextChangedListener(amountTextWatcher);
isAmountLastUpdated = false;
}
};
private TextWatcher feesTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
totalValueEditText.removeTextChangedListener(totalValueTextWatcher);
amoutEditText.removeTextChangedListener(amountTextWatcher);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if((isFieldCorrectlyFilled(amoutEditText, false) || isFieldCorrectlyFilled(totalValueEditText, false)) && isFieldCorrectlyFilled(buyPriceEditText, false))
{
double amount = Double.parseDouble(amoutEditText.getText().toString());
double purchasePrice = Double.parseDouble(buyPriceEditText.getText().toString());
double fees;
double totalValue = Double.parseDouble(totalValueEditText.getText().toString());
String feeCurrency;
if(isAmountLastUpdated)
{
totalValue = amount * purchasePrice;
}
else
{
amount = totalValue / purchasePrice;
}
if(fees_editText.getText().toString().equals("0") || (start == 0 && before == 1 && count == 0))
{
if(isAmountLastUpdated)
{
totalValueEditText.setText(String.valueOf(amount * purchasePrice));
}
else
{
amoutEditText.setText(String.valueOf(totalValue / purchasePrice));
}
}
else
{
if(feesCurrencySpinner.getSelectedItemPosition() < 2)
{
feeCurrency = fragmentPair.getFrom();
}
else
{
feeCurrency = fragmentPair.getTo();
}
fees = getFees(feeCurrency, amount, purchasePrice);
if(feesCurrencySpinner.getSelectedItemPosition() % 2 == 0)
{
if(isAmountLastUpdated)
{
totalValueEditText.setText(String.valueOf(totalValue + fees));
}
else
{
amoutEditText.setText(String.valueOf(amount - (fees / purchasePrice)));
}
}
else
{
if(fragmentCurrency.getSymbol().equals(feeCurrency))
{
if(isAmountLastUpdated)
{
totalValueEditText.setText(String.valueOf(totalValue + (fees * purchasePrice)));
}
else
{
amoutEditText.setText(String.valueOf((totalValue / purchasePrice) - fees));
}
}
else
{
if(isAmountLastUpdated)
{
totalValueEditText.setText(String.valueOf(totalValue + fees));
}
else
{
amoutEditText.setText(String.valueOf((totalValue - fees) / purchasePrice));
}
}
}
}
}
}
@Override
public void afterTextChanged(Editable s) {
totalValueEditText.addTextChangedListener(totalValueTextWatcher);
amoutEditText.addTextChangedListener(amountTextWatcher);
}
};
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.record_transaction_fragment_buy, container, false);
context = getActivity().getApplicationContext();
calendar = Calendar.getInstance();
sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy", Locale.UK);
preferenceManager = new PreferencesManager(getContext());
initializeViewElements();
return view;
}
private void checkCallingIntent()
{
Intent intent = getActivity().getIntent();
transactionId = intent.getIntExtra("transactionId", -1);
if(transactionId != -1)
{
DatabaseManager databaseManager = new DatabaseManager(context);
transaction = databaseManager.getCurrencyTransactionById(transactionId);
if(transaction.getType() == null || transaction.getType().equals("b"))
{
fillFields();
}
}
}
private void fillFields()
{
amoutEditText.setText(String.valueOf(transaction.getAmount()));
buyPriceEditText.setText(String.valueOf(transaction.getPrice()));
calendar.setTimeInMillis(transaction.getTimestamp());
buyDateEditText.setText(sdf.format(calendar.getTime()));
totalValueEditText.setText(String.valueOf(transaction.getAmount() * transaction.getPrice()));
fees_editText.setText(String.valueOf(transaction.getFees()));
note_editText.setText(transaction.getNote());
}
private void initializeViewElements()
{
totalValueEditText = view.findViewById(R.id.totalValue_editText_buy);
amoutEditText = view.findViewById(R.id.amount_editText_buy);
buyPriceEditText = view.findViewById(R.id.buyPrice_editText);
buyDateEditText = view.findViewById(R.id.buyDate_editText);
buyDateEditText.setText(sdf.format(calendar.getTime()));
buyDateEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createDatePicker();
}
});
feesCurrencySpinner = view.findViewById(R.id.feesCurrency_editText_buy);
currencyFeeAdapter = new ArrayAdapter<String>(getSecureContext(), android.R.layout.simple_spinner_item, new ArrayList<>());
currencyFeeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
feesCurrencySpinner.setAdapter(currencyFeeAdapter);
deductHoldingsSwitch = view.findViewById(R.id.deductHoldingsBuy);
if(fragmentPair != null)
{
updateAdapter();
}
saveBuyButton = view.findViewById(R.id.saveBuyButton);
saveBuyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isFieldCorrectlyFilled(amoutEditText, true) && isFieldCorrectlyFilled(buyPriceEditText, true) && isFieldCorrectlyFilled(totalValueEditText, true))
{
double amount = Double.parseDouble(amoutEditText.getText().toString());
double purchasePrice = Double.parseDouble(buyPriceEditText.getText().toString());
double fees;
String feeCurrency;
if(feesCurrencySpinner.getSelectedItemPosition() < 1)
{
feeCurrency = fragmentPair.getFrom();
}
else
{
feeCurrency = fragmentPair.getTo();
}
fees = getFees(feeCurrency, amount, purchasePrice);
String note = note_editText.getText().toString();
DatabaseManager databaseManager = new DatabaseManager(getContext());
preferenceManager.setMustUpdateSummary(true);
if(transactionId == -1)
{
databaseManager.addTransaction(fragmentCurrency.getSymbol()
, amount
, calendar.getTime()
, purchasePrice
, fees
, note
, fragmentPair.getFrom().equals(fragmentCurrency.getSymbol()) ? fragmentPair.getTo() : fragmentPair.getFrom()
, feeCurrency
, ""
, fragmentExchange.getName()
, "b"
, feesCurrencySpinner.getSelectedItemPosition() % 2 == 0 ? "p" : "f"
, deductHoldingsSwitch.isChecked());
Intent intent = new Intent(getActivity(), HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
else
{
databaseManager.updateTransactionWithId(transactionId
, amount
, calendar.getTime()
, purchasePrice
, fees
, note
, fragmentPair.getFrom().equals(fragmentCurrency.getSymbol()) ? fragmentPair.getTo() : fragmentPair.getFrom()
, feeCurrency
, ""
, fragmentExchange.getName()
,"b"
, feesCurrencySpinner.getSelectedItemPosition() % 2 == 0 ? "p" : "f"
, deductHoldingsSwitch.isChecked());
}
getActivity().finish();
}
}
});
fees_editText = view.findViewById(R.id.fees_editText_buy);
note_editText = view.findViewById(R.id.note_editText_buy);
checkCallingIntent();
setupTextWatchers();
}
private void setupTextWatchers()
{
totalValueEditText.addTextChangedListener(totalValueTextWatcher);
amoutEditText.addTextChangedListener(amountTextWatcher);
fees_editText.addTextChangedListener(feesTextWatcher);
}
private double getFees(String feeCurrency, double amount, double purchasedPrice)
{
double fees = 0;
if(!fees_editText.getText().toString().equals(""))
{
fees = Double.parseDouble(fees_editText.getText().toString());
if(feesCurrencySpinner.getSelectedItemPosition() % 2 == 0)
{
if(fragmentCurrency.getSymbol().equals(feeCurrency))
{
fees = (100 * amount) / (100 + fees);
}
else
{
double base = (100 * purchasedPrice * amount) / (100 + fees);
fees = purchasedPrice * amount - base;
}
}
}
return fees;
}
private boolean isFieldCorrectlyFilled(TextInputEditText editText, boolean displayError)
{
String purchasedPriceText = editText.getText().toString();
double purchasedPrice;
try {
purchasedPrice = Double.parseDouble(purchasedPriceText);
if(purchasedPrice < 0)
{
if(displayError) editText.setError(getResources().getString(R.string.field_negative));
return false;
}
} catch (NumberFormatException e) {
if(displayError) editText.setError(getResources().getString(R.string.field_nan));
return false;
}
if(purchasedPriceText.equals(""))
{
if(displayError) editText.setError(getResources().getString(R.string.field_empty));
return false;
}
return true;
}
private void updateAdapter()
{
symbolStrings = new ArrayList<>();
symbolStrings.addAll(PlaceholderManager.getFeeOptionsForSymbol(fragmentPair.getFrom(), getSecureContext()));
symbolStrings.addAll(PlaceholderManager.getFeeOptionsForSymbol(fragmentPair.getTo(), getSecureContext()));
currencyFeeAdapter.clear();
currencyFeeAdapter.addAll(symbolStrings);
currencyFeeAdapter.notifyDataSetChanged();
}
private void createDatePicker()
{
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(),
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
buyDateEditText.setText(sdf.format(calendar.getTime()));
createTimePicker();
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
datePickerDialog.show();
}
private void createTimePicker()
{
new android.app.TimePickerDialog(
getContext(),
new android.app.TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
buyDateEditText.setText(sdf.format(calendar.getTime()));
if(fragmentCurrency != null)
{
fragmentCurrency.getTimestampPrice(getContext(), fragmentCurrency.getSymbol().equals(fragmentPair.getFrom()) ? fragmentPair.getTo() : fragmentPair.getFrom(),calendar.getTimeInMillis() / 1000);
}
}
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
true
).show();
}
private static Context getSecureContext()
{
return context;
}
@Override
public void onCurrencyUpdated() {
fragmentCurrency = currency;
}
@Override
public void onExchangeUpdated() {
fragmentExchange = exchange;
}
public void updatePair(Pair pair)
{
currencyFeeAdapter = new ArrayAdapter<String>(getSecureContext(), android.R.layout.simple_spinner_item, new ArrayList<>());
currencyFeeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
feesCurrencySpinner.setAdapter(currencyFeeAdapter);
symbolStrings = new ArrayList<>();
symbolStrings.addAll(PlaceholderManager.getFeeOptionsForSymbol(pair.getFrom(), getSecureContext()));
symbolStrings.addAll(PlaceholderManager.getFeeOptionsForSymbol(pair.getTo(), getSecureContext()));
currencyFeeAdapter.addAll(symbolStrings);
currencyFeeAdapter.notifyDataSetChanged();
}
@Override
public void onPairUpdated() {
fragmentPair = pair;
fragmentCurrency.addOnTimestampPriceUpdatedListener(new Currency.OnTimestampPriceUpdatedListener() {
@Override
public void onTimeStampPriceUpdated(String price) {
((TextInputEditText) view.findViewById(R.id.buyPrice_editText)).setText(price);
updatePair(fragmentPair);
}
});
if(calendar == null)
{
calendar = Calendar.getInstance();
}
fragmentCurrency.getTimestampPrice(getSecureContext(), fragmentCurrency.getSymbol().equals(fragmentPair.getFrom()) ? fragmentPair.getTo() : fragmentPair.getFrom(), calendar.getTimeInMillis() / 1000);
}
}

View File

@ -0,0 +1,553 @@
package com.herbron.moodl.Activities.RecordTransactionFragments;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.AppCompatButton;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TimePicker;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.CustomLayouts.CustomRecordFragment;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.Transaction;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.DataManagers.InfoAPIManagers.Pair;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.PlaceholderManager;
import com.herbron.moodl.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class SellFragment extends CustomRecordFragment {
private TextInputEditText amoutEditText;
private TextInputEditText sellPriceEditText;
private TextInputEditText sellDateEditText;
private TextInputEditText totalValueEditText;
private TextInputEditText fees_editText;
private TextInputEditText note_editText;
private AppCompatButton saveSellButton;
private static Spinner feesCurrencySpinner;
private static View view;
private Switch deductHoldingsSwitch;
private ArrayAdapter<String> currencyFeeAdapter;
private SimpleDateFormat sdf;
private Calendar calendar;
private PreferencesManager preferenceManager;
private static Context context;
private static Currency fragmentCurrency;
private static Exchange fragmentExchange;
private static Pair fragmentPair;
private List<String> symbolStrings;
private int transactionId;
private Transaction transaction;
private boolean isAmountLastUpdated;
private TextWatcher amountTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
totalValueEditText.removeTextChangedListener(totalValueTextWatcher);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(isFieldCorrectlyFilled(sellPriceEditText, false) && isFieldCorrectlyFilled(amoutEditText, false))
{
if(Double.parseDouble(amoutEditText.getText().toString()) > 0)
{
Double totalValue = Double.parseDouble(sellPriceEditText.getText().toString()) * Double.parseDouble(s.toString());
totalValueEditText.setText(String.format("%f", totalValue));
}
else
{
totalValueEditText.setText("0");
}
}
else
{
totalValueEditText.setText("");
}
}
@Override
public void afterTextChanged(Editable s) {
totalValueEditText.addTextChangedListener(totalValueTextWatcher);
isAmountLastUpdated = true;
}
};
private TextWatcher totalValueTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
amoutEditText.removeTextChangedListener(amountTextWatcher);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(isFieldCorrectlyFilled(sellPriceEditText, false) && isFieldCorrectlyFilled(totalValueEditText, false))
{
if(Double.parseDouble(totalValueEditText.getText().toString()) > 0)
{
Double amount = Double.parseDouble(s.toString()) / Double.parseDouble(sellPriceEditText.getText().toString());
amoutEditText.setText(String.format("%f", amount));
}
else
{
amoutEditText.setText("0");
}
}
else
{
amoutEditText.setText("");
}
}
@Override
public void afterTextChanged(Editable s) {
amoutEditText.addTextChangedListener(amountTextWatcher);
isAmountLastUpdated = false;
}
};
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.record_transaction_fragment_sell, container, false);
context = getActivity().getApplicationContext();
calendar = Calendar.getInstance();
sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy", Locale.UK);
preferenceManager = new PreferencesManager(getContext());
initializeViewElements();
return view;
}
private void initializeViewElements()
{
totalValueEditText = view.findViewById(R.id.totalValue_editText_sell);
totalValueEditText.addTextChangedListener(totalValueTextWatcher);
amoutEditText = view.findViewById(R.id.amount_editText_sell);
amoutEditText.addTextChangedListener(amountTextWatcher);
sellPriceEditText = view.findViewById(R.id.sellPrice_editText);
sellDateEditText = view.findViewById(R.id.sellDate_editText);
sellDateEditText.setText(sdf.format(calendar.getTime()));
sellDateEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createDatePicker();
}
});
feesCurrencySpinner = view.findViewById(R.id.feesCurrency_editText_sell);
currencyFeeAdapter = new ArrayAdapter<String>(getSecureContext(), android.R.layout.simple_spinner_item, new ArrayList<>());
currencyFeeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
feesCurrencySpinner.setAdapter(currencyFeeAdapter);
if(fragmentPair != null)
{
updateAdapter();
}
deductHoldingsSwitch = view.findViewById(R.id.deductHoldingsSell);
saveSellButton = view.findViewById(R.id.saveSellButton);
saveSellButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isFieldCorrectlyFilled(amoutEditText, true) && isFieldCorrectlyFilled(sellPriceEditText, true) && isFieldCorrectlyFilled(totalValueEditText, true))
{
double amount = Double.parseDouble(amoutEditText.getText().toString());
double purchasePrice = Double.parseDouble(sellPriceEditText.getText().toString());
double fees;
String feeCurrency;
if(feesCurrencySpinner.getSelectedItemPosition() < 1)
{
feeCurrency = fragmentPair.getFrom();
}
else
{
feeCurrency = fragmentPair.getTo();
}
fees = getFees(feeCurrency, amount, purchasePrice);
String note = note_editText.getText().toString();
DatabaseManager databaseManager = new DatabaseManager(getContext());
preferenceManager.setMustUpdateSummary(true);
if(transactionId == -1)
{
databaseManager.addTransaction(fragmentCurrency.getSymbol()
, amount
, calendar.getTime()
, purchasePrice
, fees
, note
, fragmentPair.getFrom().equals(fragmentCurrency.getSymbol()) ? fragmentPair.getTo() : fragmentPair.getFrom()
, feeCurrency
, ""
, fragmentExchange.getName()
, "s"
, feesCurrencySpinner.getSelectedItemPosition() % 2 == 0 ? "p" : "f"
, deductHoldingsSwitch.isChecked());
Intent intent = new Intent(getActivity(), HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
else
{
databaseManager.updateTransactionWithId(transactionId
, amount
, calendar.getTime()
, purchasePrice
, fees
, note
, fragmentPair.getFrom().equals(fragmentCurrency.getSymbol()) ? fragmentPair.getTo() : fragmentPair.getFrom()
, feeCurrency
, ""
, fragmentExchange.getName()
,"s"
, feesCurrencySpinner.getSelectedItemPosition() % 2 == 0 ? "p" : "f"
, deductHoldingsSwitch.isChecked());
}
getActivity().finish();
}
}
});
fees_editText = view.findViewById(R.id.fees_editText_sell);
fees_editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
totalValueEditText.removeTextChangedListener(totalValueTextWatcher);
amoutEditText.removeTextChangedListener(amountTextWatcher);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if((isFieldCorrectlyFilled(amoutEditText, false) || isFieldCorrectlyFilled(totalValueEditText, false)) && isFieldCorrectlyFilled(sellPriceEditText, false))
{
double amount = Double.parseDouble(amoutEditText.getText().toString());
double purchasePrice = Double.parseDouble(sellPriceEditText.getText().toString());
double fees;
double totalValue = Double.parseDouble(totalValueEditText.getText().toString());
String feeCurrency;
if(isAmountLastUpdated)
{
totalValue = amount * purchasePrice;
}
else
{
amount = totalValue / purchasePrice;
}
if(fees_editText.getText().toString().equals("0") || (start == 0 && before == 1 && count == 0))
{
if(isAmountLastUpdated)
{
totalValueEditText.setText(String.valueOf(amount * purchasePrice));
}
else
{
amoutEditText.setText(String.valueOf(totalValue / purchasePrice));
}
}
else
{
if(feesCurrencySpinner.getSelectedItemPosition() < 2)
{
feeCurrency = fragmentPair.getFrom();
}
else
{
feeCurrency = fragmentPair.getTo();
}
fees = getFees(feeCurrency, amount, purchasePrice);
if(feesCurrencySpinner.getSelectedItemPosition() % 2 == 0)
{
if(isAmountLastUpdated)
{
totalValueEditText.setText(String.valueOf(totalValue - fees));
}
else
{
amoutEditText.setText(String.valueOf(amount + (fees / purchasePrice)));
}
}
else
{
if(fragmentCurrency.getSymbol().equals(feeCurrency))
{
if(isAmountLastUpdated)
{
totalValueEditText.setText(String.valueOf(totalValue - (fees * purchasePrice)));
}
else
{
amoutEditText.setText(String.valueOf((totalValue / purchasePrice) + fees));
}
}
else
{
if(isAmountLastUpdated)
{
totalValueEditText.setText(String.valueOf(totalValue - fees));
}
else
{
amoutEditText.setText(String.valueOf((totalValue + fees) / purchasePrice));
}
}
}
}
}
}
@Override
public void afterTextChanged(Editable s) {
totalValueEditText.addTextChangedListener(totalValueTextWatcher);
amoutEditText.addTextChangedListener(amountTextWatcher);
}
});
note_editText = view.findViewById(R.id.note_editText_sell);
checkCallingIntent();
}
private double getFees(String feeCurrency, double amount, double purchasedPrice)
{
double fees = 0;
if(!fees_editText.getText().toString().equals(""))
{
fees = Double.parseDouble(fees_editText.getText().toString());
if(feesCurrencySpinner.getSelectedItemPosition() % 2 == 0)
{
if(fragmentCurrency.getSymbol().equals(feeCurrency))
{
fees = (100 * amount) / (100 + fees);
}
else
{
double base = (100 * purchasedPrice * amount) / (100 + fees);
fees = purchasedPrice * amount - base;
}
}
}
return fees;
}
private void checkCallingIntent()
{
Intent intent = getActivity().getIntent();
transactionId = intent.getIntExtra("transactionId", -1);
if(transactionId != -1)
{
DatabaseManager databaseManager = new DatabaseManager(context);
transaction = databaseManager.getCurrencyTransactionById(transactionId);
if(transaction.getType().equals("s"))
{
fillFields();
}
}
}
private void fillFields()
{
amoutEditText.setText(String.valueOf(transaction.getAmount()));
sellPriceEditText.setText(String.valueOf(transaction.getPrice()));
calendar.setTimeInMillis(transaction.getTimestamp());
sellDateEditText.setText(sdf.format(calendar.getTime()));
totalValueEditText.setText(String.valueOf(transaction.getAmount() * transaction.getPrice()));
fees_editText.setText(String.valueOf(transaction.getFees()));
note_editText.setText(transaction.getNote());
}
private void updateAdapter()
{
symbolStrings = new ArrayList<>();
symbolStrings.addAll(PlaceholderManager.getFeeOptionsForSymbol(fragmentPair.getFrom(), getSecureContext()));
symbolStrings.addAll(PlaceholderManager.getFeeOptionsForSymbol(fragmentPair.getTo(), getSecureContext()));
currencyFeeAdapter.clear();
currencyFeeAdapter.addAll(symbolStrings);
currencyFeeAdapter.notifyDataSetChanged();
}
private static Context getSecureContext()
{
return context;
}
private void createDatePicker()
{
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(),
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
sellDateEditText.setText(sdf.format(calendar.getTime()));
createTimePicker();
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
datePickerDialog.show();
}
private void createTimePicker()
{
new android.app.TimePickerDialog(
getContext(),
new android.app.TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
sellDateEditText.setText(sdf.format(calendar.getTime()));
if(fragmentCurrency != null)
{
fragmentCurrency.getTimestampPrice(getContext(), fragmentCurrency.getSymbol().equals(fragmentPair.getFrom()) ? fragmentPair.getTo() : fragmentPair.getFrom(),calendar.getTimeInMillis() / 1000);
}
}
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
true
).show();
}
private boolean isFieldCorrectlyFilled(TextInputEditText editText, boolean displayError)
{
String purchasedPriceText = editText.getText().toString();
double purchasedPrice;
try {
purchasedPrice = Double.parseDouble(purchasedPriceText);
if(purchasedPrice < 0)
{
if(displayError) editText.setError(getResources().getString(R.string.field_negative));
return false;
}
} catch (NumberFormatException e) {
if(displayError) editText.setError(getResources().getString(R.string.field_nan));
return false;
}
if(purchasedPriceText.equals(""))
{
if(displayError) editText.setError(getResources().getString(R.string.field_empty));
return false;
}
return true;
}
@Override
public void onCurrencyUpdated() {
fragmentCurrency = currency;
}
@Override
public void onExchangeUpdated() {
fragmentExchange = exchange;
}
public void updatePair(Pair pair)
{
currencyFeeAdapter = new ArrayAdapter<String>(getSecureContext(), android.R.layout.simple_spinner_item, new ArrayList<>());
currencyFeeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
feesCurrencySpinner.setAdapter(currencyFeeAdapter);
symbolStrings = new ArrayList<>();
symbolStrings.addAll(PlaceholderManager.getFeeOptionsForSymbol(pair.getFrom(), getSecureContext()));
symbolStrings.addAll(PlaceholderManager.getFeeOptionsForSymbol(pair.getTo(), getSecureContext()));
currencyFeeAdapter.addAll(symbolStrings);
currencyFeeAdapter.notifyDataSetChanged();
}
@Override
public void onPairUpdated() {
fragmentPair = pair;
fragmentCurrency.addOnTimestampPriceUpdatedListener(new Currency.OnTimestampPriceUpdatedListener() {
@Override
public void onTimeStampPriceUpdated(String price) {
((TextInputEditText) view.findViewById(R.id.sellPrice_editText)).setText(price);
updatePair(fragmentPair);
}
});
if(preferenceManager == null)
{
preferenceManager = new PreferencesManager(getSecureContext());
}
if(calendar == null)
{
calendar = Calendar.getInstance();
}
fragmentCurrency.getTimestampPrice(getSecureContext(), fragmentCurrency.getSymbol().equals(fragmentPair.getFrom()) ? fragmentPair.getTo() : fragmentPair.getFrom(), calendar.getTimeInMillis() / 1000);
}
}

View File

@ -0,0 +1,471 @@
package com.herbron.moodl.Activities.RecordTransactionFragments;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TimePicker;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.CustomLayouts.CustomRecordFragment;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.Transaction;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.R;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
public class TransferFragment extends CustomRecordFragment {
private static Currency fragmentCurrency;
private static Exchange fragmentExchange;
private Spinner fromSpinner;
private Spinner toSpinner;
private Spinner feeSpinner;
private Switch deductHoldingsSwitch;
private Button saveButton;
private int transactionId;
private Transaction transaction;
private TextInputEditText transferDateEditText;
private TextInputEditText amountEditText;
private TextInputEditText feesEditText;
private TextInputEditText noteEditText;
private SimpleDateFormat sdf;
private Calendar calendar;
private View view;
public static final String EXCHANGE_CODE = "stra:e";
public static final String WALLET_CODE = "stra:mw";
public static final String MINING_CODE = "stra:m";
public static final String ELSE_WALLET_CODE = "stra:smew";
public static final String AIRDROP_CODE = "stra:a";
public static final String UNKNOWN_CODE = "stra:unk";
public static final String FORK_CODE = "stra:fo";
private View.OnClickListener saveButtonClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isFieldCorrectlyFilled(amountEditText, true))
{
if(isTransactionPossible())
{
PreferencesManager preferencesManager = new PreferencesManager(getContext());
DatabaseManager databaseManager = new DatabaseManager(getContext());
double amount = Double.valueOf(amountEditText.getText().toString());
double fees = getFees();
if(transactionId == -1)
{
databaseManager.addTransaction(fragmentCurrency.getSymbol()
, amount
, calendar.getTime()
, 0
, fees
, noteEditText.getText().toString()
, ""
, fragmentCurrency.getSymbol()
, getDestination()
, getSource()
, "t"
, feeSpinner.getSelectedItemPosition() == 0 ? "p" : "f"
, deductHoldingsSwitch.isChecked());
Intent intent = new Intent(getActivity(), HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
else
{
databaseManager.updateTransactionWithId(transactionId
, amount
, calendar.getTime()
, 0
, fees
, noteEditText.getText().toString()
, ""
, fragmentCurrency.getSymbol()
, getDestination()
, getSource()
,"t"
, feeSpinner.getSelectedItemPosition() == 0 ? "p" : "f"
, deductHoldingsSwitch.isChecked());
}
preferencesManager.setMustUpdateSummary(true);
getActivity().finish();
}
else
{
Drawable backgroundDrawableTo = toSpinner.getBackground();
backgroundDrawableTo.mutate();
backgroundDrawableTo.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.error), PorterDuff.Mode.SRC_ATOP));
backgroundDrawableTo.invalidateSelf();
Drawable backgroundDrawableFrom = fromSpinner.getBackground();
backgroundDrawableFrom.mutate();
backgroundDrawableFrom.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.error), PorterDuff.Mode.SRC_ATOP));
backgroundDrawableFrom.invalidateSelf();
view.findViewById(R.id.errorLayouts).setVisibility(View.VISIBLE);
}
}
}
};
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.record_transaction_fragment_transfer, container, false);
calendar = Calendar.getInstance();
sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy", Locale.UK);
initializeViewElements();
return view;
}
private void initializeViewElements()
{
fromSpinner = view.findViewById(R.id.from_transfer_spinner);
toSpinner = view.findViewById(R.id.to_transfer_spinner);
feeSpinner = view.findViewById(R.id.feesFormat_editText_transfer);
setupSpinnesr();
feesEditText = view.findViewById(R.id.fees_editText_transfer);
noteEditText = view.findViewById(R.id.note_editText_transfer);
amountEditText = view.findViewById(R.id.amount_editText_transfer);
transferDateEditText = view.findViewById(R.id.transfertDate_editText);
transferDateEditText.setText(sdf.format(calendar.getTime()));
transferDateEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createDatePicker();
}
});
saveButton = view.findViewById(R.id.saveTransferButton);
saveButton.setOnClickListener(saveButtonClickListener);
deductHoldingsSwitch = view.findViewById(R.id.deductHoldingsTransfer);
checkCallingIntent();
}
private void checkCallingIntent()
{
Intent intent = getActivity().getIntent();
transactionId = intent.getIntExtra("transactionId", -1);
if(transactionId != -1)
{
DatabaseManager databaseManager = new DatabaseManager(getContext());
transaction = databaseManager.getCurrencyTransactionById(transactionId);
if(transaction.getType() != null && transaction.getType().equals("t"))
{
fillFields();
}
}
}
private void fillFields()
{
setupFromSpinner();
setupToSpinner();
amountEditText.setText(String.valueOf(transaction.getAmount()));
calendar.setTimeInMillis(transaction.getTimestamp());
transferDateEditText.setText(sdf.format(calendar.getTime()));
feesEditText.setText(String.format(Locale.UK, "%f", transaction.getFees()));
noteEditText.setText(transaction.getNote());
feeSpinner.setSelection(transaction.getFeeFormat().equals("p") ? 0 : 1);
}
private void setupFromSpinner()
{
switch (transaction.getSource())
{
case EXCHANGE_CODE:
fromSpinner.setSelection(0);
break;
case WALLET_CODE:
fromSpinner.setSelection(1);
break;
case MINING_CODE:
fromSpinner.setSelection(2);
break;
case ELSE_WALLET_CODE:
fromSpinner.setSelection(3);
break;
case AIRDROP_CODE:
fromSpinner.setSelection(4);
break;
case UNKNOWN_CODE:
fromSpinner.setSelection(5);
break;
case FORK_CODE:
fromSpinner.setSelection(6);
break;
}
}
private void setupToSpinner()
{
switch (transaction.getDestination())
{
case EXCHANGE_CODE:
toSpinner.setSelection(0);
break;
case WALLET_CODE:
toSpinner.setSelection(1);
break;
case ELSE_WALLET_CODE:
toSpinner.setSelection(2);
break;
case UNKNOWN_CODE:
toSpinner.setSelection(3);
break;
}
}
private void setupSpinnesr()
{
ArrayAdapter<String> fromAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.from_transfer_options_string_array));
fromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fromSpinner.setAdapter(fromAdapter);
ArrayAdapter<String> toAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.to_transfer_options_string_array));
toAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
toSpinner.setAdapter(toAdapter);
ArrayAdapter<String> feeAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.fees_options));
feeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
feeSpinner.setAdapter(feeAdapter);
fromSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
Drawable backgroundDrawableFrom = fromSpinner.getBackground();
backgroundDrawableFrom.mutate();
backgroundDrawableFrom.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.separationColor), PorterDuff.Mode.SRC_ATOP));
backgroundDrawableFrom.invalidateSelf();
view.findViewById(R.id.errorLayouts).setVisibility(View.INVISIBLE);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
toSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
Drawable backgroundDrawableTo = toSpinner.getBackground();
backgroundDrawableTo.mutate();
backgroundDrawableTo.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.separationColor), PorterDuff.Mode.SRC_ATOP));
backgroundDrawableTo.invalidateSelf();
view.findViewById(R.id.errorLayouts).setVisibility(View.INVISIBLE);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private double getFees()
{
double fees = 0;
if(!feesEditText.getText().toString().equals(""))
{
fees = Double.parseDouble(feesEditText.getText().toString());
}
return fees;
}
private boolean isTransactionPossible()
{
Set<Integer> conflictFrom = new HashSet<>(Arrays.asList(2, 3, 4, 5, 6));
Set<Integer> conflictTo = new HashSet<>(Arrays.asList(2, 3));
return !(conflictFrom.contains(fromSpinner.getSelectedItemPosition()) && conflictTo.contains(toSpinner.getSelectedItemPosition()));
}
private String getDestination()
{
String destination = "";
switch (toSpinner.getSelectedItemPosition())
{
case 0:
destination = EXCHANGE_CODE;
break;
case 1:
destination = WALLET_CODE;
break;
case 2:
destination = ELSE_WALLET_CODE;
break;
case 3:
destination = UNKNOWN_CODE;
break;
}
return destination;
}
private String getSource()
{
String source = "";
switch (fromSpinner.getSelectedItemPosition())
{
case 0:
source = EXCHANGE_CODE;
break;
case 1:
source = WALLET_CODE;
break;
case 2:
source = MINING_CODE;
break;
case 3:
source = ELSE_WALLET_CODE;
break;
case 4:
source = AIRDROP_CODE;
break;
case 5:
source = UNKNOWN_CODE;
break;
case 6:
source = FORK_CODE;
break;
}
return source;
}
private boolean isFieldCorrectlyFilled(TextInputEditText editText, boolean displayError)
{
String purchasedPriceText = editText.getText().toString();
double purchasedPrice;
try {
purchasedPrice = Double.parseDouble(purchasedPriceText);
if(purchasedPrice < 0)
{
if(displayError) editText.setError(getResources().getString(R.string.field_negative));
return false;
}
} catch (NumberFormatException e) {
if(displayError) editText.setError(getResources().getString(R.string.field_nan));
return false;
}
if(purchasedPriceText.equals(""))
{
if(displayError) editText.setError(getResources().getString(R.string.field_empty));
return false;
}
return true;
}
private void createDatePicker()
{
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(),
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
transferDateEditText.setText(sdf.format(calendar.getTime()));
createTimePicker();
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
datePickerDialog.show();
}
private void createTimePicker()
{
new android.app.TimePickerDialog(
getContext(),
new android.app.TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
transferDateEditText.setText(sdf.format(calendar.getTime()));
}
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
true
).show();
}
@Override
public void onCurrencyUpdated() {
fragmentCurrency = currency;
}
@Override
public void onExchangeUpdated() {
fragmentExchange = exchange;
}
@Override
public void onPairUpdated() {
}
}

View File

@ -6,9 +6,11 @@ import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
@ -20,6 +22,7 @@ import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.preference.SwitchPreference;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
@ -34,9 +37,7 @@ import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import com.applandeo.FilePicker;
import com.applandeo.listeners.OnSelectFileListener;
@ -68,9 +69,7 @@ import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@ -178,6 +177,10 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
Drawable gradientDrawable = getResources().getDrawable(R.drawable.gradient_background);
actionBar.setBackgroundDrawable(gradientDrawable);
}
/**
@ -235,7 +238,9 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
return false;
Log.d("moodl", "> " + o + " " + preference);
return (boolean) o;
}
});
@ -244,7 +249,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
public boolean onPreferenceClick(Preference preference) {
boolean isChecked = ((SwitchPreference) findPreference("enable_hitbtc")).isChecked();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
@ -260,7 +265,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
public boolean onPreferenceClick(Preference preference) {
boolean isChecked = ((SwitchPreference) findPreference("enable_binance")).isChecked();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
@ -287,62 +292,64 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
private void startFingerprintProtocol()
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getContext());
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity().getBaseContext());
FingerprintDialogFragment newFragment = FingerprintDialogFragment.newInstance();
SwitchPreference touchdIdSwitch = (SwitchPreference) findPreference("enable_fingerprint");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
keyguardManager = (KeyguardManager) this.getActivity().getSystemService(KEYGUARD_SERVICE);
fingerprintManager = (FingerprintManager) this.getActivity().getSystemService(FINGERPRINT_SERVICE);
try {
if(!fingerprintManager.isHardwareDetected())
{
touchdIdSwitch.setEnabled(false);
}
if(ActivityCompat.checkSelfPermission(this.getActivity().getBaseContext(), Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED)
{
touchdIdSwitch.setEnabled(false);
}
if(!fingerprintManager.hasEnrolledFingerprints())
{
touchdIdSwitch.setEnabled(false);
}
if(!keyguardManager.isKeyguardSecure())
{
touchdIdSwitch.setEnabled(false);
}
else
{
try {
generateKey();
} catch (FingerprintException e) {
e.printStackTrace();
}
if(initCipher())
{
cryptoObject = new FingerprintManager.CryptoObject(cipher);
FingerprintHandler helper = new FingerprintHandler(this.getActivity().getBaseContext(), newFragment);
helper.startAuth(fingerprintManager, cryptoObject);
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
if(preferences.getBoolean("enable_fingerprint", false))
{
newFragment.setCancelable(false);
newFragment.show(getFragmentManager(), "dialog");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
keyguardManager = (KeyguardManager) this.getActivity().getSystemService(KEYGUARD_SERVICE);
fingerprintManager = (FingerprintManager) this.getActivity().getSystemService(FINGERPRINT_SERVICE);
try {
if(!fingerprintManager.isHardwareDetected())
{
this.getActivity().findViewById(R.id.fingerprint_switch).setVisibility(View.GONE);
}
if(ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED)
{
this.getActivity().findViewById(R.id.fingerprint_switch).setVisibility(View.GONE);
}
if(!fingerprintManager.hasEnrolledFingerprints())
{
this.getActivity().findViewById(R.id.fingerprint_switch).setVisibility(View.GONE);
}
if(!keyguardManager.isKeyguardSecure())
{
this.getActivity().findViewById(R.id.fingerprint_switch).setVisibility(View.GONE);
}
else
{
try {
generateKey();
} catch (FingerprintException e) {
e.printStackTrace();
}
if(initCipher())
{
cryptoObject = new FingerprintManager.CryptoObject(cipher);
FingerprintHandler helper = new FingerprintHandler(this.getContext(), newFragment);
helper.startAuth(fingerprintManager, cryptoObject);
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
@TargetApi(23)
private void generateKey() throws FingerprintException
{
try {
@ -368,6 +375,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
}
}
@TargetApi(23)
public boolean initCipher()
{
try {
@ -426,7 +434,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
developperCategory.getPreference(0).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
File cacheDir = getContext().getCacheDir();
File cacheDir = getActivity().getBaseContext().getCacheDir();
File[] cachedFiles = cacheDir.listFiles();
for(int i = 0; i < cachedFiles.length; i++)
@ -446,8 +454,8 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
@Override
public boolean onPreferenceClick(Preference preference) {
Context context = getContext();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
Context context = getActivity().getBaseContext();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainPreferenceFragment.this.getActivity());
View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_export_data, null, true);
dialogBuilder.setView(dialogView);
@ -502,7 +510,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault());
Date currentDate = new Date();
String fileName = "Bakup_" + formatter.format(currentDate) + ".moodl";
DatabaseManager databaseManager = new DatabaseManager(getContext());
DatabaseManager databaseManager = new DatabaseManager(getActivity().getBaseContext());
if(enterPasswordCheckbox.isChecked())
{
@ -528,15 +536,15 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
if(backupManualEntriesCheckbox.isChecked())
{
backupJson.put("transactions",
databaseManager.getDatabaseBackup(getContext(),
DatabaseManager.TABLE_MANUAL_CURRENCIES,
databaseManager.getDatabaseBackup(getActivity().getBaseContext(),
DatabaseManager.TABLE_MANUAL_TRANSACTIONS,
enterPasswordCheckbox.isChecked()));
}
if(backupWatchlistCheckbox.isChecked())
{
backupJson.put("watchlist",
databaseManager.getDatabaseBackup(getContext(),
databaseManager.getDatabaseBackup(getActivity().getBaseContext(),
DatabaseManager.TABLE_WATCHLIST,
enterPasswordCheckbox.isChecked()));
}
@ -544,7 +552,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
if(backupKeysCheckbox.isChecked())
{
backupJson.put("apiKeys",
databaseManager.getDatabaseBackup(getContext(),
databaseManager.getDatabaseBackup(getActivity().getBaseContext(),
DatabaseManager.TABLE_EXCHANGE_KEYS,
enterPasswordCheckbox.isChecked()));
}
@ -580,8 +588,8 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
@Override
public boolean onPreferenceClick(Preference preference) {
Context context = getContext();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
Context context = getActivity().getBaseContext();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainPreferenceFragment.this.getActivity());
View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_import_data, null, true);
dialogBuilder.setView(dialogView);
@ -706,7 +714,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
if(enterPasswordCheckbox.isChecked())
{
checker = DataCrypter.decrypt(getContext(), backupJson.getString("encodeChecker"));
checker = DataCrypter.decrypt(getActivity().getBaseContext(), backupJson.getString("encodeChecker"));
}
else
{
@ -719,7 +727,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
{
if(wipeManualEntriesCheckbox.isChecked())
{
databaseManager.wipeData(DatabaseManager.TABLE_MANUAL_CURRENCIES);
databaseManager.wipeData(DatabaseManager.TABLE_MANUAL_TRANSACTIONS);
}
if(backupJson.has("transactions"))
@ -730,7 +738,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
{
JSONObject transactionObject = transactionsArray.getJSONObject(i);
databaseManager.addRowTransaction(transactionObject, getContext(), enterPasswordCheckbox.isChecked());
databaseManager.addRowTransaction(transactionObject, getActivity().getBaseContext(), enterPasswordCheckbox.isChecked());
}
}
}
@ -748,9 +756,29 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
for(int i = 0; i < watchlistArray.length(); i++)
{
JSONObject transactionObject = watchlistArray.getJSONObject(i);
JSONObject watchlistObject = watchlistArray.getJSONObject(i);
databaseManager.addRowWatchlist(transactionObject, getContext(), enterPasswordCheckbox.isChecked());
databaseManager.addRowWatchlist(watchlistObject, getActivity().getBaseContext(), enterPasswordCheckbox.isChecked());
}
}
}
if(restoreApiKeysCheckbox.isChecked())
{
if(wipeApiKeyxCheckbox.isChecked())
{
databaseManager.wipeData(DatabaseManager.TABLE_EXCHANGE_KEYS);
}
if(backupJson.has("apiKeys"))
{
JSONArray apiArray = backupJson.getJSONArray("apiKeys");
for(int i = 0; i < apiArray.length(); i++)
{
JSONObject apiKeysObject = apiArray.getJSONObject(i);
databaseManager.addRowApiKeys(apiKeysObject, getActivity().getBaseContext(), enterPasswordCheckbox.isChecked());
}
}
}
@ -784,6 +812,26 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
}
});
DatabaseManager databaseManager = new DatabaseManager(getActivity().getBaseContext());
int disabledAcount = databaseManager.getDisabledExchangeAccountsNumber();
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("exchange");
if(disabledAcount > 0)
{
preferenceScreen.setWidgetLayoutResource(R.layout.alert_layout);
}
preferenceScreen.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent exchangeListIntent = new Intent(getActivity().getBaseContext(), ExchangeListActivity.class);
startActivity(exchangeListIntent);
return false;
}
});
EditTextPreference editTextPreference = (EditTextPreference) findPreference("minimum_value_displayed");
editTextPreference.setPositiveButtonText(getString(R.string.save));
editTextPreference.setNegativeButtonText(getString(R.string.cancel));
@ -793,7 +841,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
{
if(mustEncrypt)
{
backupJson.put("encodeChecker", DataCrypter.encrypt(getContext(), "NaukVerification"));
backupJson.put("encodeChecker", DataCrypter.encrypt(getActivity().getBaseContext(), "NaukVerification"));
}
else
{
@ -820,7 +868,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(getContext(), p);
result = ContextCompat.checkSelfPermission(getActivity().getBaseContext(), p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
@ -839,6 +887,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
//startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}

View File

@ -0,0 +1,13 @@
package com.herbron.moodl;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
public interface CurrencyInfoUpdateNotifierInterface {
void onTimestampPriceUpdated(String price);
void onHistoryDataUpdated();
void onPriceUpdated(Currency currency);
}

View File

@ -0,0 +1,120 @@
package com.herbron.moodl.CustomAdapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.R;
import java.util.ArrayList;
public class CoinRecordListAdapter extends ArrayAdapter<Currency> {
private CustomFilter filter;
private ArrayList<Currency> currencies, suggestions;
public CoinRecordListAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Currency> currencies) {
super(context, resource, currencies);
this.currencies = currencies;
this.suggestions = currencies;
}
@Override
public int getCount() {
return currencies.size();
}
@Override
public Currency getItem(int position) {
return currencies.get(position);
}
@Override
public long getItemId(int position) {
return currencies.indexOf(getItem(position));
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Currency currency = getItem(position);
if(convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_summary_coin_row, parent, false);
}
TextView nameTxtview = convertView.findViewById(R.id.currencyName);
TextView symbolTxtView = convertView.findViewById(R.id.currencySymbol);
nameTxtview.setText(currency.getName());
symbolTxtView.setText(currency.getSymbol());
return convertView;
}
@NonNull
@Override
public Filter getFilter() {
if(filter == null)
{
filter = new CustomFilter();
}
return filter;
}
private class CustomFilter extends Filter
{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null && constraint.length() > 0)
{
constraint = constraint.toString().toLowerCase();
ArrayList<Currency> filters = new ArrayList<>();
for(int i = 0; i < suggestions.size(); i++)
{
if(suggestions.get(i).getName().toLowerCase().contains(constraint) || suggestions.get(i).getSymbol().toLowerCase().contains(constraint))
{
Currency currency = new Currency(suggestions.get(i).getName(), suggestions.get(i).getSymbol());
filters.add(currency);
}
}
results.count = filters.size();
results.values = filters;
}
else
{
results.count = suggestions.size();
results.values = suggestions;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results != null)
{
currencies = (ArrayList<Currency>) results.values;
}
notifyDataSetChanged();
}
}
}

View File

@ -1,4 +1,4 @@
package com.herbron.moodl.LayoutManagers;
package com.herbron.moodl.CustomAdapters;
import android.content.Context;
import android.support.annotation.NonNull;
@ -19,13 +19,13 @@ import java.util.ArrayList;
* Created by Guitoune on 17/01/2018.
*/
public class CurrencyListAdapter extends BaseAdapter implements Filterable {
public class CoinWatchlistAdapter extends BaseAdapter implements Filterable {
private ArrayList<Currency> currencies, suggestions;
private Context context;
private CustomFilter filter;
public CurrencyListAdapter(Context context, ArrayList<Currency> currencies) {
public CoinWatchlistAdapter(Context context, ArrayList<Currency> currencies) {
this.context = context;
this.currencies = currencies;
this.suggestions = currencies;
@ -53,7 +53,7 @@ public class CurrencyListAdapter extends BaseAdapter implements Filterable {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_currency_row, parent, false);
convertView = inflater.inflate(R.layout.custom_watchlist_coin_row, parent, false);
}
TextView currencyName = convertView.findViewById(R.id.currencyName);
@ -68,7 +68,7 @@ public class CurrencyListAdapter extends BaseAdapter implements Filterable {
}
if (position % 2 == 0)
convertView.setBackgroundColor(context.getResources().getColor(R.color.listBackground2));
convertView.setBackgroundColor(context.getResources().getColor(R.color.white));
else
convertView.setBackgroundColor(context.getResources().getColor(R.color.listBackground));

View File

@ -0,0 +1,78 @@
package com.herbron.moodl.CustomAdapters;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.herbron.moodl.Activities.AddExchangeActivity;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.R;
import java.util.ArrayList;
public class ExchangeDescriptionListAdapter extends ArrayAdapter<Exchange> {
private Context context;
public ExchangeDescriptionListAdapter(Context context, ArrayList<Exchange> exchanges)
{
super(context, android.R.layout.simple_list_item_1, exchanges);
this.context = context;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Exchange exchange = getItem(position);
if(convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.exchange_cell, parent, false);
}
TextView exchangeNameTextView = convertView.findViewById(R.id.exchange_name);
TextView exchangeDescriptionTextView = convertView.findViewById(R.id.exchange_description);
ImageView accountOffImageView = convertView.findViewById(R.id.exchange_account_off_imageView);
exchangeNameTextView.setText(exchange.getName());
exchangeDescriptionTextView.setText(exchange.getDescription());
if(!exchange.isEnabled())
{
accountOffImageView.setVisibility(View.VISIBLE);
}
convertView.findViewById(R.id.editExchangeInfosLayout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent editExchangeAccountIntent = new Intent(context, AddExchangeActivity.class);
editExchangeAccountIntent.putExtra("isEdit", true);
editExchangeAccountIntent.putExtra("exchangeId", exchange.getId());
editExchangeAccountIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(editExchangeAccountIntent);
}
});
convertView.findViewById(R.id.deleteExchangeInfosLayout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatabaseManager databaseManager = new DatabaseManager(getContext());
databaseManager.deleteExchangeAccountFromId(exchange.getId());
remove(exchange);
notifyDataSetChanged();
}
});
return convertView;
}
}

View File

@ -0,0 +1,120 @@
package com.herbron.moodl.CustomAdapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.R;
import java.util.ArrayList;
public class ExchangeRecordListAdapter extends ArrayAdapter<Exchange> {
private CustomFilter filter;
private ArrayList<Exchange> exchanges, suggestions;
public ExchangeRecordListAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Exchange> exchanges) {
super(context, resource, exchanges);
this.exchanges = exchanges;
this.suggestions = exchanges;
}
@NonNull
@Override
public Filter getFilter() {
if(filter == null)
{
filter = new CustomFilter();
}
return filter;
}
@Override
public int getCount() {
return exchanges.size();
}
@Nullable
@Override
public Exchange getItem(int position) {
return exchanges.get(position);
}
@Override
public long getItemId(int position) {
return exchanges.indexOf(getItem(position));
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Exchange exchange = getItem(position);
if(convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.simple_spinner_item, parent, false);
}
TextView nameTxtview = convertView.findViewById(R.id.textView);
nameTxtview.setTextColor(getContext().getResources().getColor(android.R.color.tab_indicator_text));
nameTxtview.setText(exchange.getName());
return convertView;
}
private class CustomFilter extends Filter
{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null && constraint.length() > 0)
{
constraint = constraint.toString().toLowerCase();
ArrayList<Exchange> filters = new ArrayList<>();
for(int i = 0; i < suggestions.size(); i++)
{
if(suggestions.get(i).getName().toLowerCase().contains(constraint))
{
Exchange exchange = new Exchange(suggestions.get(i));
filters.add(exchange);
}
}
results.count = filters.size();
results.values = filters;
}
else
{
results.count = suggestions.size();
results.values = suggestions;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results != null)
{
exchanges = (ArrayList<Exchange>) results.values;
}
notifyDataSetChanged();
}
}
}

View File

@ -1,4 +1,4 @@
package com.herbron.moodl.LayoutManagers;
package com.herbron.moodl.CustomAdapters;
import android.app.Activity;
import android.content.Context;
@ -11,7 +11,7 @@ import android.widget.LinearLayout;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyCardview;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyDetailsList;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import java.util.List;
@ -22,14 +22,14 @@ import java.util.List;
public class OverviewListAdapter extends ArrayAdapter<Currency> {
private Activity activity;
private CurrencyDetailsList currencyDetailsList;
private CryptocompareApiManager cryptocompareApiManager;
public OverviewListAdapter(Context context, List<Currency> currencies, Activity activity)
{
super(context, android.R.layout.simple_expandable_list_item_1, currencies);
this.activity = activity;
currencyDetailsList = CurrencyDetailsList.getInstance(getContext());
cryptocompareApiManager = CryptocompareApiManager.getInstance(getContext());
}
@NonNull
@ -38,7 +38,7 @@ public class OverviewListAdapter extends ArrayAdapter<Currency> {
{
Currency currency = getItem(position);
currencyDetailsList.getCurrencyDetailsFromSymbol(currency.getSymbol());
cryptocompareApiManager.getCurrencyDetailsFromSymbol(currency.getSymbol());
CurrencyCardview currencyCardview = new CurrencyCardview(getContext(), currency, activity);
LinearLayout linearLayout = new LinearLayout(getContext());

View File

@ -0,0 +1,121 @@
package com.herbron.moodl.CustomAdapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import com.herbron.moodl.DataManagers.InfoAPIManagers.Pair;
import com.herbron.moodl.PlaceholderManager;
import com.herbron.moodl.R;
import java.util.ArrayList;
public class PairRecordListAdapter extends ArrayAdapter<Pair> {
private CustomFilter filter;
private ArrayList<Pair> pairs, suggestions;
public PairRecordListAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Pair> pairs) {
super(context, resource, pairs);
this.pairs = pairs;
this.suggestions = pairs;
}
@NonNull
@Override
public Filter getFilter() {
if(filter == null)
{
filter = new CustomFilter();
}
return filter;
}
@Override
public int getCount() {
return pairs.size();
}
@Nullable
@Override
public Pair getItem(int position) {
return pairs.get(position);
}
@Override
public long getItemId(int position) {
return pairs.indexOf(getItem(position));
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Pair pair = getItem(position);
if(convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.simple_spinner_item, parent, false);
}
TextView pairTxtView = convertView.findViewById(R.id.textView);
pairTxtView.setTextColor(getContext().getResources().getColor(android.R.color.tab_indicator_text));
pairTxtView.setText(PlaceholderManager.getPairString(pair.getFrom(), pair.getTo(), getContext()));
return convertView;
}
private class CustomFilter extends Filter
{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null && constraint.length() > 0)
{
constraint = constraint.toString().toUpperCase();
ArrayList<Pair> filters = new ArrayList<>();
for(int i = 0; i < suggestions.size(); i++)
{
if(suggestions.get(i).getFrom().contains(constraint) || suggestions.get(i).getTo().contains(constraint))
{
Pair pair = new Pair(suggestions.get(i));
filters.add(pair);
}
}
results.count = filters.size();
results.values = filters;
}
else
{
results.count = suggestions.size();
results.values = suggestions;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results != null)
{
pairs = (ArrayList<Pair>) results.values;
}
notifyDataSetChanged();
}
}
}

View File

@ -0,0 +1,44 @@
package com.herbron.moodl.CustomAdapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.herbron.moodl.Activities.RecordTransactionFragments.BuyFragment;
import com.herbron.moodl.Activities.RecordTransactionFragments.SellFragment;
import com.herbron.moodl.Activities.RecordTransactionFragments.TransferFragment;
public class RecordTransactionPageAdapter extends FragmentStatePagerAdapter {
private int tabsNumber;
public RecordTransactionPageAdapter(FragmentManager fm, int tabsNumber) {
super(fm);
this.tabsNumber = tabsNumber;
}
@Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
BuyFragment buyFragment = new BuyFragment();
return buyFragment;
case 1:
SellFragment sellFragment = new SellFragment();
return sellFragment;
case 2:
TransferFragment transferFragment = new TransferFragment();
return transferFragment;
default:
return null;
}
}
@Override
public int getCount() {
return tabsNumber;
}
}

View File

@ -1,4 +1,4 @@
package com.herbron.moodl.LayoutManagers;
package com.herbron.moodl.CustomAdapters;
import android.content.Context;
import android.support.annotation.NonNull;

View File

@ -1,4 +1,4 @@
package com.herbron.moodl.LayoutManagers;
package com.herbron.moodl.CustomAdapters;
import android.app.Activity;
import android.content.Context;
@ -55,7 +55,7 @@ public class TransactionListAdapter extends ArrayAdapter<Transaction> {
TextView dateTxtView = convertView.findViewById(R.id.purchaseDate);
amountTxtView.setText(String.valueOf(transaction.getAmount()));
valueTxtView.setText(numberConformer(transaction.getPurchasedPrice() * transaction.getAmount()));
valueTxtView.setText(numberConformer(transaction.getPrice() * transaction.getAmount()));
dateTxtView.setText(getDateFromTimestamp(transaction.getTimestamp()));
LinearLayout deleteLayout = convertView.findViewById(R.id.deleteTransactionLayout);

View File

@ -1,4 +1,4 @@
package com.herbron.moodl.LayoutManagers;
package com.herbron.moodl.CustomLayouts;
import android.content.Context;
import android.util.AttributeSet;

View File

@ -0,0 +1,41 @@
package com.herbron.moodl.CustomLayouts;
import android.support.v4.app.Fragment;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.DataManagers.InfoAPIManagers.Pair;
public abstract class CustomRecordFragment extends Fragment {
protected Currency currency;
protected Exchange exchange;
protected Pair pair;
public void setCurrency(Currency currency)
{
this.currency = currency;
onCurrencyUpdated();
}
public void setExchange(Exchange exchange)
{
this.exchange = exchange;
onExchangeUpdated();
}
public void setPair(Pair pair)
{
this.pair = pair;
onPairUpdated();
}
public abstract void onCurrencyUpdated();
public abstract void onExchangeUpdated();
public abstract void onPairUpdated();
}

View File

@ -0,0 +1,92 @@
package com.herbron.moodl.CustomLayouts;
import android.content.Context;
import android.graphics.drawable.StateListDrawable;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.herbron.moodl.R;
public class CustomTabLayout extends TabLayout {
private LinearLayout linearLayout;
private Context context;
public CustomTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
linearLayout = (LinearLayout) getChildAt(0);
this.context = context;
}
private StateListDrawable getSellStateListDrawable() {
StateListDrawable sld = new StateListDrawable();
sld.addState(new int[] {android.R.attr.state_pressed},
ContextCompat.getDrawable(context, R.drawable.unselected_tab_background));
sld.addState(new int[] {android.R.attr.state_selected},
ContextCompat.getDrawable(context, R.drawable.record_transaction_tab_background_sell));
sld.addState(new int[] {android.R.attr.state_enabled },
ContextCompat.getDrawable(context, R.drawable.unselected_tab_background));
sld.addState(new int[] { },
ContextCompat.getDrawable(context, R.drawable.disabled_tab_background));
return sld;
}
private StateListDrawable getBuyStateListDrawable() {
StateListDrawable sld = new StateListDrawable();
sld.addState(new int[] {android.R.attr.state_pressed},
ContextCompat.getDrawable(context, R.drawable.unselected_tab_background));
sld.addState(new int[] {android.R.attr.state_selected},
ContextCompat.getDrawable(context, R.drawable.record_transaction_tab_background_buy));
sld.addState(new int[] {android.R.attr.state_enabled },
ContextCompat.getDrawable(context, R.drawable.unselected_tab_background));
sld.addState(new int[] { },
ContextCompat.getDrawable(context, R.drawable.disabled_tab_background));
return sld;
}
private StateListDrawable getTransferStateListDrawable() {
StateListDrawable sld = new StateListDrawable();
sld.addState(new int[] {android.R.attr.state_pressed},
ContextCompat.getDrawable(context, R.drawable.unselected_tab_background));
sld.addState(new int[] {android.R.attr.state_selected},
ContextCompat.getDrawable(context, R.drawable.record_transaction_tab_background_transfer));
sld.addState(new int[] {android.R.attr.state_enabled },
ContextCompat.getDrawable(context, R.drawable.unselected_tab_background));
sld.addState(new int[] { },
ContextCompat.getDrawable(context, R.drawable.disabled_tab_background));
return sld;
}
public void addTab(int index, String label) {
TextView textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setText(label);
textView.setGravity(GRAVITY_CENTER);
textView.setTextColor(getResources().getColor(R.color.separationColor));
addTab(newTab().setCustomView(textView));
View tabView = linearLayout.getChildAt(linearLayout.getChildCount() - 1);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
params.setMargins(2, 0, 2, 0);
tabView.setLayoutParams(params);
switch (index)
{
case 0:
tabView.setBackground(getBuyStateListDrawable());
break;
case 1:
tabView.setBackground(getSellStateListDrawable());
break;
case 2:
tabView.setBackground(getTransferStateListDrawable());
break;
}
}
}

View File

@ -1,4 +1,4 @@
package com.herbron.moodl.LayoutManagers;
package com.herbron.moodl.CustomLayouts;
import android.content.Context;
import android.support.v4.view.ViewPager;

View File

@ -1,49 +1,31 @@
package com.herbron.moodl.DataManagers;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.DataNotifiers.BinanceUpdateNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyDetailsList;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import com.herbron.moodl.DataManagers.ExchangeManager.BinanceManager;
import com.herbron.moodl.DataManagers.ExchangeManager.HitBtcManager;
import com.herbron.moodl.DataNotifierInterface;
import com.herbron.moodl.R;
import com.herbron.moodl.DataNotifiers.BalanceUpdateNotifierInterface;
import com.herbron.moodl.DataNotifiers.HitBTCUpdateNotifierInterface;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
/**
* Created by Tiji on 25/12/2017.
*/
public class BalanceManager {
public class BalanceManager implements BinanceUpdateNotifierInterface, HitBTCUpdateNotifierInterface {
private String publicHitKey;
private String publicBinanceKey;
private String publicPoloniex;
private String privateHitKey;
private String privateBinanceKey;
private String privatePoloniex;
final private String hitBalanceUrl = "https://api.hitbtc.com/api/2/trading/balance";
final private String detailUrl = "https://www.cryptocompare.com/api/data/coinlist/";
private RequestQueue requestQueue;
private List<Currency> binanceBalance;
private List<Currency> hitBalance;
private List<Currency> manualBalances;
private List<Currency> totalBalance;
private android.content.Context context;
private LinkedHashMap<String, String> coinInfosHashmap;
private PreferencesManager preferenceManager;
private DatabaseManager databaseManager;
private CurrencyDetailsList currencyDetailsList;
private CryptocompareApiManager cryptocompareApiManager;
private int balanceCounter;
@ -51,70 +33,37 @@ public class BalanceManager {
private List<HitBtcManager> hitBtcManagers;
private List<BinanceManager> binanceManagers;
private DataNotifierInterface dataNotifierInterface;
private BalanceUpdateNotifierInterface balanceUpdateNotifierInterface;
public BalanceManager(android.content.Context context)
{
this.context = context;
preferenceManager = new PreferencesManager(context);
requestQueue = Volley.newRequestQueue(context);
binanceBalance = new ArrayList<Currency>();
hitBalance = new ArrayList<Currency>();
manualBalances = new ArrayList<Currency>();
databaseManager = new DatabaseManager(context);
hitBtcManagers = new ArrayList<>();
binanceManagers = new ArrayList<>();
currencyDetailsList = CurrencyDetailsList.getInstance(context);
cryptocompareApiManager = CryptocompareApiManager.getInstance(context);
balanceCounter = 0;
setListener((DataNotifierInterface) ((HomeActivity) context).getHoldingsFragment());
setListener((BalanceUpdateNotifierInterface) ((HomeActivity) context).getHoldingsFragment());
}
public void setListener(DataNotifierInterface dataNotifierInterface)
public void setListener(BalanceUpdateNotifierInterface balanceUpdateNotifierInterface)
{
this.dataNotifierInterface = dataNotifierInterface;
}
public List<String> getBiggestCurrencies()
{
List<String> currenciesDetails = new ArrayList<>();
int index = 0;
Iterator<String> coinIterator = currencyDetailsList.getCoinInfosHashmap().keySet().iterator();
while(index < 11)
{
index++;
Log.d("moodl", "For " + index + " : " + coinIterator.next());
}
return currenciesDetails;
this.balanceUpdateNotifierInterface = balanceUpdateNotifierInterface;
}
public void updateExchangeKeys()
{
String publicKey = preferenceManager.getHitBTCPublicKey();
String privateKey = preferenceManager.getHitBTCPrivateKey();
hitBtcManagers.clear();
if(preferenceManager.isHitBTCActivated() && publicKey != null && privateKey != null)
{
hitBtcManagers.add(new HitBtcManager(context, publicKey, privateKey));
}
publicKey = preferenceManager.getBinancePublicKey();
privateKey = preferenceManager.getBinancePrivateKey();
hitBtcManagers = databaseManager.getHitBtcAccounts(context);
binanceManagers.clear();
if(preferenceManager.isBinanceActivated() && publicKey != null && privateKey != null)
{
binanceManagers.add(new BinanceManager(publicKey, privateKey));
}
binanceManagers = databaseManager.getBinanceAccounts();
}
public List<Currency> getTotalBalance()
@ -125,10 +74,12 @@ public class BalanceManager {
public void updateTotalBalance()
{
boolean isUpdated = false;
updateExchangeKeys();
balanceCounter = 0;
manualBalances = databaseManager.getAllCurrenciesFromManualCurrency();
manualBalances = databaseManager.getAllCurrenciesFromTransactions();
if(binanceManagers.size() > 0)
{
@ -136,17 +87,9 @@ public class BalanceManager {
for(int i = 0; i < binanceManagers.size(); i++)
{
binanceManagers.get(i).updateBalance(new BinanceManager.BinanceCallBack() {
@Override
public void onSuccess() {
countBalances();
}
@Override
public void onError(String error) {
dataNotifierInterface.onBalanceError(error);
}
});
final BinanceManager binanceManager = binanceManagers.get(i);
binanceManager.addListener(this);
binanceManager.updateBalance();
}
}
@ -156,17 +99,9 @@ public class BalanceManager {
for(int i = 0; i < hitBtcManagers.size(); i++)
{
hitBtcManagers.get(i).updateGlobalBalance(new HitBtcManager.HitBtcCallBack() {
@Override
public void onSuccess() {
countBalances();
}
@Override
public void onError(String error) {
dataNotifierInterface.onBalanceError(error);
}
});
final HitBtcManager hitBtcManager = hitBtcManagers.get(i);
hitBtcManager.addListener(this);
hitBtcManager.updateGlobalBalance();
}
}
@ -204,7 +139,7 @@ public class BalanceManager {
mergeBalanceTotal(manualBalances);
dataNotifierInterface.onBalanceDataUpdated();
balanceUpdateNotifierInterface.onBalanceDataUpdated();
}
private void mergeBalanceTotal(List<Currency> balance)
@ -233,13 +168,31 @@ public class BalanceManager {
}
}
public interface VolleyCallBack {
void onSuccess();
void onError(String error);
@Override
public void onBinanceTradesUpdated() {
}
public interface IconCallBack {
void onSuccess();
@Override
public void onBinanceBalanceUpdateSuccess() {
countBalances();
}
@Override
public void onBinanceBalanceUpdateError(int accountId, String error) {
databaseManager.disableExchangeAccount(accountId);
balanceUpdateNotifierInterface.onBalanceError(error);
}
@Override
public void onHitBTCBalanceUpdateSuccess() {
countBalances();
}
@Override
public void onHitBTCBalanceUpdateError(int accountId, String error) {
databaseManager.disableExchangeAccount(accountId);
balanceUpdateNotifierInterface.onBalanceError(error);
}
public void sortCoins()
@ -258,47 +211,9 @@ public class BalanceManager {
}
}
public void updateDetails(final IconCallBack callBack)
public CryptocompareApiManager getCryptocompareApiManager()
{
if(!currencyDetailsList.isUpToDate())
{
currencyDetailsList.update(callBack);
}
else
{
callBack.onSuccess();
}
}
public String getIconUrl(String symbol)
{
String url;
try {
switch (symbol)
{
case "IOTA":
url = "https://www.cryptocompare.com/media/1383540/iota_logo.png?width=50";
break;
default:
JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol));
url = "https://www.cryptocompare.com" + jsonObject.getString("ImageUrl") + "?width=50";
break;
}
} catch (NullPointerException e) {
Log.d(context.getResources().getString(R.string.debug), symbol + " has no icon URL");
url = null;
} catch (JSONException e) {
Log.d(context.getResources().getString(R.string.debug), "Url parsing error for " + symbol);
url = null;
}
return url;
}
public CurrencyDetailsList getCurrencyDetailList()
{
return currencyDetailsList;
return cryptocompareApiManager;
}
public String getCurrencyName(String symbol)
@ -306,10 +221,12 @@ public class BalanceManager {
String currencyName = null;
try {
JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol));
JSONObject jsonObject = new JSONObject(cryptocompareApiManager.getCoinInfosHashmap().get(symbol));
currencyName = jsonObject.getString("CoinName");
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
currencyName = symbol;
}
return currencyName;
@ -320,40 +237,14 @@ public class BalanceManager {
int id = 0;
try {
JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol));
JSONObject jsonObject = new JSONObject(cryptocompareApiManager.getCoinInfosHashmap().get(symbol));
id = jsonObject.getInt("Id");
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
id = -1;
}
return id;
}
private void sortDetails()
{
LinkedHashMap<String, String> sortedHashmap = new LinkedHashMap<>();
List<String> listInfos = new ArrayList<>(coinInfosHashmap.values());
List<String> listSymbols = new ArrayList<>(coinInfosHashmap.keySet());
for(int i = 0; i < coinInfosHashmap.keySet().size(); i++)
{
try {
JSONObject jsonObject = new JSONObject(listInfos.get(i));
int index = jsonObject.getInt("SortOrder");
listInfos.add(index, listInfos.get(i));
listSymbols.add(index, listSymbols.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for(int i = 0; i < listInfos.size(); i++)
{
sortedHashmap.put(listSymbols.get(i), listInfos.get(i));
}
coinInfosHashmap = sortedHashmap;
}
}

View File

@ -4,10 +4,8 @@ import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import com.herbron.moodl.CurrencyInfoUpdateNotifierInterface;
import java.lang.reflect.Field;
import java.util.ArrayList;
@ -46,8 +44,11 @@ public class Currency implements Parcelable {
private int rank;
private String startDate;
private List<String> socialMediaLinks;
private List<OnTimestampPriceUpdatedListener> onTimestampPriceUpdatedListenerList;
//private String proofType
private CurrencyInfoUpdateNotifierInterface currencyInfoUpdateNotifierInterface;
public Currency() {}
public Currency(String symbol, double balance)
@ -76,9 +77,12 @@ public class Currency implements Parcelable {
this.tickerId = tickerId;
}
//public Currency(int id, String symbol, String name, String algorithm, String proofType, )
public void setListener(CurrencyInfoUpdateNotifierInterface currencyInfoUpdateNotifierInterface)
{
this.currencyInfoUpdateNotifierInterface = currencyInfoUpdateNotifierInterface;
}
public void getTimestampPrice(android.content.Context context, String toSymbol, final PriceCallBack callBack, long timestamp)
public void getTimestampPrice(android.content.Context context, String toSymbol, long timestamp)
{
dataRetriver = new CurrencyDataRetriever(context);
@ -88,12 +92,20 @@ public class Currency implements Parcelable {
@Override
public void onSuccess(String price) {
callBack.onSuccess(price);
currencyInfoUpdateNotifierInterface.onTimestampPriceUpdated(price);
if(onTimestampPriceUpdatedListenerList != null)
{
for(int i = 0; i < onTimestampPriceUpdatedListenerList.size(); i++)
{
onTimestampPriceUpdatedListenerList.get(i).onTimeStampPriceUpdated(price);
}
}
}
}, timestamp);
}
public void updatePrice(android.content.Context context, String toSymbol, final CurrencyCallBack callBack)
public void updatePrice(android.content.Context context, String toSymbol, final CurrencyInfoUpdateNotifierInterface callBack)
{
dataRetriver = new CurrencyDataRetriever(context);
@ -107,12 +119,12 @@ public class Currency implements Parcelable {
setDayFluctuationPercentage(currencyInfo.getDayFluctuationPercentage());
}
callBack.onSuccess(Currency.this);
callBack.onPriceUpdated(currencyInfo);
}
});
}
public void updateHistoryMinutes(android.content.Context context, String toSymbol, final CurrencyCallBack callBack)
public void updateHistoryMinutes(android.content.Context context, String toSymbol)
{
dataRetriver = new CurrencyDataRetriever(context);
@ -121,7 +133,7 @@ public class Currency implements Parcelable {
public void onSuccess(List<CurrencyDataChart> dataChart) {
setHistoryMinutes(dataChart);
callBack.onSuccess(Currency.this);
currencyInfoUpdateNotifierInterface.onHistoryDataUpdated();
}
@Override
@ -178,7 +190,7 @@ public class Currency implements Parcelable {
});
}
public void updateHistoryHours(android.content.Context context, String toSymbol, final CurrencyCallBack callBack)
public void updateHistoryHours(android.content.Context context, String toSymbol)
{
dataRetriver = new CurrencyDataRetriever(context);
dataRetriver.updateHistory(symbol, toSymbol, new CurrencyDataRetriever.DataChartCallBack() {
@ -186,7 +198,7 @@ public class Currency implements Parcelable {
public void onSuccess(List<CurrencyDataChart> dataChart) {
setHistoryHours(dataChart);
callBack.onSuccess(Currency.this);
currencyInfoUpdateNotifierInterface.onHistoryDataUpdated();
}
@Override
@ -194,7 +206,7 @@ public class Currency implements Parcelable {
}, CurrencyDataRetriever.HOURS);
}
public void updateHistoryDays(android.content.Context context, String toSymbol, final CurrencyCallBack callBack)
public void updateHistoryDays(android.content.Context context, String toSymbol)
{
dataRetriver = new CurrencyDataRetriever(context);
dataRetriver.updateHistory(symbol, toSymbol, new CurrencyDataRetriever.DataChartCallBack() {
@ -202,7 +214,7 @@ public class Currency implements Parcelable {
public void onSuccess(List<CurrencyDataChart> dataChart) {
setHistoryDays(dataChart);
callBack.onSuccess(Currency.this);
currencyInfoUpdateNotifierInterface.onHistoryDataUpdated();
}
@Override
@ -210,12 +222,6 @@ public class Currency implements Parcelable {
}, CurrencyDataRetriever.DAYS);
}
public void updateDetails(android.content.Context context, final CurrencyCallBack callBack)
{
dataRetriver = new CurrencyDataRetriever(context);
}
private int getDarkenColor(int color)
{
int transColor;
@ -525,4 +531,19 @@ public class Currency implements Parcelable {
return new Currency[size];
}
};
public interface OnTimestampPriceUpdatedListener
{
void onTimeStampPriceUpdated(String price);
}
public void addOnTimestampPriceUpdatedListener(OnTimestampPriceUpdatedListener onTimestampPriceUpdatedListener)
{
if(onTimestampPriceUpdatedListenerList == null)
{
onTimestampPriceUpdatedListenerList = new ArrayList<>();
}
onTimestampPriceUpdatedListenerList.add(onTimestampPriceUpdatedListener);
}
}

View File

@ -12,11 +12,11 @@ import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
@ -25,6 +25,7 @@ import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.herbron.moodl.Activities.CurrencyDetailsActivity;
import com.herbron.moodl.CurrencyInfoUpdateNotifierInterface;
import com.herbron.moodl.DataManagers.DatabaseManager;
import com.herbron.moodl.DataManagers.PreferencesManager;
import com.herbron.moodl.MoodlBox;
@ -36,16 +37,34 @@ import java.util.List;
import static com.herbron.moodl.MoodlBox.collapseH;
import static com.herbron.moodl.MoodlBox.expandH;
import static com.herbron.moodl.MoodlBox.getColor;
import static com.herbron.moodl.MoodlBox.numberConformer;
/**
* Created by Tiji on 12/05/2018.
*/
public class CurrencyCardview extends CardView {
public class CurrencyCardview extends CardView implements CurrencyInfoUpdateNotifierInterface {
private Currency currency;
private Activity parentActivity;
private OnClickListener detailsClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(parentActivity, CurrencyDetailsActivity.class);
intent.putExtra(getContext().getString(R.string.currency), currency);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(parentActivity, findViewById(R.id.LineChartView), "chart");
parentActivity.startActivity(intent, activityOptions.toBundle());
}
else {
parentActivity.startActivity(intent);
}
}
};
public CurrencyCardview(@NonNull Context context) {
super(context);
@ -55,7 +74,10 @@ public class CurrencyCardview extends CardView {
{
super (context);
currency.setListener(this);
this.currency = currency;
this.parentActivity = activity;
LayoutInflater.from(context).inflate(R.layout.cardview_watchlist, this, true);
@ -71,34 +93,18 @@ public class CurrencyCardview extends CardView {
if (view.findViewById(R.id.collapsableLayout).getVisibility() == View.VISIBLE) {
collapseH(view.findViewById(R.id.collapsableLayout));
} else {
view.findViewById(R.id.linearLayoutSubLayout).setVisibility(View.GONE);
view.findViewById(R.id.linearLayoutSubCharts).setVisibility(View.GONE);
view.findViewById(R.id.progressBarLinechartWatchlist).setVisibility(View.VISIBLE);
expandH(view.findViewById(R.id.collapsableLayout));
if (currency.getHistoryMinutes() == null) {
currency.updateHistoryMinutes(context, preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
if(currency.getHistoryMinutes() != null)
{
setupLineChart(currency);
view.findViewById(R.id.progressBarLinechartWatchlist).setVisibility(View.GONE);
view.findViewById(R.id.linearLayoutSubLayout).setVisibility(View.VISIBLE);
}
else
{
view.findViewById(R.id.progressBarLinechartWatchlist).setVisibility(View.GONE);
view.findViewById(R.id.linearLayoutSubLayout).setVisibility(View.VISIBLE);
view.findViewById(R.id.linearLayoutSubLayout).findViewById(R.id.detailsArrow).setVisibility(View.GONE);
}
}
});
currency.updateHistoryMinutes(context, preferencesManager.getDefaultCurrency());
}
else
{
expandH(view.findViewById(R.id.collapsableLayout));
view.findViewById(R.id.progressBarLinechartWatchlist).setVisibility(View.GONE);
view.findViewById(R.id.linearLayoutSubLayout).setVisibility(View.VISIBLE);
view.findViewById(R.id.linearLayoutSubCharts).setVisibility(View.VISIBLE);
}
}
}
@ -115,34 +121,20 @@ public class CurrencyCardview extends CardView {
}
});
findViewById(R.id.LineChartView).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(activity, CurrencyDetailsActivity.class);
intent.putExtra("currency", currency);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(activity, findViewById(R.id.LineChartView), "chart");
activity.startActivity(intent, activityOptions.toBundle());
}
else
{
activity.startActivity(intent);
}
}
});
findViewById(R.id.linearLayoutSubCharts).setOnClickListener(detailsClickListener);
findViewById(R.id.LineChartView).setOnClickListener(detailsClickListener);
updateColor(currency);
}
public CurrencyCardview(@NonNull final Context context, final Currency currency, float totalValue, boolean isBalanceHidden)
public CurrencyCardview(@NonNull final Context context, final Currency currency, Activity activity, float totalValue, boolean isBalanceHidden)
{
super(context);
currency.setListener(this);
this.currency = currency;
this.parentActivity = activity;
LayoutInflater.from(context).inflate(R.layout.cardview_currency, this, true);
@ -158,34 +150,18 @@ public class CurrencyCardview extends CardView {
if (view.findViewById(R.id.collapsableLayout).getVisibility() == View.VISIBLE) {
collapseH(view.findViewById(R.id.collapsableLayout));
} else {
view.findViewById(R.id.linearLayoutSubLayout).setVisibility(View.GONE);
view.findViewById(R.id.linearLayoutSubCharts).setVisibility(View.GONE);
view.findViewById(R.id.progressBarLinechartSummary).setVisibility(View.VISIBLE);
expandH(view.findViewById(R.id.collapsableLayout));
if (currency.getHistoryMinutes() == null) {
currency.updateHistoryMinutes(context, preferencesManager.getDefaultCurrency(), new Currency.CurrencyCallBack() {
@Override
public void onSuccess(Currency currency) {
if(currency.getHistoryMinutes() != null)
{
setupLineChart(currency);
view.findViewById(R.id.progressBarLinechartSummary).setVisibility(View.GONE);
view.findViewById(R.id.linearLayoutSubLayout).setVisibility(View.VISIBLE);
}
else
{
view.findViewById(R.id.progressBarLinechartSummary).setVisibility(View.GONE);
view.findViewById(R.id.linearLayoutSubLayout).setVisibility(View.VISIBLE);
view.findViewById(R.id.linearLayoutSubLayout).findViewById(R.id.detailsArrow).setVisibility(View.GONE);
}
}
});
currency.updateHistoryMinutes(context, preferencesManager.getDefaultCurrency());
}
else
{
expandH(view.findViewById(R.id.collapsableLayout));
view.findViewById(R.id.progressBarLinechartSummary).setVisibility(View.GONE);
view.findViewById(R.id.linearLayoutSubLayout).setVisibility(View.VISIBLE);
view.findViewById(R.id.linearLayoutSubCharts).setVisibility(View.VISIBLE);
}
}
}
@ -193,15 +169,8 @@ public class CurrencyCardview extends CardView {
updateCardViewInfos(currency, totalValue, isBalanceHidden);
findViewById(R.id.LineChartView).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), CurrencyDetailsActivity.class);
intent.putExtra(getContext().getString(R.string.currency), currency);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intent);
}
});
findViewById(R.id.linearLayoutSubCharts).setOnClickListener(detailsClickListener);
findViewById(R.id.LineChartView).setOnClickListener(detailsClickListener);
updateColor(currency);
}
@ -213,7 +182,7 @@ public class CurrencyCardview extends CardView {
private void setupCardView()
{
ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.MarginLayoutParams.MATCH_PARENT, LinearLayout.MarginLayoutParams.WRAP_CONTENT);
int margin = (int) MoodlBox.convertDpToPx(10, getResources());
layoutParams.setMargins(margin, margin, margin, 0);
@ -264,14 +233,22 @@ public class CurrencyCardview extends CardView {
.setText(PlaceholderManager.getPercentageString(numberConformer(currency.getDayFluctuationPercentage()), getContext()));
Drawable arrowDrawable = ((ImageView) findViewById(R.id.detailsArrow)).getDrawable();
arrowDrawable.mutate();
arrowDrawable.setColorFilter(new PorterDuffColorFilter(currency.getChartColor(), PorterDuff.Mode.SRC_IN));
arrowDrawable.invalidateSelf();
if(arrowDrawable != null)
{
arrowDrawable.mutate();
arrowDrawable.setColorFilter(new PorterDuffColorFilter(currency.getChartColor(), PorterDuff.Mode.SRC_IN));
arrowDrawable.invalidateSelf();
}
Drawable progressDrawable = ((ProgressBar) findViewById(R.id.progressBarLinechartWatchlist)).getIndeterminateDrawable();
progressDrawable.mutate();
progressDrawable.setColorFilter(new PorterDuffColorFilter(currency.getChartColor(), PorterDuff.Mode.SRC_IN));
progressDrawable.invalidateSelf();
if(progressDrawable != null)
{
progressDrawable.mutate();
progressDrawable.setColorFilter(new PorterDuffColorFilter(currency.getChartColor(), PorterDuff.Mode.SRC_IN));
progressDrawable.invalidateSelf();
}
}
private void updateCardViewInfos(Currency currency, float totalValue, boolean isBalanceHidden)
@ -386,4 +363,38 @@ public class CurrencyCardview extends CardView {
return transColor ;
}
@Override
public void onTimestampPriceUpdated(String price) {
}
@Override
public void onHistoryDataUpdated() {
View progressWatchlistView = findViewById(R.id.progressBarLinechartWatchlist);
View progressSummaryView = findViewById(R.id.progressBarLinechartSummary);
if(progressWatchlistView != null)
{
progressWatchlistView.setVisibility(View.GONE);
}
if(progressSummaryView != null)
{
progressSummaryView.setVisibility(View.GONE);
}
findViewById(R.id.linearLayoutSubCharts).setVisibility(View.VISIBLE);
if(currency.getHistoryMinutes() != null)
{
setupLineChart(currency);
}
}
@Override
public void onPriceUpdated(Currency currency) {
}
}

View File

@ -10,6 +10,7 @@ import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.herbron.moodl.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@ -267,35 +268,25 @@ public class CurrencyDataRetriever {
{
List<CurrencyDataChart> dataChart = new ArrayList<>();
if(response.length() > 250)
{
response = response.substring(response.indexOf("Data\":[{") + 7, response.lastIndexOf("}],\"TimeTo"));
String[] tab = response.split(Pattern.quote("},{"));
for(int i = 0; i < tab.length; i++)
try {
JSONObject mainJsonObject = new JSONObject(response);
if(mainJsonObject.getString("Response").equals("Success"))
{
JSONArray dataJsonArray = mainJsonObject.getJSONArray("Data");
if(i == 0)
for(int i = 0; i < dataJsonArray.length(); i++)
{
tab[i] = tab[i] + "}";
}
else
{
tab[i] = "{" + tab[i] + "}";
}
try {
JSONObject jsonObject = new JSONObject(tab[i]);
dataChart.add(parseJSON(jsonObject));
} catch (JSONException e) {
Log.d(context.getResources().getString(R.string.debug_volley), "API Request error: " + e + " index: " + i);
JSONObject timeJsonObject = dataJsonArray.getJSONObject(i);
dataChart.add(parseJSON(timeJsonObject));
}
}
}
else
{
dataChart = null;
else
{
dataChart = null;
}
} catch (JSONException e) {
Log.d("moodl", "API Request error : " + e);
}
return dataChart;

View File

@ -1,176 +0,0 @@
package com.herbron.moodl.DataManagers.CurrencyData;
import android.content.Context;
import android.os.StrictMode;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.herbron.moodl.DataManagers.BalanceManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Pattern;
/**
* Created by Tiji on 11/04/2018.
*/
public class CurrencyDetailsList {
final private static String DETAILURL = "https://min-api.cryptocompare.com/data/all/coinlist";
private RequestQueue requestQueue;
private LinkedHashMap<String, String> coinInfosHashmap;
private static CurrencyDetailsList INSTANCE;
private boolean upToDate;
private CurrencyDetailsList(Context context)
{
requestQueue = Volley.newRequestQueue(context);
}
public static synchronized CurrencyDetailsList getInstance(Context context)
{
if(INSTANCE == null)
{
INSTANCE = new CurrencyDetailsList(context);
}
return INSTANCE;
}
public void update(final BalanceManager.IconCallBack callBack)
{
StringRequest strRequest = new StringRequest(Request.Method.GET, DETAILURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0) {
processDetailResult(response, callBack);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(strRequest);
}
public boolean isUpToDate()
{
return upToDate;
}
private void processDetailResult(String response, final BalanceManager.IconCallBack callBack)
{
response = response.substring(response.indexOf("\"Data\"") + 7, response.lastIndexOf("},\"BaseImageUrl\""));
String[] tab = response.split(Pattern.quote("},"));
coinInfosHashmap = new LinkedHashMap<>();
for(int i = 0; i < tab.length; i++)
{
tab[i] = tab[i].substring(tab[i].indexOf("\":{")+2, tab[i].length()) + "}";
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
JSONObject jsonObject = new JSONObject(tab[i]);
switch (jsonObject.getString("Symbol"))
{
case "IOT":
coinInfosHashmap.put("MIOTA", tab[i]);
break;
case "XRB":
coinInfosHashmap.put("NANO", tab[i]);
break;
default:
coinInfosHashmap.put(jsonObject.getString("Symbol"), tab[i]);
break;
}
} catch (JSONException e) {
Log.d("moodl", "ImageUrl not found.");
}
}
sortDetails();
upToDate = true;
callBack.onSuccess();
}
private void sortDetails()
{
LinkedHashMap<String, String> sortedHashmap = new LinkedHashMap<>();
List<String> listInfos = new ArrayList<>(coinInfosHashmap.values());
List<String> listSymbols = new ArrayList<>(coinInfosHashmap.keySet());
for(int i = 0; i < coinInfosHashmap.keySet().size(); i++)
{
try {
JSONObject jsonObject = new JSONObject(listInfos.get(i));
int index = jsonObject.getInt("SortOrder");
listInfos.add(index, listInfos.get(i));
listSymbols.add(index, listSymbols.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for(int i = 0; i < listInfos.size(); i++)
{
sortedHashmap.put(listSymbols.get(i), listInfos.get(i));
}
coinInfosHashmap = sortedHashmap;
}
public LinkedHashMap<String, String> getCoinInfosHashmap() {
return coinInfosHashmap;
}
public List<String> getCurrenciesName()
{
List<String> currenciesName = new ArrayList<>();
for (String symbol : coinInfosHashmap.keySet())
{
try {
JSONObject jsonObject = new JSONObject(coinInfosHashmap.get(symbol));
currenciesName.add(jsonObject.getString("CoinName"));
} catch (JSONException e) {
e.printStackTrace();
}
}
return currenciesName;
}
public Currency getCurrencyDetailsFromSymbol(String symbol)
{
//Currency currency = new Currency();
return null;
}
public List<String> getCurrenciesSymbol()
{
return new ArrayList<>(coinInfosHashmap.keySet());
}
}

View File

@ -1,197 +0,0 @@
package com.herbron.moodl.DataManagers.CurrencyData;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.herbron.moodl.Activities.HomeActivityFragments.Overview;
import com.herbron.moodl.DataManagers.BalanceManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by Guitoune on 22/04/2018.
*/
public class CurrencyTickerList {
final private static String LISTINGURL = "https://api.coinmarketcap.com/v2/listings/";
final private static String TICKERLISTURL1 = "https://api.coinmarketcap.com/v2/ticker/?start=";
private RequestQueue requestQueue;
private List<Currency> currencyTickerList;
private static CurrencyTickerList INSTANCE;
private boolean upToDate;
private CurrencyTickerList(Context context)
{
requestQueue = Volley.newRequestQueue(context);
}
public static synchronized CurrencyTickerList getInstance(Context context)
{
if(INSTANCE == null)
{
INSTANCE = new CurrencyTickerList(context);
}
return INSTANCE;
}
public boolean isUpToDate()
{
return upToDate;
}
public void getCurrenciesFrom(int indexFrom, final String toSymbol, Overview.UpdateCallBack callBack)
{
String requetsString = TICKERLISTURL1 + indexFrom + "&limit=50&convert=" + toSymbol;
StringRequest strRequest = new StringRequest(Request.Method.GET, requetsString,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0)
{
processTickersResult(response, toSymbol, callBack);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(strRequest);
}
public void updateListing(final BalanceManager.IconCallBack callBack)
{
currencyTickerList = new ArrayList<>();
StringRequest strRequest = new StringRequest(Request.Method.GET, LISTINGURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0) {
processTickerListResult(response, callBack);
}
upToDate = true;
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
upToDate = true;
}
});
requestQueue.add(strRequest);
}
public int getTickerIdForSymbol(String symbol)
{
int tickerId = 0;
int i = 0;
while(!currencyTickerList.get(i).getSymbol().equals(symbol) && currencyTickerList.size() > i+1)
{
i++;
}
if(currencyTickerList.get(i).getSymbol().equals(symbol))
{
tickerId = currencyTickerList.get(i).getTickerId();
}
return tickerId;
}
private void processTickersResult(String response, String toSymbol, Overview.UpdateCallBack callBack)
{
List<Currency> currencyList = new ArrayList<>();
try {
JSONObject masterJsonObject = new JSONObject(response);
if(masterJsonObject.keys().hasNext())
{
JSONObject currencyJsonObject = masterJsonObject.getJSONObject(masterJsonObject.keys().next());
Iterator<?> keys = currencyJsonObject.keys();
while(keys.hasNext())
{
String key = keys.next().toString();
JSONObject subCurrencyJsonObject = currencyJsonObject.getJSONObject(key);
Currency newCurrency = new Currency(subCurrencyJsonObject.getString("name"), subCurrencyJsonObject.getString("symbol"), subCurrencyJsonObject.getInt("id"));
newCurrency.setRank(subCurrencyJsonObject.getInt("rank"));
JSONObject quoteJsonObject = subCurrencyJsonObject.getJSONObject("quotes");
JSONObject symJsonObject = quoteJsonObject.getJSONObject(toSymbol);
newCurrency.setValue(symJsonObject.getDouble("price"));
newCurrency.setDayFluctuationPercentage((float) symJsonObject.getDouble("percent_change_24h"));
newCurrency.setDayFluctuation(newCurrency.getDayFluctuationPercentage() * newCurrency.getValue() / 100);
currencyList.add(newCurrency);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
callBack.onSuccess(currencyList);
}
public void processTickerListResult(String response, BalanceManager.IconCallBack callBack)
{
try {
JSONObject dataJsonObject = new JSONObject(response);
JSONArray dataJsonArray = dataJsonObject.getJSONArray("data");
for(int i = 0; i < dataJsonArray.length(); i++)
{
JSONObject currencyJsonObject = dataJsonArray.getJSONObject(i);
currencyTickerList.add(new Currency(currencyJsonObject.getString("name"), currencyJsonObject.getString("symbol"), currencyJsonObject.getInt("id")));
}
} catch (JSONException e) {
e.printStackTrace();
}
/*response = response.substring(16, response.length() - 2);
String[] strTable = response.split(Pattern.quote("},"));
for(int i = 0; i < strTable.length; i++)
{
strTable[i] += "}";
Log.d("moodl", "TICKER " + i + " " + strTable[i]);
try {
JSONObject jsonObject = new JSONObject(strTable[i]);
Log.d("moodl", "TICKER JSON " + i + " " + jsonObject);
switch (jsonObject.getString("symbol"))
{
case "MIOTA":
coinTickersHashmap.put("IOT", strTable[i]);
break;
case "NANO":
coinTickersHashmap.put("XRB", strTable[i]);
break;
default:
coinTickersHashmap.put(jsonObject.getString("symbol"), strTable[i]);
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
callBack.onSuccess();
}
}

View File

@ -10,18 +10,33 @@ public class Transaction {
private String symbol;
private double amount;
private long timestamp;
private double purchasedPrice;
private double price;
private double fees;
private boolean isMined;
private String feeCurrency;
private String feeFormat;
private String note;
private String symPair;
private String source;
private String destination;
private String type;
private boolean isDeducted;
public Transaction(int transactionId, String symbol, double amount, long timestamp, double purchasedPrice, double fees)
public Transaction(int transactionId, String symbol, String symPair, double amount, long timestamp, double purchasedPrice, double fees, String note, String feeCurrency, String source, String destination, String type, String feeFormat, boolean isDeducted)
{
this.transactionId = transactionId;
this.symbol = symbol;
this.symPair = symPair;
this.amount = amount;
this.timestamp = timestamp;
this.purchasedPrice = purchasedPrice;
this.price = purchasedPrice;
this.fees = fees;
this.note = note;
this.feeCurrency = feeCurrency;
this.source = source;
this.destination = destination;
this.type = type;
this.feeFormat = feeFormat;
this.isDeducted = isDeducted;
}
public int getTransactionId() {
@ -53,14 +68,14 @@ public class Transaction {
this.amount = amount;
}
public void setPurchasedPrice(double purchasedPrice)
public void setPrice(double purchasedPrice)
{
this.purchasedPrice = purchasedPrice;
this.price = purchasedPrice;
}
public double getPurchasedPrice()
public double getPrice()
{
return purchasedPrice;
return price;
}
public double getFees() {
@ -70,4 +85,72 @@ public class Transaction {
public void setFees(double fees) {
this.fees = fees;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getSymPair() {
return symPair;
}
public void setSymPair(String symPair) {
this.symPair = symPair;
}
public String getFeeCurrency() {
return feeCurrency;
}
public void setFeeCurrency(String feeCurrency) {
this.feeCurrency = feeCurrency;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFeeFormat() {
return feeFormat;
}
public void setFeeFormat(String feeFormat) {
this.feeFormat = feeFormat;
}
public boolean isDeducted() {
return isDeducted;
}
public void setDeducted(boolean deducted) {
isDeducted = deducted;
}
}

View File

@ -3,20 +3,28 @@ package com.herbron.moodl.DataManagers;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.herbron.moodl.Activities.RecordTransactionFragments.TransferFragment;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.CurrencyData.Transaction;
import com.herbron.moodl.DataManagers.ExchangeManager.BinanceManager;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import com.herbron.moodl.DataManagers.ExchangeManager.HitBtcManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by Guitoune on 14/01/2018.
@ -24,34 +32,45 @@ import java.util.List;
public class DatabaseManager extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 7;
private static final int DATABASE_VERSION = 17;
private static final String DATABASE_NAME = "Currencies.db";
private static final String DATABASE_NAME = "mdn.db";
public static final String TABLE_MANUAL_CURRENCIES = "ManualCurrencies";
public static final String TABLE_MANUAL_TRANSACTIONS = "ManualTransactions";
public static final String TABLE_EXCHANGE_KEYS = "ExchangeKeys";
public static final String TABLE_WATCHLIST = "Watchlist";
private static final String KEY_CURRENCY_ID = "idCurrency";
private static final String KEY_CURRENCY_SYMBOL = "symbol";
private static final String KEY_CURRENCY_NAME = "name";
private static final String KEY_CURRENCY_BALANCE = "balance";
private static final String KEY_CURRENCY_DATE = "addDate";
private static final String KEY_CURRENCY_PURCHASED_PRICE = "purchasedPrice";
private static final String KEY_CURRENCY_IS_MINED = "isMined";
private static final String KEY_CURRENCY_FEES = "fees";
private static final String KEY_TRANSACTION_ID = "transactionId";
private static final String KEY_TRANSACTION_SYMBOL = "symbol";
private static final String KEY_TRANSACTION_AMOUNT = "amount";
private static final String KEY_TRANSACTION_PAIR = "symPair";
private static final String KEY_TRANSACTION_DATE = "transactionDate";
private static final String KEY_TRANSACTION_PURCHASE_PRICE = "purchasePrice";
private static final String KEY_TRANSACTION_SOURCE = "source";
private static final String KEY_TRANSACTION_DESTINATION = "destination";
private static final String KEY_TRANSACTION_FEES = "fees";
private static final String KEY_TRANSACTION_FEE_CURRENCY = "feeCurrency";
private static final String KEY_TRANSACTION_FEE_FORMAT = "feeFormat";
private static final String KEY_TRANSACTION_NOTES = "notes";
private static final String KEY_TRANSACTION_TYPE = "transactionType";
private static final String KEY_TRANSACTION_DEDUCT = "deductHoldings";
private static final String KEY_EXCHANGE_ID = "idExchange";
private static final String KEY_EXCHANGE_NAME = "name";
private static final String KEY_EXCHANGE_TYPE = "type";
private static final String KEY_EXCHANGE_DESCRIPTION = "description";
private static final String KEY_EXCHANGE_PUBLIC_KEY = "publicKey";
private static final String KEY_EXCHANGE_SECRET_KEY = "secretKey";
private static final String KEY_EXCHANGE_IS_ENABLED = "enabled";
private static final String KEY_WATCHLIST_ID = "idWatchlist";
private static final String KEY_WATCHLIST_SYMBOL = "symbol";
private static final String KEY_WATCHLIST_NAME = "name";
private static final String KEY_WATCHLIST_POSITION = "position";
public static final int BINANCE_TYPE = 0;
public static final int HITBTC_TYPE = 1;
public DatabaseManager(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
@ -60,23 +79,31 @@ public class DatabaseManager extends SQLiteOpenHelper{
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_MANUAL_CURRENCIES + "("
+ KEY_CURRENCY_ID + " INTEGER PRIMARY KEY,"
+ KEY_CURRENCY_SYMBOL + " VARCHAR(4),"
+ KEY_CURRENCY_NAME + " VARCHAR(45),"
+ KEY_CURRENCY_BALANCE + " TEXT,"
+ KEY_CURRENCY_DATE + " TEXT,"
+ KEY_CURRENCY_PURCHASED_PRICE + " REAL,"
+ KEY_CURRENCY_IS_MINED + " INTEGER,"
+ KEY_CURRENCY_FEES + " REAL"
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_MANUAL_TRANSACTIONS + "("
+ KEY_TRANSACTION_ID + " INTEGER PRIMARY KEY,"
+ KEY_TRANSACTION_SYMBOL + " VARCHAR(4),"
+ KEY_TRANSACTION_AMOUNT + " TEXT,"
+ KEY_TRANSACTION_DATE + " TEXT,"
+ KEY_TRANSACTION_PURCHASE_PRICE + " REAL,"
+ KEY_TRANSACTION_NOTES + " TEXT,"
+ KEY_TRANSACTION_PAIR + " VARCHAR(4),"
+ KEY_TRANSACTION_FEE_CURRENCY + " VARCHAR(4),"
+ KEY_TRANSACTION_FEES + " REAL,"
+ KEY_TRANSACTION_FEE_FORMAT + " VARCHAR(1),"
+ KEY_TRANSACTION_SOURCE + " TEXT,"
+ KEY_TRANSACTION_DESTINATION + " TEXT,"
+ KEY_TRANSACTION_TYPE + " VARCHAR(1),"
+ KEY_TRANSACTION_DEDUCT + " INTEGER"
+ ");");
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_EXCHANGE_KEYS + "("
+ KEY_EXCHANGE_ID + " INTEGER PRIMARY KEY,"
+ KEY_EXCHANGE_NAME + " TEXT,"
+ KEY_EXCHANGE_TYPE + " INTEGER,"
+ KEY_EXCHANGE_DESCRIPTION + " TEXT,"
+ KEY_EXCHANGE_PUBLIC_KEY + " TEXT,"
+ KEY_EXCHANGE_SECRET_KEY + " TEXT"
+ KEY_EXCHANGE_SECRET_KEY + " TEXT,"
+ KEY_EXCHANGE_IS_ENABLED + " INTEGER"
+ ");");
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_WATCHLIST + "("
@ -92,12 +119,11 @@ public class DatabaseManager extends SQLiteOpenHelper{
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
switch (oldVersion)
{
case 6:
db.execSQL("ALTER TABLE " + TABLE_EXCHANGE_KEYS
+ " ADD " + KEY_EXCHANGE_DESCRIPTION+ " VARCHAR");
}
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MANUAL_TRANSACTIONS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EXCHANGE_KEYS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WATCHLIST);
onCreate(db);
}
private boolean isCurrencyInWatchlist(String symbol)
@ -131,6 +157,51 @@ public class DatabaseManager extends SQLiteOpenHelper{
return false;
}
public void updateTransactionWithId(int transactionId, double amount, Date date, double purchasedPrice, double fees, String note, String symbolFrom, String feeCurrency, String destination, String source, String type, String feeFormat, boolean deductFromHoldings)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_TRANSACTION_AMOUNT, amount);
cv.put(KEY_TRANSACTION_DATE, date.getTime());
cv.put(KEY_TRANSACTION_PURCHASE_PRICE, purchasedPrice);
cv.put(KEY_TRANSACTION_FEES, fees);
cv.put(KEY_TRANSACTION_NOTES, note);
cv.put(KEY_TRANSACTION_PAIR, symbolFrom);
cv.put(KEY_TRANSACTION_FEE_CURRENCY, feeCurrency);
cv.put(KEY_TRANSACTION_SOURCE, source);
cv.put(KEY_TRANSACTION_DESTINATION, destination);
cv.put(KEY_TRANSACTION_TYPE, type);
cv.put(KEY_TRANSACTION_FEE_FORMAT, feeFormat);
cv.put(KEY_TRANSACTION_DEDUCT, deductFromHoldings ? 1 : 0);
db.update(TABLE_MANUAL_TRANSACTIONS, cv, KEY_TRANSACTION_ID + "=" + transactionId, null);
}
public void addTransaction(String symbol, Double amount, Date date, double purchasePrice, double fees, String note, String symbolFrom, String feeCurrency, String destination, String source, String type, String feeFormat, boolean deductFromHoldings)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TRANSACTION_SYMBOL, symbol);
values.put(KEY_TRANSACTION_AMOUNT, amount);
values.put(KEY_TRANSACTION_DATE, date.getTime());
values.put(KEY_TRANSACTION_PURCHASE_PRICE, purchasePrice);
values.put(KEY_TRANSACTION_FEES, fees);
values.put(KEY_TRANSACTION_NOTES, note);
values.put(KEY_TRANSACTION_PAIR, symbolFrom);
values.put(KEY_TRANSACTION_FEE_CURRENCY, feeCurrency);
values.put(KEY_TRANSACTION_SOURCE, source);
values.put(KEY_TRANSACTION_DESTINATION, destination);
values.put(KEY_TRANSACTION_TYPE, type);
values.put(KEY_TRANSACTION_FEE_FORMAT, feeFormat);
values.put(KEY_TRANSACTION_DEDUCT, deductFromHoldings ? 1 : 0);
db.insert(TABLE_MANUAL_TRANSACTIONS, null, values);
db.close();
}
public void updateWatchlistPosition(String symbol, int position)
{
SQLiteDatabase db = this.getWritableDatabase();
@ -139,7 +210,6 @@ public class DatabaseManager extends SQLiteOpenHelper{
cv.put(KEY_WATCHLIST_POSITION, position);
db.update(TABLE_WATCHLIST, cv, KEY_WATCHLIST_SYMBOL + "='" + symbol + "'", null);
}
private int getWatchlistRowCount(SQLiteDatabase db)
@ -152,6 +222,25 @@ public class DatabaseManager extends SQLiteOpenHelper{
return result.getInt(0);
}
public int getDisabledExchangeAccountsNumber()
{
SQLiteDatabase db = this.getWritableDatabase();
String countQuerry = "SELECT COUNT() FROM " + TABLE_EXCHANGE_KEYS + " WHERE " + KEY_EXCHANGE_IS_ENABLED + "=0";
Cursor result = db.rawQuery(countQuerry, null);
result.moveToFirst();
return result.getInt(0);
}
public void deleteExchangeAccountFromId(int id)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_EXCHANGE_KEYS, KEY_EXCHANGE_ID + " = " + id, null);
db.close();
}
public void deleteCurrencyFromWatchlist(String symbol)
{
SQLiteDatabase db = this.getWritableDatabase();
@ -160,6 +249,76 @@ public class DatabaseManager extends SQLiteOpenHelper{
db.close();
}
public void disableExchangeAccount(int id)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_EXCHANGE_IS_ENABLED, 0);
db.update(TABLE_EXCHANGE_KEYS, cv, KEY_EXCHANGE_ID + "='" + id + "'", null);
}
public Exchange getExchangeFromId(int exchangeId)
{
String selectQuerry = "SELECT * FROM " + TABLE_EXCHANGE_KEYS + " WHERE " + KEY_EXCHANGE_ID + " = " + exchangeId;
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery(selectQuerry, null);
Exchange selectedExchange = null;
if(result.moveToFirst())
{
selectedExchange = new Exchange(result.getInt(result.getColumnIndex(KEY_EXCHANGE_ID))
, result.getString(result.getColumnIndex(KEY_EXCHANGE_NAME))
, result.getInt(result.getColumnIndex(KEY_EXCHANGE_TYPE))
, result.getString(result.getColumnIndex(KEY_EXCHANGE_DESCRIPTION))
, result.getString(result.getColumnIndex(KEY_EXCHANGE_PUBLIC_KEY))
, result.getString(result.getColumnIndex(KEY_EXCHANGE_SECRET_KEY))
, (result.getInt(result.getColumnIndex(KEY_EXCHANGE_IS_ENABLED)) == 1));
}
return selectedExchange;
}
public ArrayList<Exchange> getExchanges()
{
String selectQuerry = "SELECT * FROM " + TABLE_EXCHANGE_KEYS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery(selectQuerry, null);
ArrayList<Exchange> exchanges = new ArrayList<>();
while(result.moveToNext())
{
exchanges.add(new Exchange(result.getInt(result.getColumnIndex(KEY_EXCHANGE_ID))
, result.getString(result.getColumnIndex(KEY_EXCHANGE_NAME))
, result.getInt(result.getColumnIndex(KEY_EXCHANGE_TYPE))
, result.getString(result.getColumnIndex(KEY_EXCHANGE_DESCRIPTION))
, result.getString(result.getColumnIndex(KEY_EXCHANGE_PUBLIC_KEY))
, result.getString(result.getColumnIndex(KEY_EXCHANGE_SECRET_KEY))
, (result.getInt(result.getColumnIndex(KEY_EXCHANGE_IS_ENABLED)) == 1)));
}
return exchanges;
}
public void addExchange(String name, int type, String description, String publicKey, String privateKey)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EXCHANGE_NAME, name);
values.put(KEY_EXCHANGE_TYPE, type);
values.put(KEY_EXCHANGE_DESCRIPTION, description);
values.put(KEY_EXCHANGE_PUBLIC_KEY, publicKey);
values.put(KEY_EXCHANGE_SECRET_KEY, privateKey);
values.put(KEY_EXCHANGE_IS_ENABLED, 1);
db.insert(TABLE_EXCHANGE_KEYS, null, values);
db.close();
}
public JSONArray getDatabaseBackup(Context context, String table, boolean encryptData)
{
String selectQuerry = "SELECT * FROM " + table;
@ -198,6 +357,9 @@ public class DatabaseManager extends SQLiteOpenHelper{
backupArray.put(backupObject);
}
result.close();
db.close();
return backupArray;
}
@ -207,6 +369,66 @@ public class DatabaseManager extends SQLiteOpenHelper{
db.execSQL("DELETE FROM "+ table);
}
public void addRawData(Context context, JSONObject rawValues, String table, boolean decrypt)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
while(rawValues.keys().hasNext())
{
String key = rawValues.keys().next();
try {
if(decrypt)
{
values.put(key, DataCrypter.decrypt(context, rawValues.getString(key)));
}
else
{
values.put(key, rawValues.getString(key));
}
} catch (JSONException e) {
Log.d("moodl", "Error while inserting " + key + " " + e.getMessage());
}
}
db.insert(table, null, values);
db.close();
}
public void addRowApiKeys(JSONObject rawValues, Context context, boolean decrypt)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
try {
if(decrypt)
{
values.put(KEY_EXCHANGE_NAME, DataCrypter.decrypt(context, rawValues.getString(KEY_EXCHANGE_NAME)));
values.put(KEY_EXCHANGE_TYPE, DataCrypter.decrypt(context, rawValues.getString(KEY_EXCHANGE_TYPE)));
values.put(KEY_EXCHANGE_DESCRIPTION, DataCrypter.decrypt(context, rawValues.getString(KEY_EXCHANGE_DESCRIPTION)));
values.put(KEY_EXCHANGE_PUBLIC_KEY, DataCrypter.decrypt(context, rawValues.getString(KEY_EXCHANGE_PUBLIC_KEY)));
values.put(KEY_EXCHANGE_SECRET_KEY, DataCrypter.decrypt(context, rawValues.getString(KEY_EXCHANGE_SECRET_KEY)));
values.put(KEY_EXCHANGE_IS_ENABLED, DataCrypter.decrypt(context, rawValues.getString(KEY_EXCHANGE_IS_ENABLED)));
}
else
{
values.put(KEY_EXCHANGE_NAME, rawValues.getString(KEY_EXCHANGE_NAME));
values.put(KEY_EXCHANGE_TYPE, rawValues.getString(KEY_EXCHANGE_TYPE));
values.put(KEY_EXCHANGE_DESCRIPTION, rawValues.getString(KEY_EXCHANGE_DESCRIPTION));
values.put(KEY_EXCHANGE_PUBLIC_KEY, rawValues.getString(KEY_EXCHANGE_PUBLIC_KEY));
values.put(KEY_EXCHANGE_SECRET_KEY, rawValues.getString(KEY_EXCHANGE_SECRET_KEY));
values.put(KEY_EXCHANGE_IS_ENABLED, rawValues.getString(KEY_EXCHANGE_IS_ENABLED));
}
} catch (JSONException e) {
Log.d("moodl", "Error while inserting api key " + e.getMessage());
}
db.insert(TABLE_EXCHANGE_KEYS, null, values);
db.close();
}
public void addRowWatchlist(JSONObject rawValues, Context context, boolean decrypt)
{
SQLiteDatabase db = this.getWritableDatabase();
@ -226,10 +448,10 @@ public class DatabaseManager extends SQLiteOpenHelper{
values.put(KEY_WATCHLIST_POSITION, rawValues.getString(KEY_WATCHLIST_POSITION));
}
} catch (JSONException e) {
Log.d("moodl", "Error while inserting transaction");
Log.d("moodl", "Error while inserting watchlist " + e.getMessage());
}
db.insert(TABLE_MANUAL_CURRENCIES, null, values);
db.insert(TABLE_WATCHLIST, null, values);
db.close();
}
@ -241,29 +463,43 @@ public class DatabaseManager extends SQLiteOpenHelper{
try {
if(decrypt)
{
values.put(KEY_CURRENCY_SYMBOL, DataCrypter.decrypt(context, rawValues.getString(KEY_CURRENCY_SYMBOL)));
values.put(KEY_CURRENCY_NAME, DataCrypter.decrypt(context, rawValues.getString(KEY_CURRENCY_NAME)));
values.put(KEY_CURRENCY_BALANCE, DataCrypter.decrypt(context, rawValues.getString(KEY_CURRENCY_BALANCE)));
values.put(KEY_CURRENCY_DATE, DataCrypter.decrypt(context, rawValues.getString(KEY_CURRENCY_DATE)));
values.put(KEY_CURRENCY_PURCHASED_PRICE, DataCrypter.decrypt(context, rawValues.getString(KEY_CURRENCY_PURCHASED_PRICE)));
values.put(KEY_CURRENCY_IS_MINED, DataCrypter.decrypt(context, rawValues.getString(KEY_CURRENCY_IS_MINED)));
values.put(KEY_CURRENCY_FEES, DataCrypter.decrypt(context, rawValues.getString(KEY_CURRENCY_FEES)));
values.put(KEY_TRANSACTION_SYMBOL, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_SYMBOL)));
values.put(KEY_TRANSACTION_AMOUNT, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_AMOUNT)));
values.put(KEY_TRANSACTION_DATE, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_DATE)));
values.put(KEY_TRANSACTION_PURCHASE_PRICE, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_PURCHASE_PRICE)));
values.put(KEY_TRANSACTION_FEES, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_FEES)));
values.put(KEY_TRANSACTION_NOTES, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_NOTES)));
values.put(KEY_TRANSACTION_PAIR, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_PAIR)));
values.put(KEY_TRANSACTION_FEE_CURRENCY, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_FEE_CURRENCY)));
values.put(KEY_TRANSACTION_SOURCE, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_SOURCE)));
values.put(KEY_TRANSACTION_DESTINATION, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_DESTINATION)));
values.put(KEY_TRANSACTION_TYPE, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_TYPE)));
values.put(KEY_TRANSACTION_FEE_FORMAT, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_FEE_FORMAT)));
values.put(KEY_TRANSACTION_DEDUCT, DataCrypter.decrypt(context, rawValues.getString(KEY_TRANSACTION_DEDUCT)));
}
else
{
values.put(KEY_CURRENCY_SYMBOL, rawValues.getString(KEY_CURRENCY_SYMBOL));
values.put(KEY_CURRENCY_NAME, rawValues.getString(KEY_CURRENCY_NAME));
values.put(KEY_CURRENCY_BALANCE, rawValues.getString(KEY_CURRENCY_BALANCE));
values.put(KEY_CURRENCY_DATE, rawValues.getString(KEY_CURRENCY_DATE));
values.put(KEY_CURRENCY_PURCHASED_PRICE, rawValues.getString(KEY_CURRENCY_PURCHASED_PRICE));
values.put(KEY_CURRENCY_IS_MINED, rawValues.getString(KEY_CURRENCY_IS_MINED));
values.put(KEY_CURRENCY_FEES, rawValues.getString(KEY_CURRENCY_FEES));
values.put(KEY_TRANSACTION_SYMBOL, rawValues.getString(KEY_TRANSACTION_SYMBOL));
values.put(KEY_TRANSACTION_AMOUNT, rawValues.getString(KEY_TRANSACTION_AMOUNT));
values.put(KEY_TRANSACTION_DATE, rawValues.getString(KEY_TRANSACTION_DATE));
values.put(KEY_TRANSACTION_PURCHASE_PRICE, rawValues.getDouble(KEY_TRANSACTION_PURCHASE_PRICE));
values.put(KEY_TRANSACTION_FEES, rawValues.getDouble(KEY_TRANSACTION_FEES));
values.put(KEY_TRANSACTION_NOTES, rawValues.getString(KEY_TRANSACTION_NOTES));
values.put(KEY_TRANSACTION_PAIR, rawValues.getString(KEY_TRANSACTION_PAIR));
values.put(KEY_TRANSACTION_FEE_CURRENCY, rawValues.getString(KEY_TRANSACTION_FEE_CURRENCY));
values.put(KEY_TRANSACTION_SOURCE, rawValues.getString(KEY_TRANSACTION_SOURCE));
values.put(KEY_TRANSACTION_DESTINATION, rawValues.getString(KEY_TRANSACTION_DESTINATION));
values.put(KEY_TRANSACTION_TYPE, rawValues.getString(KEY_TRANSACTION_TYPE));
values.put(KEY_TRANSACTION_FEE_FORMAT, rawValues.getString(KEY_TRANSACTION_FEE_FORMAT));
values.put(KEY_TRANSACTION_DEDUCT, rawValues.getInt(KEY_TRANSACTION_DEDUCT));
}
} catch (JSONException e) {
Log.d("moodl", "Error while inserting transaction");
Log.d("moodl", "Error while inserting transaction " + e.getMessage());
}
db.insert(TABLE_MANUAL_CURRENCIES, null, values);
Log.d("mood", "Raw " + rawValues.toString());
db.insert(TABLE_MANUAL_TRANSACTIONS, null, values);
db.close();
}
@ -277,30 +513,70 @@ public class DatabaseManager extends SQLiteOpenHelper{
while(resultList.moveToNext())
{
currencyList.add(new Currency(resultList.getString(2), resultList.getString(1)));
currencyList.add(new Currency(resultList.getString(resultList.getColumnIndex(KEY_WATCHLIST_NAME)), resultList.getString(resultList.getColumnIndex(KEY_WATCHLIST_SYMBOL))));
}
resultList.close();
db.close();
return currencyList;
}
public void addCurrencyToManualCurrency(String symbol, double balance, Date date, double purchasedPrice, double fees)
public List<HitBtcManager> getHitBtcAccounts(Context context)
{
String searchQuerry = "SELECT * FROM " + TABLE_EXCHANGE_KEYS + " WHERE " + KEY_EXCHANGE_TYPE + " = " + HITBTC_TYPE + " AND " + KEY_EXCHANGE_IS_ENABLED + " = 1";
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
Cursor resultList = db.rawQuery(searchQuerry, null);
values.put(KEY_CURRENCY_SYMBOL, symbol);
values.put(KEY_CURRENCY_BALANCE, balance);
values.put(KEY_CURRENCY_DATE, date.getTime());
values.put(KEY_CURRENCY_PURCHASED_PRICE, purchasedPrice);
values.put(KEY_CURRENCY_FEES, fees);
List<HitBtcManager> accountList = new ArrayList<>();
db.insert(TABLE_MANUAL_CURRENCIES, null, values);
while(resultList.moveToNext())
{
Exchange exchange = new Exchange(resultList.getInt(resultList.getColumnIndex(KEY_EXCHANGE_ID))
, resultList.getString(resultList.getColumnIndex(KEY_EXCHANGE_NAME))
, resultList.getInt(resultList.getColumnIndex(KEY_EXCHANGE_TYPE))
, resultList.getString(resultList.getColumnIndex(KEY_EXCHANGE_DESCRIPTION))
, resultList.getString(resultList.getColumnIndex(KEY_EXCHANGE_PUBLIC_KEY))
, resultList.getString(resultList.getColumnIndex(KEY_EXCHANGE_SECRET_KEY))
, (resultList.getInt(resultList.getColumnIndex(KEY_EXCHANGE_IS_ENABLED)) == 1));
accountList.add(new HitBtcManager(context, exchange));
}
resultList.close();
db.close();
return accountList;
}
public List<Currency> getAllCurrenciesFromManualCurrency()
public List<BinanceManager> getBinanceAccounts()
{
String searchQuerry = "SELECT * FROM " + TABLE_MANUAL_CURRENCIES;
String searchQuerry = "SELECT * FROM " + TABLE_EXCHANGE_KEYS + " WHERE " + KEY_EXCHANGE_TYPE + " = " + BINANCE_TYPE + " AND " + KEY_EXCHANGE_IS_ENABLED + " = 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor resultList = db.rawQuery(searchQuerry, null);
List<BinanceManager> accountList = new ArrayList<>();
while(resultList.moveToNext())
{
Exchange exchange = new Exchange(resultList.getInt(resultList.getColumnIndex(KEY_EXCHANGE_ID))
, resultList.getString(resultList.getColumnIndex(KEY_EXCHANGE_NAME))
, resultList.getInt(resultList.getColumnIndex(KEY_EXCHANGE_TYPE))
, resultList.getString(resultList.getColumnIndex(KEY_EXCHANGE_DESCRIPTION))
, resultList.getString(resultList.getColumnIndex(KEY_EXCHANGE_PUBLIC_KEY))
, resultList.getString(resultList.getColumnIndex(KEY_EXCHANGE_SECRET_KEY))
, (resultList.getInt(resultList.getColumnIndex(KEY_EXCHANGE_IS_ENABLED)) == 1));
accountList.add(new BinanceManager(exchange));
}
resultList.close();
db.close();
return accountList;
}
public List<Currency> getAllCurrenciesFromTransactions()
{
String searchQuerry = "SELECT * FROM " + TABLE_MANUAL_TRANSACTIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor resultatList = db.rawQuery(searchQuerry, null);
@ -308,7 +584,87 @@ public class DatabaseManager extends SQLiteOpenHelper{
while(resultatList.moveToNext())
{
currencyList.add(new Currency(resultatList.getString(1), resultatList.getDouble(3) - resultatList.getDouble(7)));
String symbol = resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL));
String feeSym = resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_FEE_CURRENCY));
String type = resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_TYPE));
if(type != null && !type.equals(""))
{
switch (type)
{
case "b":
if(symbol.equals(feeSym))
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT)) - resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))));
}
else
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT))));
}
break;
case "s":
if(symbol.equals(feeSym))
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, -resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT)) - resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))));
}
else
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, -resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT))));
}
break;
case "t":
if(isBalanceRelated(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SOURCE))) && isBalanceRelated(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_DESTINATION))))
{
if(!resultatList.isNull(resultatList.getColumnIndex(KEY_TRANSACTION_DEDUCT)))
{
if(resultatList.getInt(resultatList.getColumnIndex(KEY_TRANSACTION_DEDUCT)) == 1)
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, -resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT)) - resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))));
}
else
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, -resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))));
}
}
}
else
{
if(isBalanceRelated(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SOURCE))))
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, -resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT)) - resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))));
}
else
{
if(isBalanceRelated(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_DESTINATION))))
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT)) - resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))));
}
}
}
break;
}
}
else
{
if(symbol.equals(feeSym))
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT)) - resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))));
}
else
{
currencyList.add(new Currency(resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT))));
}
}
}
resultatList.close();
@ -318,23 +674,15 @@ public class DatabaseManager extends SQLiteOpenHelper{
return currencyList;
}
public void updateTransactionWithId(int transactionId, double amount, Date time, double purchasedPrice, double fees)
private boolean isBalanceRelated(String str)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_CURRENCY_BALANCE, amount);
cv.put(KEY_CURRENCY_DATE, time.getTime());
cv.put(KEY_CURRENCY_PURCHASED_PRICE, purchasedPrice);
cv.put(KEY_CURRENCY_FEES, fees);
db.update(TABLE_MANUAL_CURRENCIES, cv, KEY_CURRENCY_ID + "=" + transactionId, null);
Set<String> set = new HashSet<>(Arrays.asList(TransferFragment.EXCHANGE_CODE, TransferFragment.WALLET_CODE));
return set.contains(str);
}
public Transaction getCurrencyTransactionById(int id)
{
String searchQuerry = "SELECT * FROM " + TABLE_MANUAL_CURRENCIES + " WHERE " + KEY_CURRENCY_ID + "='" + id + "'";
String searchQuerry = "SELECT * FROM " + TABLE_MANUAL_TRANSACTIONS + " WHERE " + KEY_TRANSACTION_ID + "='" + id + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor resultatList = db.rawQuery(searchQuerry, null);
@ -342,9 +690,33 @@ public class DatabaseManager extends SQLiteOpenHelper{
if(resultatList.moveToFirst())
{
transaction = new Transaction(resultatList.getInt(0), resultatList.getString(1), resultatList.getDouble(3), resultatList.getLong(4), resultatList.getLong(5), resultatList.getDouble(7));
boolean deduct = false;
if(!resultatList.isNull(resultatList.getColumnIndex(KEY_TRANSACTION_DEDUCT)))
{
deduct = resultatList.getInt(resultatList.getColumnIndex(KEY_TRANSACTION_DEDUCT)) == 1;
}
Log.d("moodl", "> " + resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_TYPE)));
transaction = new Transaction(resultatList.getInt(resultatList.getColumnIndex(KEY_TRANSACTION_ID))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_PAIR))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT))
, resultatList.getLong(resultatList.getColumnIndex(KEY_TRANSACTION_DATE))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_PURCHASE_PRICE))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_NOTES))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_FEE_CURRENCY))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SOURCE))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_DESTINATION))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_TYPE))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_FEE_FORMAT))
, deduct);
}
Log.d("moodl", "> " + DatabaseUtils.dumpCurrentRowToString(resultatList));
resultatList.close();
db.close();
@ -354,7 +726,7 @@ public class DatabaseManager extends SQLiteOpenHelper{
public ArrayList<Transaction> getCurrencyTransactionsForSymbol(String symbol)
{
String searchQuerry = "SELECT * FROM " + TABLE_MANUAL_CURRENCIES + " WHERE " + KEY_CURRENCY_SYMBOL + "='" + symbol.toUpperCase() + "'";
String searchQuerry = "SELECT * FROM " + TABLE_MANUAL_TRANSACTIONS + " WHERE " + KEY_TRANSACTION_SYMBOL + "='" + symbol.toUpperCase() + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor resultatList = db.rawQuery(searchQuerry, null);
@ -362,7 +734,27 @@ public class DatabaseManager extends SQLiteOpenHelper{
while (resultatList.moveToNext())
{
transactionList.add(new Transaction(resultatList.getInt(0), resultatList.getString(1), resultatList.getDouble(3), resultatList.getLong(4), resultatList.getLong(5), resultatList.getDouble(7)));
boolean deduct = false;
if(!resultatList.isNull(resultatList.getColumnIndex(KEY_TRANSACTION_DEDUCT)))
{
deduct = resultatList.getInt(resultatList.getColumnIndex(KEY_TRANSACTION_DEDUCT)) == 1;
}
transactionList.add(new Transaction(resultatList.getInt(resultatList.getColumnIndex(KEY_TRANSACTION_ID))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SYMBOL))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_PAIR))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_AMOUNT))
, resultatList.getLong(resultatList.getColumnIndex(KEY_TRANSACTION_DATE))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_PURCHASE_PRICE))
, resultatList.getDouble(resultatList.getColumnIndex(KEY_TRANSACTION_FEES))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_NOTES))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_FEE_CURRENCY))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_SOURCE))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_DESTINATION))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_TYPE))
, resultatList.getString(resultatList.getColumnIndex(KEY_TRANSACTION_FEE_FORMAT))
, deduct));
}
resultatList.close();
@ -376,7 +768,7 @@ public class DatabaseManager extends SQLiteOpenHelper{
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MANUAL_CURRENCIES, KEY_CURRENCY_ID + "=" + id, null);
db.delete(TABLE_MANUAL_TRANSACTIONS, KEY_TRANSACTION_ID + "=" + id, null);
db.close();
}

View File

@ -1,13 +1,12 @@
package com.herbron.moodl.DataManagers.ExchangeManager;
import android.util.Log;
import com.binance.api.client.BinanceApiClientFactory;
import com.binance.api.client.BinanceApiRestClient;
import com.binance.api.client.domain.account.Account;
import com.binance.api.client.domain.account.AssetBalance;
import com.binance.api.client.domain.account.Trade;
import com.binance.api.client.exception.BinanceApiException;
import com.herbron.moodl.DataNotifiers.BinanceUpdateNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import java.util.ArrayList;
@ -17,23 +16,31 @@ import java.util.List;
* Created by Guitoune on 26/02/2018.
*/
public class BinanceManager {
private String publicKey;
private String privateKey;
public class BinanceManager extends Exchange {
private List<Currency> balance;
private ArrayList<com.herbron.moodl.DataManagers.CurrencyData.Trade> trades;
private List<String> pairSymbolList;
private static List<String> pairSymbolList;
public BinanceManager(String publicKey, String privateKey)
private List<BinanceUpdateNotifierInterface> binanceUpdateNotifierInterfaceList;
public BinanceManager(Exchange exchange)
{
this.publicKey = publicKey;
this.privateKey = privateKey;
super(exchange.id, exchange.name, exchange.type, exchange.description, exchange.publicKey, exchange.privateKey, exchange.isEnabled);
createPairSymbolList();
}
public void addListener(BinanceUpdateNotifierInterface binanceUpdateNotifierInterface)
{
if(binanceUpdateNotifierInterfaceList == null)
{
binanceUpdateNotifierInterfaceList = new ArrayList<>();
}
binanceUpdateNotifierInterfaceList.add(binanceUpdateNotifierInterface);
}
private void createPairSymbolList()
{
pairSymbolList = new ArrayList<>();
@ -44,9 +51,10 @@ public class BinanceManager {
pairSymbolList.add("USDT");
}
public void updateBalance(BinanceCallBack callBack)
public void updateBalance()
{
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(publicKey, privateKey);
BinanceApiRestClient client = factory.newRestClient();
try {
@ -59,21 +67,30 @@ public class BinanceManager {
{
if(Double.parseDouble(assets.get(i).getFree()) > 0 || Double.parseDouble(assets.get(i).getLocked()) > 0)
{
balance.add(new Currency(assets.get(i).getAsset(), Double.parseDouble(assets.get(i).getFree()) + Double.parseDouble(assets.get(i).getLocked())));
//balance.add(new Currency(assets.get(i).getAsset(), Double.parseDouble(assets.get(i).getFree()) + Double.parseDouble(assets.get(i).getLocked())));
if(!assets.get(i).getAsset().equals("VEN"))
{
balance.add(new Currency(assets.get(i).getAsset(), Double.parseDouble(assets.get(i).getFree()) + Double.parseDouble(assets.get(i).getLocked())));
}
}
}
callBack.onSuccess();
for(BinanceUpdateNotifierInterface binanceUpdateNotifierInterface : binanceUpdateNotifierInterfaceList)
{
binanceUpdateNotifierInterface.onBinanceBalanceUpdateSuccess();
}
} catch (BinanceApiException e) {
callBack.onError(e.getMessage());
for(BinanceUpdateNotifierInterface binanceUpdateNotifierInterface : binanceUpdateNotifierInterfaceList)
{
binanceUpdateNotifierInterface.onBinanceBalanceUpdateError(id, e.getMessage());
}
}
}
public void updateTrades(BinanceCallBack callBack, String symbol)
public void updateTrades(String symbol)
{
trades = new ArrayList<>();
for(int i = 0; i < pairSymbolList.size(); i++)
{
if(!pairSymbolList.get(i).equals(symbol))
@ -82,7 +99,10 @@ public class BinanceManager {
}
}
callBack.onSuccess();
for(BinanceUpdateNotifierInterface binanceUpdateNotifierInterface : binanceUpdateNotifierInterfaceList)
{
binanceUpdateNotifierInterface.onBinanceTradesUpdated();
}
}
public void updateTrades(BinanceCallBack callBack, String symbol, long fromId)

View File

@ -0,0 +1,96 @@
package com.herbron.moodl.DataManagers.ExchangeManager;
import com.herbron.moodl.DataManagers.InfoAPIManagers.Pair;
import java.util.ArrayList;
import java.util.List;
public class Exchange {
protected int id;
protected String name;
protected int type;
protected String description;
protected String publicKey;
protected String privateKey;
protected boolean isEnabled;
private List<Pair> pairs;
public Exchange(int id, String name, int type, String description, String publicKey, String privateKey, boolean isEnabled)
{
this.id = id;
this.name = name;
this.type = type;
this.description = description;
this.publicKey = publicKey;
this.privateKey = privateKey;
this.isEnabled = isEnabled;
}
public Exchange(String name, List<Pair> pairs)
{
this.name = name;
this.pairs = pairs;
}
public Exchange(Exchange exchange)
{
this.name = exchange.name;
this.pairs = exchange.pairs;
}
public List<Pair> getPairs()
{
return pairs;
}
public boolean isEnabled()
{
return isEnabled;
}
public String getPublicKey()
{
return publicKey;
}
public String getPrivateKey()
{
return privateKey;
}
public int getType()
{
return type;
}
public String getName()
{
return name;
}
public String getDescription()
{
return description;
}
public int getId()
{
return id;
}
public List<Pair> getPairsFor(String symbol)
{
List<Pair> compatiblePairs = new ArrayList<>();
for(Pair pair : pairs)
{
if(pair.contains(symbol))
{
compatiblePairs.add(pair);
}
}
return compatiblePairs;
}
}

View File

@ -11,6 +11,7 @@ import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataNotifiers.HitBTCUpdateNotifierInterface;
import com.herbron.moodl.R;
import org.json.JSONArray;
@ -26,10 +27,8 @@ import java.util.Map;
* Created by Guitoune on 26/02/2018.
*/
public class HitBtcManager {
public class HitBtcManager extends Exchange {
private String publicKey;
private String privateKey;
final private String hitBalanceUrl = "https://api.hitbtc.com/api/2/account/balance";
final private String hitTradingBalanceUrl = "https://api.hitbtc.com/api/2/trading/balance";
final private String tradeHistoryUrl = "https://api.hitbtc.com/api/2/history/trades?";
@ -41,13 +40,24 @@ public class HitBtcManager {
private List<Currency> balance;
private android.content.Context context;
public HitBtcManager(android.content.Context context, String publicKey, String privateKey)
private List<HitBTCUpdateNotifierInterface> hitBTCUpdateNotifierInterfaceList;
public HitBtcManager(android.content.Context context, Exchange exchange)
{
super(exchange.id, exchange.name, exchange.type, exchange.description, exchange.publicKey, exchange.privateKey, exchange.isEnabled);
this.context = context;
requestQueue = Volley.newRequestQueue(context);
}
this.publicKey = publicKey;
this.privateKey = privateKey;
public void addListener(HitBTCUpdateNotifierInterface hitBTCUpdateNotifierInterface)
{
if(hitBTCUpdateNotifierInterfaceList == null)
{
hitBTCUpdateNotifierInterfaceList = new ArrayList<>();
}
hitBTCUpdateNotifierInterfaceList.add(hitBTCUpdateNotifierInterface);
}
private void createPairSymbolList()
@ -60,11 +70,6 @@ public class HitBtcManager {
pairSymbolList.add("USDT");
}
public void updateTrades(final HitBtcCallBack callBack, String symbol, String pairSymbol)
{
}
private void mergeBalanceSymbols()
{
List<Currency> mergedBalance = new ArrayList<>();
@ -91,7 +96,7 @@ public class HitBtcManager {
balance = mergedBalance;
}
public void updateGlobalBalance(final HitBtcCallBack masterCallBack)
public void updateGlobalBalance()
{
isTradingBalanceUpdated = false;
isBalanceUpdated = false;
@ -106,13 +111,20 @@ public class HitBtcManager {
if(isTradingBalanceUpdated)
{
mergeBalanceSymbols();
masterCallBack.onSuccess();
for(HitBTCUpdateNotifierInterface hitBTCUpdateNotifierInterface : hitBTCUpdateNotifierInterfaceList)
{
hitBTCUpdateNotifierInterface.onHitBTCBalanceUpdateSuccess();
}
}
}
@Override
public void onError(String error) {
masterCallBack.onError(error);
for(HitBTCUpdateNotifierInterface hitBTCUpdateNotifierInterface : hitBTCUpdateNotifierInterfaceList)
{
hitBTCUpdateNotifierInterface.onHitBTCBalanceUpdateError(id, error);
}
}
});
@ -124,13 +136,20 @@ public class HitBtcManager {
if(isBalanceUpdated)
{
mergeBalanceSymbols();
masterCallBack.onSuccess();
for(HitBTCUpdateNotifierInterface hitBTCUpdateNotifierInterface : hitBTCUpdateNotifierInterfaceList)
{
hitBTCUpdateNotifierInterface.onHitBTCBalanceUpdateSuccess();
}
}
}
@Override
public void onError(String error) {
masterCallBack.onError(error);
for(HitBTCUpdateNotifierInterface hitBTCUpdateNotifierInterface : hitBTCUpdateNotifierInterfaceList)
{
hitBTCUpdateNotifierInterface.onHitBTCBalanceUpdateError(id, error);
}
}
});
}

View File

@ -0,0 +1,352 @@
package com.herbron.moodl.DataManagers.InfoAPIManagers;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.herbron.moodl.DataNotifiers.CoinmarketcapNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by Guitoune on 22/04/2018.
*/
public class CoinmarketCapAPIManager {
final private static String LISTINGURL = "https://api.coinmarketcap.com/v2/listings/";
final private static String TICKERLISTURL1 = "https://api.coinmarketcap.com/v2/ticker/?start=";
private static final String topCurrenciesUrl = "https://api.coinmarketcap.com/v2/ticker/?limit=9&convert=";
private static final String marketCapUrl = "https://api.coinmarketcap.com/v2/global/?convert=";
private RequestQueue requestQueue;
private List<Currency> currencyTickerList;
private static CoinmarketCapAPIManager INSTANCE;
private boolean upToDate;
private List<Currency> topCurrencies;
private long marketCap;
private long dayVolume;
private String active_crypto;
private String active_markets;
private List<CoinmarketcapNotifierInterface> coinmarketcapNotifierInterfaceList;
private CoinmarketCapAPIManager(Context context)
{
requestQueue = Volley.newRequestQueue(context);
}
public static synchronized CoinmarketCapAPIManager getInstance(Context context)
{
if(INSTANCE == null)
{
INSTANCE = new CoinmarketCapAPIManager(context);
}
return INSTANCE;
}
public void addListener(CoinmarketcapNotifierInterface coinmarketcapNotifierInterface)
{
if(coinmarketcapNotifierInterfaceList == null)
{
coinmarketcapNotifierInterfaceList = new ArrayList<>();
}
coinmarketcapNotifierInterfaceList.add(coinmarketcapNotifierInterface);
}
public boolean isUpToDate()
{
if(currencyTickerList == null)
{
upToDate = false;
}
return upToDate;
}
public void getCurrenciesFrom(int indexFrom, final String toSymbol)
{
String requetsString = TICKERLISTURL1 + indexFrom + "&limit=50&convert=" + toSymbol;
StringRequest strRequest = new StringRequest(Request.Method.GET, requetsString,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0)
{
processTickersResult(response, toSymbol);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(strRequest);
}
public void updateListing()
{
currencyTickerList = new ArrayList<>();
StringRequest strRequest = new StringRequest(Request.Method.GET, LISTINGURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0) {
processTickerListResult(response);
}
upToDate = true;
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
upToDate = true;
}
});
requestQueue.add(strRequest);
}
public int getTickerIdForSymbol(String symbol)
{
int tickerId = 0;
int i = 0;
while(!currencyTickerList.get(i).getSymbol().equals(symbol) && currencyTickerList.size() > i+1)
{
i++;
}
if(currencyTickerList.get(i).getSymbol().equals(symbol))
{
tickerId = currencyTickerList.get(i).getTickerId();
}
return tickerId;
}
private void processTickersResult(String response, String toSymbol)
{
List<Currency> currencyList = new ArrayList<>();
try {
JSONObject masterJsonObject = new JSONObject(response);
if(masterJsonObject.keys().hasNext())
{
JSONObject currencyJsonObject = masterJsonObject.getJSONObject(masterJsonObject.keys().next());
Iterator<?> keys = currencyJsonObject.keys();
while(keys.hasNext())
{
String key = keys.next().toString();
JSONObject subCurrencyJsonObject = currencyJsonObject.getJSONObject(key);
Currency newCurrency = new Currency(subCurrencyJsonObject.getString("name"), subCurrencyJsonObject.getString("symbol"), subCurrencyJsonObject.getInt("id"));
newCurrency.setRank(subCurrencyJsonObject.getInt("rank"));
JSONObject quoteJsonObject = subCurrencyJsonObject.getJSONObject("quotes");
JSONObject symJsonObject = quoteJsonObject.getJSONObject(toSymbol);
newCurrency.setValue(symJsonObject.getDouble("price"));
newCurrency.setDayFluctuationPercentage((float) symJsonObject.getDouble("percent_change_24h"));
newCurrency.setDayFluctuation(newCurrency.getDayFluctuationPercentage() * newCurrency.getValue() / 100);
currencyList.add(newCurrency);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
for(CoinmarketcapNotifierInterface coinmarketcapNotifierInterface : coinmarketcapNotifierInterfaceList)
{
coinmarketcapNotifierInterface.onCurrenciesRetrieved(currencyList);
}
}
private void processTickerListResult(String response)
{
try {
JSONObject dataJsonObject = new JSONObject(response);
JSONArray dataJsonArray = dataJsonObject.getJSONArray("data");
for(int i = 0; i < dataJsonArray.length(); i++)
{
JSONObject currencyJsonObject = dataJsonArray.getJSONObject(i);
currencyTickerList.add(new Currency(currencyJsonObject.getString("name"), currencyJsonObject.getString("symbol"), currencyJsonObject.getInt("id")));
}
} catch (JSONException e) {
e.printStackTrace();
}
for(CoinmarketcapNotifierInterface coinmarketcapNotifierInterface : coinmarketcapNotifierInterfaceList)
{
coinmarketcapNotifierInterface.onListingUpdated();
}
}
public void updateTopCurrencies(final String toSymbol)
{
String requestString = topCurrenciesUrl + toSymbol;
topCurrencies = new ArrayList<>();
StringRequest strRequest = new StringRequest(Request.Method.GET, requestString,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0) {
processTopCurrencies(response, toSymbol);
}
for(CoinmarketcapNotifierInterface coinmarketcapNotifierInterface : coinmarketcapNotifierInterfaceList)
{
coinmarketcapNotifierInterface.onTopCurrenciesUpdated();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(strRequest);
}
public void updateMarketCap(final String toSymbol)
{
String requestString = marketCapUrl + toSymbol;
StringRequest strRequest = new StringRequest(Request.Method.GET, requestString,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0) {
processMarketCapData(response, toSymbol);
}
for(CoinmarketcapNotifierInterface coinmarketcapNotifierInterface : coinmarketcapNotifierInterfaceList)
{
coinmarketcapNotifierInterface.onMarketCapUpdated();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(strRequest);
}
private void processMarketCapData(String response, String toSymbol)
{
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
JSONObject quotesJsonObject = dataJsonObject.getJSONObject("quotes");
JSONObject valuesJsonObject = quotesJsonObject.getJSONObject(toSymbol);
active_crypto = dataJsonObject.getString("active_cryptocurrencies");
active_markets = dataJsonObject.getString("active_markets");
marketCap = valuesJsonObject.getLong("total_market_cap");
dayVolume = valuesJsonObject.getLong("total_volume_24h");
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getActive_crypto()
{
return active_crypto;
}
public String getActive_markets()
{
return active_markets;
}
public List<Currency> getTopCurrencies()
{
return topCurrencies;
}
public long getDayVolume()
{
return dayVolume;
}
private void processTopCurrencies(String response, String toSymbol)
{
try {
JSONObject masterJsonObject = new JSONObject(response);
if(masterJsonObject.keys().hasNext())
{
JSONObject currencyJsonObject = masterJsonObject.getJSONObject(masterJsonObject.keys().next());
Iterator<?> keys = currencyJsonObject.keys();
while(keys.hasNext())
{
String key = keys.next().toString();
JSONObject subCurrencyJsonObject = currencyJsonObject.getJSONObject(key);
Currency newCurrency = new Currency(subCurrencyJsonObject.getString("name"), subCurrencyJsonObject.getString("symbol"), subCurrencyJsonObject.getInt("id"));
JSONObject quoteJsonObject = subCurrencyJsonObject.getJSONObject("quotes");
JSONObject symJsonObject = quoteJsonObject.getJSONObject(toSymbol);
newCurrency.setMarketCapitalization(symJsonObject.getDouble("market_cap"));
newCurrency.setVolume24h(symJsonObject.getDouble("volume_24h"));
topCurrencies.add(newCurrency);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public Currency getCurrencyFromSymbol(String symbol)
{
Currency returnedCurrency = null;
int index = 0;
do {
if(symbol.equals(topCurrencies.get(index).getSymbol()))
{
returnedCurrency = topCurrencies.get(index);
}
index++;
} while(index < topCurrencies.size() && returnedCurrency == null);
return returnedCurrency;
}
public long getMarketCap()
{
return marketCap;
}
}

View File

@ -0,0 +1,313 @@
package com.herbron.moodl.DataManagers.InfoAPIManagers;
import android.content.Context;
import android.os.StrictMode;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.herbron.moodl.DataNotifiers.CryptocompareNotifierInterface;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import com.herbron.moodl.DataManagers.ExchangeManager.Exchange;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Pattern;
/**
* Created by Tiji on 11/04/2018.
*/
public class CryptocompareApiManager {
final private static String DETAILURL = "https://min-api.cryptocompare.com/data/all/coinlist";
final private static String EXCHANGEURL = "https://min-api.cryptocompare.com/data/all/exchanges";
private RequestQueue requestQueue;
private LinkedHashMap<String, String> coinInfosHashmap;
private List<Exchange> exchangeList;
private static CryptocompareApiManager INSTANCE;
private boolean exchangesUpToDate;
private boolean detailsUpToDate;
private List<CryptocompareNotifierInterface> cryptocompareNotifierInterfaceList;
private CryptocompareApiManager(Context context)
{
requestQueue = Volley.newRequestQueue(context);
}
public static synchronized CryptocompareApiManager getInstance(Context context)
{
if(INSTANCE == null)
{
INSTANCE = new CryptocompareApiManager(context);
}
return INSTANCE;
}
public void addListener(CryptocompareNotifierInterface cryptocompareNotifierInterface)
{
if(cryptocompareNotifierInterfaceList == null)
{
cryptocompareNotifierInterfaceList = new ArrayList<>();
}
cryptocompareNotifierInterfaceList.add(cryptocompareNotifierInterface);
}
public void updateExchangeList()
{
StringRequest stringRequest = new StringRequest(Request.Method.GET, EXCHANGEURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
processExchangeResult(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(stringRequest);
}
public void updateDetails()
{
StringRequest strRequest = new StringRequest(Request.Method.GET, DETAILURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0) {
processDetailResult(response);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(strRequest);
}
public boolean isExchangesUpToDate()
{
if(exchangeList == null)
{
exchangesUpToDate = false;
}
return exchangesUpToDate;
}
public boolean isDetailsUpToDate()
{
if(coinInfosHashmap == null)
{
detailsUpToDate = false;
}
return detailsUpToDate;
}
private void processExchangeResult(String response)
{
exchangeList = new ArrayList<>();
try {
JSONObject mainJsonObject = new JSONObject(response);
Iterator<String> exchangeIterator = mainJsonObject.keys();
while(exchangeIterator.hasNext())
{
String exchangeKey = exchangeIterator.next();
JSONObject exchangeJsonObject = mainJsonObject.getJSONObject(exchangeKey);
Iterator<String> pairIterator = exchangeJsonObject.keys();
List<Pair> pairList = new ArrayList<>();
while(pairIterator.hasNext())
{
String pairKey = pairIterator.next();
JSONArray pairJsonArray = exchangeJsonObject.getJSONArray(pairKey);
for(int i = 0; i < pairJsonArray.length(); i++)
{
pairList.add(new Pair(pairKey, pairJsonArray.get(i).toString()));
}
}
exchangeList.add(new Exchange(exchangeKey, pairList));
}
for(CryptocompareNotifierInterface cryptocompareNotifierInterface : cryptocompareNotifierInterfaceList)
{
cryptocompareNotifierInterface.onExchangesUpdated();
}
} catch (JSONException e) {
Log.d("moodl", "Error while processing exchange result");
}
}
public List<Exchange> getExchangeList(String symbol)
{
List<Exchange> compatibleExchanges = new ArrayList<>();
for(Exchange exchange : exchangeList)
{
int i = 0;
boolean isSymbolTraded = false;
while(i < exchange.getPairs().size() && !isSymbolTraded)
{
if(exchange.getPairs().get(i).contains(symbol))
{
compatibleExchanges.add(exchange);
isSymbolTraded = true;
}
i++;
}
}
return compatibleExchanges;
}
private void processDetailResult(String response)
{
response = response.substring(response.indexOf("\"Data\"") + 7, response.lastIndexOf("},\"BaseImageUrl\""));
String[] tab = response.split(Pattern.quote("},"));
coinInfosHashmap = new LinkedHashMap<>();
for(int i = 0; i < tab.length; i++)
{
tab[i] = tab[i].substring(tab[i].indexOf("\":{")+2, tab[i].length()) + "}";
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
JSONObject jsonObject = new JSONObject(tab[i]);
switch (jsonObject.getString("Symbol"))
{
case "IOT":
coinInfosHashmap.put("MIOTA", tab[i]);
break;
case "XRB":
coinInfosHashmap.put("NANO", tab[i]);
break;
default:
coinInfosHashmap.put(jsonObject.getString("Symbol"), tab[i]);
break;
}
} catch (JSONException e) {
Log.d("moodl", "ImageUrl not found.");
}
}
sortDetails();
detailsUpToDate = true;
for(CryptocompareNotifierInterface cryptocompareNotifierInterface : cryptocompareNotifierInterfaceList)
{
cryptocompareNotifierInterface.onDetailsUpdated();
}
}
private void sortDetails()
{
LinkedHashMap<String, String> sortedHashmap = new LinkedHashMap<>();
List<String> listInfos = new ArrayList<>(coinInfosHashmap.values());
List<String> listSymbols = new ArrayList<>(coinInfosHashmap.keySet());
for(int i = 0; i < coinInfosHashmap.keySet().size(); i++)
{
try {
JSONObject jsonObject = new JSONObject(listInfos.get(i));
int index = jsonObject.getInt("SortOrder");
listInfos.add(index, listInfos.get(i));
listSymbols.add(index, listSymbols.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for(int i = 0; i < listInfos.size(); i++)
{
sortedHashmap.put(listSymbols.get(i), listInfos.get(i));
}
coinInfosHashmap = sortedHashmap;
}
public LinkedHashMap<String, String> getCoinInfosHashmap() {
return coinInfosHashmap;
}
public List<String> getCurrenciesName()
{
List<String> currenciesName = new ArrayList<>();
for (String symbol : coinInfosHashmap.keySet())
{
try {
JSONObject jsonObject = new JSONObject(coinInfosHashmap.get(symbol));
currenciesName.add(jsonObject.getString("CoinName"));
} catch (JSONException e) {
e.printStackTrace();
}
}
return currenciesName;
}
public List<Currency> getCurrenciesDenomination()
{
List<Currency> currencies = new ArrayList<>();
for(String symbol : coinInfosHashmap.keySet())
{
try {
JSONObject jsonObject = new JSONObject(coinInfosHashmap.get(symbol));
currencies.add(new Currency(jsonObject.getString("CoinName"), symbol));
} catch (JSONException e) {
e.printStackTrace();
}
}
return currencies;
}
public Currency getCurrencyDetailsFromSymbol(String symbol)
{
//Currency currency = new Currency();
return null;
}
public List<String> getCurrenciesSymbol()
{
return new ArrayList<>(coinInfosHashmap.keySet());
}
}

View File

@ -0,0 +1,41 @@
package com.herbron.moodl.DataManagers.InfoAPIManagers;
public class Pair {
private String from;
private String to;
public Pair(String from, String to)
{
this.from = from;
this.to = to;
}
public Pair(Pair pair)
{
this.from = pair.from;
this.to = pair.to;
}
public boolean contains(String symbol)
{
symbol = symbol.toUpperCase();
return symbol.equals(from) || symbol.equals(to);
}
public String getFrom()
{
return from;
}
public String getTo()
{
return to;
}
@Override
public String toString() {
return from + "/" + to;
}
}

View File

@ -1,182 +0,0 @@
package com.herbron.moodl.DataManagers;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by Guitoune on 02/03/2018.
*/
public class MarketCapManager {
private static final String topCurrenciesUrl = "https://api.coinmarketcap.com/v2/ticker/?limit=9&convert=";
private static final String marketCapUrl = "https://api.coinmarketcap.com/v2/global/?convert=";
private RequestQueue requestQueue;
private List<Currency> topCurrencies;
private long marketCap;
private long dayVolume;
private String active_crypto;
private String active_markets;
public MarketCapManager(android.content.Context context)
{
requestQueue = Volley.newRequestQueue(context);
}
public void updateTopCurrencies(final VolleyCallBack callBack, final String toSymbol)
{
String requestString = topCurrenciesUrl + toSymbol;
topCurrencies = new ArrayList<>();
StringRequest strRequest = new StringRequest(Request.Method.GET, requestString,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0) {
processTopCurrencies(response, toSymbol);
}
callBack.onSuccess();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(strRequest);
}
public void updateMarketCap(final VolleyCallBack callBack, final String toSymbol)
{
String requestString = marketCapUrl + toSymbol;
StringRequest strRequest = new StringRequest(Request.Method.GET, requestString,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() > 0) {
processMarketCapData(response, toSymbol);
}
callBack.onSuccess();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(strRequest);
}
private void processMarketCapData(String response, String toSymbol)
{
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
JSONObject quotesJsonObject = dataJsonObject.getJSONObject("quotes");
JSONObject valuesJsonObject = quotesJsonObject.getJSONObject(toSymbol);
active_crypto = dataJsonObject.getString("active_cryptocurrencies");
active_markets = dataJsonObject.getString("active_markets");
marketCap = valuesJsonObject.getLong("total_market_cap");
dayVolume = valuesJsonObject.getLong("total_volume_24h");
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getActive_crypto()
{
return active_crypto;
}
public String getActive_markets()
{
return active_markets;
}
public List<Currency> getTopCurrencies()
{
return topCurrencies;
}
public long getDayVolume()
{
return dayVolume;
}
private void processTopCurrencies(String response, String toSymbol)
{
try {
JSONObject masterJsonObject = new JSONObject(response);
if(masterJsonObject.keys().hasNext())
{
JSONObject currencyJsonObject = masterJsonObject.getJSONObject(masterJsonObject.keys().next());
Iterator<?> keys = currencyJsonObject.keys();
while(keys.hasNext())
{
String key = keys.next().toString();
JSONObject subCurrencyJsonObject = currencyJsonObject.getJSONObject(key);
Currency newCurrency = new Currency(subCurrencyJsonObject.getString("name"), subCurrencyJsonObject.getString("symbol"), subCurrencyJsonObject.getInt("id"));
JSONObject quoteJsonObject = subCurrencyJsonObject.getJSONObject("quotes");
JSONObject symJsonObject = quoteJsonObject.getJSONObject(toSymbol);
newCurrency.setMarketCapitalization(symJsonObject.getDouble("market_cap"));
newCurrency.setVolume24h(symJsonObject.getDouble("volume_24h"));
topCurrencies.add(newCurrency);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public Currency getCurrencyFromSymbol(String symbol)
{
Currency returnedCurrency = null;
int index = 0;
do {
if(symbol.equals(topCurrencies.get(index).getSymbol()))
{
returnedCurrency = topCurrencies.get(index);
}
index++;
} while(index < topCurrencies.size() && returnedCurrency == null);
return returnedCurrency;
}
public long getMarketCap()
{
return marketCap;
}
public interface VolleyCallBack
{
void onSuccess();
}
}

View File

@ -38,21 +38,6 @@ public class PreferencesManager {
return settingPreferences.getString("default_currency", "USD");
}
public String getHitBTCPublicKey()
{
return settingPreferences.getString("hitbtc_publickey", null);
}
public String getHitBTCPrivateKey()
{
return settingPreferences.getString("hitbtc_privatekey", null);
}
public boolean isHitBTCActivated()
{
return settingPreferences.getBoolean("enable_hitbtc", false);
}
public boolean switchBalanceHiddenState()
{
SharedPreferences.Editor editor = settingPreferences.edit();
@ -74,16 +59,6 @@ public class PreferencesManager {
editor.apply();
}
public String getBinancePublicKey()
{
return settingPreferences.getString("binance_publickey", null);
}
public String getBinancePrivateKey()
{
return settingPreferences.getString("binance_privatekey", null);
}
public boolean isBinanceActivated()
{
return settingPreferences.getBoolean("enable_binance", false);

View File

@ -1,16 +0,0 @@
package com.herbron.moodl;
/**
* Created by Administrator on 17/06/2018.
*/
public interface DataNotifierInterface {
void onTickerListUpdated();
void onDetailsUpdated();
void onBalanceDataUpdated();
void onBalanceError(String error);
}

View File

@ -0,0 +1,12 @@
package com.herbron.moodl.DataNotifiers;
/**
* Created by Administrator on 17/06/2018.
*/
public interface BalanceUpdateNotifierInterface {
void onBalanceDataUpdated();
void onBalanceError(String error);
}

View File

@ -0,0 +1,10 @@
package com.herbron.moodl.DataNotifiers;
public interface BinanceUpdateNotifierInterface {
void onBinanceTradesUpdated();
void onBinanceBalanceUpdateSuccess();
void onBinanceBalanceUpdateError(int accountId, String error);
}

View File

@ -0,0 +1,16 @@
package com.herbron.moodl.DataNotifiers;
import com.herbron.moodl.DataManagers.CurrencyData.Currency;
import java.util.List;
public interface CoinmarketcapNotifierInterface {
void onCurrenciesRetrieved(List<Currency> currencyList);
void onTopCurrenciesUpdated();
void onMarketCapUpdated();
void onListingUpdated();
}

View File

@ -0,0 +1,9 @@
package com.herbron.moodl.DataNotifiers;
public interface CryptocompareNotifierInterface {
void onDetailsUpdated();
void onExchangesUpdated();
}

View File

@ -0,0 +1,9 @@
package com.herbron.moodl.DataNotifiers;
public interface HitBTCUpdateNotifierInterface {
void onHitBTCBalanceUpdateSuccess();
void onHitBTCBalanceUpdateError(int accountId, String error);
}

View File

@ -0,0 +1,9 @@
package com.herbron.moodl.DataNotifiers;
import android.graphics.Bitmap;
public interface MoodlboxNotifierInterface {
void onBitmapDownloaded(Bitmap bitmap);
}

View File

@ -4,7 +4,6 @@ import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.widget.CardView;
@ -13,8 +12,8 @@ import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import com.herbron.moodl.Activities.HomeActivity;
import com.herbron.moodl.DataManagers.CurrencyData.CurrencyDetailsList;
import com.herbron.moodl.DataManagers.InfoAPIManagers.CryptocompareApiManager;
import com.herbron.moodl.DataNotifiers.MoodlboxNotifierInterface;
import org.json.JSONException;
import org.json.JSONObject;
@ -207,7 +206,7 @@ public class MoodlBox {
}
}
public static void getBitmapFromURL(String src, String symbol, Resources resources, Context context, HomeActivity.IconCallBack callBack)
public static void getBitmapFromURL(String src, String symbol, Resources resources, Context context, MoodlboxNotifierInterface callBack)
{
String size = src.substring(src.lastIndexOf("=") + 1, src.length());
String filepath = context.getCacheDir() + "/" + symbol + "x" + size + ".png";
@ -240,7 +239,7 @@ public class MoodlBox {
}
}
callBack.onSuccess(result);
callBack.onBitmapDownloaded(result);
}
public static int getColor(int id, Context context)
@ -275,9 +274,9 @@ public class MoodlBox {
return drawable;
}
public static String getIconUrl(String symbol, CurrencyDetailsList currencyDetailsList)
public static String getIconUrl(String symbol, CryptocompareApiManager cryptocompareApiManager)
{
return getIconUrl(symbol, 50, currencyDetailsList);
return getIconUrl(symbol, 50, cryptocompareApiManager);
}
public static float convertDpToPx(float dp, Resources resources)
@ -285,12 +284,12 @@ public class MoodlBox {
return dp * resources.getDisplayMetrics().density;
}
public static String getIconUrl(String symbol, int size, CurrencyDetailsList currencyDetailsList)
public static String getIconUrl(String symbol, int size, CryptocompareApiManager cryptocompareApiManager)
{
String url;
try {
JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol));
JSONObject jsonObject = new JSONObject(cryptocompareApiManager.getCoinInfosHashmap().get(symbol));
url = "https://www.cryptocompare.com" + jsonObject.getString("ImageUrl") + "?width=" + size;
} catch (JSONException | NullPointerException e) {
url = null;

View File

@ -4,6 +4,9 @@ import android.content.Context;
import com.herbron.moodl.DataManagers.PreferencesManager;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Tiji on 19/04/2018.
*/
@ -34,6 +37,26 @@ public class PlaceholderManager {
return formattedString;
}
public static List<String> getFeeOptionsForSymbol(String symbol, Context context)
{
List<String> options = new ArrayList<>();
options.add(context.getResources().getString(R.string.fixedFee, symbol));
options.add(context.getResources().getString(R.string.percentageFee, symbol));
return options;
}
public static String getPairString(String pair1, String pair2, Context context)
{
return context.getResources().getString(R.string.pairPlaceholder, pair1, pair2);
}
public static String getDenomination(String coinName, String coinSymbol, Context context)
{
return context.getResources().getString(R.string.denomincationPlaceholder, coinName, coinSymbol);
}
public static String getEditTransactionString(String coinName, Context context)
{
return context.getResources().getString(R.string.edit_transaction, coinName);

View File

@ -0,0 +1,10 @@
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false"
android:fillAfter="true">
<translate
android:fromXDelta="0%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="200%"
android:duration="400" />
</set>

View File

@ -0,0 +1,10 @@
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false"
android:fillAfter="true">
<translate
android:fromXDelta="0%" android:toXDelta="0%"
android:fromYDelta="200%" android:toYDelta="0%"
android:duration="400"/>
</set>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/separationColor">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="@color/separationColor" />
<corners android:radius="2dp" />
</shape>
</item>
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<solid android:color="@color/transparent"/>
<corners android:radius="2dp"/>
<stroke
android:color="@color/separationColor"
android:width="2dp"
android:dashGap="4dp"
android:dashWidth="9dp"/>
</shape>
</item>
</ripple>

View File

@ -1,14 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/separationColor">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="@color/separationColor" />
<corners android:radius="2dp" />
</shape>
</item>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<solid android:color="@color/transparent"/>
@ -20,4 +11,4 @@
android:dashWidth="9dp"/>
</shape>
</item>
</ripple>
</selector>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/softWhite"/>
<corners
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
<padding
android:left="3dp"
android:right="3dp"
android:top="3dp"
android:bottom="3dp"/>
</shape>
</item>
</layer-list>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="@color/separationColor"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M7,10l5,5 5,-5z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M7,10l5,5 5,-5z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="@color/separationColor"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M7,14l5,-5 5,5z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M7,14l5,-5 5,5z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="@color/error"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-2h2v2zM13,13h-2L11,7h2v6z"/>
</vector>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="-90"
android:centerY="2%"
android:startColor="@color/increaseCandle"
android:centerColor="@color/white"
android:endColor="@color/white"
android:type="linear"/>
</shape>
</item>
</selector>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="-90"
android:centerY="2%"
android:startColor="@color/decreaseCandle"
android:centerColor="@color/white"
android:endColor="@color/white"
android:type="linear"/>
</shape>
</item>
</selector>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="-90"
android:centerY="2%"
android:startColor="@color/blue"
android:centerColor="@color/white"
android:endColor="@color/white"
android:type="linear"/>
</shape>
</item>
</selector>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/increaseCandle"/>
<corners
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
<padding
android:left="3dp"
android:right="3dp"
android:top="3dp"
android:bottom="3dp"/>
</shape>
</item>
</layer-list>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/decreaseCandle"/>
<corners
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
<padding
android:left="3dp"
android:right="3dp"
android:top="3dp"
android:bottom="3dp"/>
</shape>
</item>
</layer-list>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/blue"/>
<corners
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
<padding
android:left="3dp"
android:right="3dp"
android:top="3dp"
android:bottom="3dp"/>
</shape>
</item>
</layer-list>

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true">
<layer-list>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/transparent"/>
<corners android:radius="2dp"/>
<stroke
android:color="@color/separationColor"
android:width="1dp"/>
</shape>
</item>
<item
android:gravity="center_vertical|right"
android:drawable="@drawable/ic_arrow_drop_down_24dp"/>
</layer-list>
</item>
</selector>

View File

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true">
<layer-list>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/hardWhite"/>
<corners
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
<padding
android:left="3dp"
android:right="3dp"
android:top="3dp"
android:bottom="3dp"/>
</shape>
</item>
<item
android:gravity="center_vertical|right"
android:drawable="@drawable/ic_arrow_drop_down_white_24dp"/>
</layer-list>
</item>
<item android:state_enabled="false">
<layer-list>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/softWhite"/>
<corners
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
<padding
android:left="3dp"
android:right="3dp"
android:top="3dp"
android:bottom="3dp"/>
</shape>
</item>
<item
android:gravity="center_vertical|right"
android:drawable="@drawable/ic_arrow_drop_down_white_24dp"/>
</layer-list>
</item>
</selector>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/hardWhite"/>
<corners
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
<padding
android:left="3dp"
android:right="3dp"
android:top="3dp"
android:bottom="3dp"/>
</shape>
</item>
</layer-list>

View File

@ -0,0 +1,203 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLinear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:orientation="vertical"
android:tag="mainLinear">
<ProgressBar
android:id="@+id/currencyPortfolioDominance"
android:layout_width="match_parent"
android:layout_height="2dp"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:visibility="invisible"/>
<LinearLayout
android:id="@+id/currencyInfoLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout
android:id="@+id/topLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/currencyIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp" />
<TextView
android:id="@+id/currencyNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="start"
android:textColor="@color/mainTextViewColor"
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencySymbolTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:gravity="left"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewCaption" />
<TextView
android:id="@+id/currencyValueTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewTitle" />
</LinearLayout>
<LinearLayout
android:id="@+id/bottomLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/percentageOwnedTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="start"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewTitle"
android:visibility="gone"/>
<LinearLayout
android:id="@+id/currencyOwnedInfoLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/currencyOwnedTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="start"
android:textColor="@color/mainTextViewColor"
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencyValueOwnedTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:gravity="start"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewCaption" />
</LinearLayout>
<LinearLayout
android:id="@+id/secondaryLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal">
<TextView
android:id="@+id/currencyFluctuationPercentageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencyFluctuationTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/cardViewCaption" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/collapsableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:orientation="vertical">
<LinearLayout
android:id="@+id/separationLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/day_history"
android:textSize="@dimen/cardViewCaption" />
<View
android:layout_width="match_parent"
android:layout_height="@dimen/separationLineSize"
android:layout_gravity="center_vertical"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/separationColor" />
</LinearLayout>
<FrameLayout
android:id="@+id/frameLayoutChart"
android:layout_width="match_parent"
android:layout_height="@dimen/cardViewChartSize"
android:clickable="true"
android:focusable="true">
<ProgressBar
android:id="@+id/progressBarLinechartSummary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:focusable="false"
android:visibility="visible"/>
<FrameLayout
android:id="@+id/linearLayoutSubCharts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:visibility="gone">
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/LineChartView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:transitionName="chart"/>
<ImageView
android:id="@+id/detailsArrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_keyboard_arrow_right_grey_48dp"
android:layout_gravity="center_vertical|end"/>
</FrameLayout>
</FrameLayout>
</LinearLayout>
</LinearLayout>

View File

@ -0,0 +1,214 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLinear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:orientation="vertical"
android:tag="mainLinear">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false">
<LinearLayout
android:id="@+id/dragCardWatchlist"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="start"
android:visibility="gone"
android:layout_weight="0.08"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_drag_handle_24dp"
android:clickable="false"
android:focusable="false"/>
</LinearLayout>
<LinearLayout
android:id="@+id/currencyInfoLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical"
android:layout_weight="0.92">
<LinearLayout
android:id="@+id/topLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<ImageView
android:id="@+id/currencyIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp" />
<TextView
android:id="@+id/currencyNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="start"
android:textColor="@color/mainTextViewColor"
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencySymbolTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:layout_marginLeft="2dp"
android:gravity="left"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewCaption" />
</LinearLayout>
<LinearLayout
android:id="@+id/bottomLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/currencyValueTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="start"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewTitle"
android:layout_weight="0.5"/>
<LinearLayout
android:id="@+id/secondaryLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal"
android:layout_weight="0.5">
<TextView
android:id="@+id/currencyFluctuationPercentageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencyFluctuationTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/cardViewCaption" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/deleteCardWatchlist"
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="@color/decreaseCandle"
android:gravity="center"
android:layout_gravity="end"
android:visibility="gone"
android:layout_weight="0.08"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_delete_white_24dp"
android:clickable="false"
android:focusable="false"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/collapsableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:orientation="vertical">
<LinearLayout
android:id="@+id/separationLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/day_history"
android:textSize="@dimen/cardViewCaption" />
<View
android:layout_width="match_parent"
android:layout_height="@dimen/separationLineSize"
android:layout_gravity="center_vertical"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/separationColor" />
</LinearLayout>
<FrameLayout
android:id="@+id/frameLayoutChart"
android:layout_width="match_parent"
android:layout_height="@dimen/cardViewChartSize"
android:clickable="true"
android:focusable="true"
android:visibility="visible">
<ProgressBar
android:id="@+id/progressBarLinechartWatchlist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:focusable="false"
android:visibility="visible"/>
<FrameLayout
android:id="@+id/linearLayoutSubCharts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:visibility="gone">
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/LineChartView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:id="@+id/detailsArrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_keyboard_arrow_right_grey_48dp"
android:layout_gravity="center_vertical|end"/>
</FrameLayout>
</FrameLayout>
</LinearLayout>
</LinearLayout>

View File

@ -77,7 +77,7 @@
android:layout_height="350dp"
android:layout_marginTop="5dp">
<com.herbron.moodl.LayoutManagers.CustomPieChart
<com.herbron.moodl.CustomLayouts.CustomPieChart
android:id="@+id/marketCapPieChart"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
style="@style/InputActivityTheme">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="125dp"
app:layout_collapseMode="pin"
app:elevation="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_collapseMode="pin">
<ImageButton
android:id="@+id/back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|center_vertical"
android:background="@drawable/ic_arrow_back_white_24dp"
android:text="@string/action_settings"
android:visibility="visible" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="@string/title_add_exchange"
android:textColor="@color/white"
android:textSize="18sp"
android:textStyle="bold" />
</FrameLayout>
<Spinner
android:id="@+id/exchange_spinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginBottom="22dp"
android:layout_marginEnd="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="12dp"
android:background="@drawable/spinner_background_header"
android:gravity="center"
android:textSize="18sp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<LinearLayout
android:id="@+id/exchange_setup_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="125dp"
android:background="@drawable/list_background"
android:paddingTop="5dp"
android:orientation="vertical"/>
</android.support.constraint.ConstraintLayout>

View File

@ -6,7 +6,7 @@
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.herbron.moodl.Activities.CurrencyDetailsActivity">
<com.herbron.moodl.LayoutManagers.CustomViewPager
<com.herbron.moodl.CustomLayouts.CustomViewPager
android:id="@+id/vfCurrencyDetails"
android:layout_width="match_parent"
android:layout_height="match_parent"

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.ExchangeListActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/gradient_background"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_exchange_list" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@drawable/ic_add_white_24dp" />
</android.support.design.widget.CoordinatorLayout>

View File

@ -1,126 +1,136 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.herbron.moodl.Activities.RecordTransactionActivity">
android:background="@drawable/gradient_background"
style="@style/InputActivityTheme">
<LinearLayout
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="5dp">
android:layout_height="@dimen/double_toolbarSpinner_size"
app:layout_collapseMode="pin"
app:elevation="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/buyButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:text="@string/buyText"
android:background="@drawable/button_buy"
android:layout_marginEnd="2.5dp"
android:enabled="false"
android:textColor="@color/white" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_collapseMode="pin"
android:focusableInTouchMode="true">
<Button
android:id="@+id/sellButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:text="@string/sellText"
android:background="@drawable/button_sell"
android:layout_marginStart="2.5dp"
android:layout_marginEnd="2.5dp"
android:textColor="@color/white"
android:enabled="true" />
<ImageButton
android:id="@+id/back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|center_vertical"
android:background="@drawable/ic_arrow_back_white_24dp"
android:text="@string/action_settings"
android:visibility="visible" />
<Button
android:id="@+id/transfertButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:text="@string/transferText"
android:background="@drawable/button_transfer"
android:layout_marginStart="2.5dp"
android:textColor="@color/white"
android:enabled="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="@string/title_choose_coin"
android:textColor="@color/white"
android:textSize="18sp"
android:textStyle="bold" />
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="@dimen/spinner_toolbar_height"
android:layout_marginEnd="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="12dp">
<AutoCompleteTextView
android:id="@+id/coin_autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/spinner_background_header"
android:textSize="18sp"
android:hint="@string/select_coin"
android:inputType="textNoSuggestions"
android:gravity="center"/>
<ImageView
android:id="@+id/currencyIconImageView"
android:layout_width="40dp"
android:layout_height="match_parent"
android:layout_gravity="start|center_vertical"
android:layout_margin="5dp"/>
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/spinner_toolbar_height"
android:layout_marginEnd="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp">
<AutoCompleteTextView
android:id="@+id/exchange_autoCompleteTextView"
android:layout_width="0dp"
android:layout_weight="1.7"
android:layout_marginEnd="12dp"
android:layout_height="@dimen/spinner_toolbar_height"
android:background="@drawable/spinner_background_header"
android:hint="@string/select_exchange"
android:inputType="textNoSuggestions"
android:gravity="center"
android:enabled="false"/>
<AutoCompleteTextView
android:id="@+id/pair_autoCompleteTextView"
android:layout_width="0dp"
android:layout_height="@dimen/spinner_toolbar_height"
android:layout_weight="1.2"
android:background="@drawable/spinner_background_header"
android:hint="@string/select_pair"
android:inputType="textNoSuggestions"
android:gravity="center"
android:enabled="false"/>
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/currencySymbol"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"/>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_currency_amount"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/globalTabLayouts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="@dimen/double_toolbarSpinner_size"
android:paddingTop="5dp"
android:orientation="vertical"
android:visibility="invisible">
<EditText
android:id="@+id/currencyAmount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/activity_add_amount"
android:inputType="numberDecimal"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_purchase_date"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/purchaseDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/activity_purchased_date"
android:focusable="false"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_purchase_price"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/purchasePrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/activity_purchased_price"
android:inputType="numberDecimal" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_fees"
<com.herbron.moodl.CustomLayouts.CustomTabLayout
android:id="@+id/transactionsTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone">
app:tabMode="fixed"
app:tabIndicatorColor="@color/transparent"/>
<EditText
android:id="@+id/feesTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/activity_fees"
android:inputType="numberDecimal" />
</android.support.design.widget.TextInputLayout>
<android.support.v4.view.ViewPager
android:id="@+id/transactionsViewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_error_24dp"/>

View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/InputActivityTheme"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="@dimen/margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/informations"
android:textSize="@dimen/cardViewTitle"
android:layout_marginBottom="10dp"
android:textColor="@color/mainTextViewColor"/>
<View
android:layout_width="match_parent"
android:layout_height="@dimen/separationLineSize"
android:layout_gravity="center_vertical"
android:background="@color/separationColor" />
<android.support.design.widget.TextInputLayout
android:id="@+id/input_account_label"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/account_label_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/account_label"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_description"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/account_description_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/description"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_publicKey"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/publicKey_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/apiKey"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_secretKey"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/secretKey_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/secretKey"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/saveExchangeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:text="@string/save"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
style="@style/Widget.AppCompat.Button.Colored"/>
</RelativeLayout>

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/mainLinear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
@ -40,7 +41,7 @@
android:layout_gravity="center_vertical"
android:gravity="start"
android:textColor="@color/mainTextViewColor"
android:textSize="@dimen/cardViewMainText" />
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencySymbolTextView"
@ -49,7 +50,7 @@
android:layout_marginStart="2dp"
android:gravity="left"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewSecondaryText" />
android:textSize="@dimen/cardViewCaption" />
<TextView
android:id="@+id/currencyValueTextView"
@ -57,7 +58,7 @@
android:layout_height="wrap_content"
android:gravity="right"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewMainText" />
android:textSize="@dimen/cardViewTitle" />
</LinearLayout>
@ -73,7 +74,7 @@
android:layout_height="wrap_content"
android:gravity="start"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewMainText"
android:textSize="@dimen/cardViewTitle"
android:visibility="gone"/>
<LinearLayout
@ -88,7 +89,7 @@
android:layout_height="wrap_content"
android:gravity="start"
android:textColor="@color/mainTextViewColor"
android:textSize="@dimen/cardViewMainText" />
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencyValueOwnedTextView"
@ -97,7 +98,7 @@
android:layout_marginStart="2dp"
android:gravity="start"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewSecondaryText" />
android:textSize="@dimen/cardViewCaption" />
</LinearLayout>
@ -112,13 +113,13 @@
android:id="@+id/currencyFluctuationPercentageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/cardViewMainText" />
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencyFluctuationTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/cardViewSecondaryText" />
android:textSize="@dimen/cardViewCaption" />
</LinearLayout>
@ -143,7 +144,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/day_history"
android:textSize="@dimen/cardViewSecondaryText" />
android:textSize="@dimen/cardViewCaption" />
<View
android:layout_width="match_parent"
@ -174,7 +175,7 @@
android:visibility="visible"/>
<FrameLayout
android:id="@+id/linearLayoutSubLayout"
android:id="@+id/linearLayoutSubCharts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
@ -191,7 +192,8 @@
android:id="@+id/detailsArrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_keyboard_arrow_right_grey_48dp"
app:srcCompat="@drawable/ic_keyboard_arrow_right_grey_48dp"
android:background="@color/transparent"
android:layout_gravity="center_vertical|end"/>
</FrameLayout>

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/mainLinear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
@ -26,7 +27,8 @@
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_drag_handle_24dp"
app:srcCompat="@drawable/ic_drag_handle_24dp"
android:background="@color/transparent"
android:clickable="false"
android:focusable="false"/>
@ -60,7 +62,7 @@
android:layout_gravity="center_vertical"
android:gravity="start"
android:textColor="@color/mainTextViewColor"
android:textSize="@dimen/cardViewMainText" />
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencySymbolTextView"
@ -70,7 +72,7 @@
android:layout_marginLeft="2dp"
android:gravity="left"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewSecondaryText" />
android:textSize="@dimen/cardViewCaption" />
</LinearLayout>
@ -86,7 +88,7 @@
android:layout_height="wrap_content"
android:gravity="start"
android:textColor="@color/secondaryTextViewColor"
android:textSize="@dimen/cardViewMainText"
android:textSize="@dimen/cardViewTitle"
android:layout_weight="0.5"/>
<LinearLayout
@ -101,13 +103,13 @@
android:id="@+id/currencyFluctuationPercentageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/cardViewMainText" />
android:textSize="@dimen/cardViewTitle" />
<TextView
android:id="@+id/currencyFluctuationTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/cardViewSecondaryText" />
android:textSize="@dimen/cardViewCaption" />
</LinearLayout>
@ -129,7 +131,8 @@
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_delete_white_24dp"
app:srcCompat="@drawable/ic_delete_white_24dp"
android:background="@color/transparent"
android:clickable="false"
android:focusable="false"/>
@ -154,7 +157,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/day_history"
android:textSize="@dimen/cardViewSecondaryText" />
android:textSize="@dimen/cardViewCaption" />
<View
android:layout_width="match_parent"
@ -186,7 +189,7 @@
android:visibility="visible"/>
<FrameLayout
android:id="@+id/linearLayoutSubLayout"
android:id="@+id/linearLayoutSubCharts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
@ -202,7 +205,8 @@
android:id="@+id/detailsArrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_keyboard_arrow_right_grey_48dp"
app:srcCompat="@drawable/ic_keyboard_arrow_right_grey_48dp"
android:background="@color/transparent"
android:layout_gravity="center_vertical|end"/>
</FrameLayout>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".Activities.ExchangeListActivity"
tools:showIn="@layout/activity_exchange_list">
<ListView
android:id="@+id/exchange_listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/currencyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:gravity="center_vertical|center_horizontal"
android:textSize="15sp" />
<TextView
android:id="@+id/currencySymbol"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:gravity="center_vertical|center_horizontal"
android:textColor="@color/captionColor"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>

Some files were not shown because too many files have changed in this diff Show More