diff --git a/.idea/statistic.xml b/.idea/statistic.xml new file mode 100644 index 0000000..66820b8 --- /dev/null +++ b/.idea/statistic.xml @@ -0,0 +1,21 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 3c07cdd..e06f310 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,7 @@ -# Coinfolio - +# Coinfolio ![State](https://img.shields.io/badge/State-in%20development-red.svg) +This repository contains the source code of Coinfolio + + +# What is coinfolio ? + +Coinfolio is a handy cryptocurrency and ICO portfolio tracker. With its easy to use interface, you can easily watch your cryptocurrencies and ICOs fluctuate during the day/week/month or year. Coinfolio allows you to keep up with the Global Market Capitalization as well and Exchanges statistics. diff --git a/app/build.gradle b/app/build.gradle index 6a810b4..15ddffa 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -32,7 +32,6 @@ dependencies { implementation 'com.android.support:support-v4:27.1.0' implementation 'com.android.support:palette-v7:27.1.0' implementation 'com.daimajia.swipelayout:library:1.2.0@aar' - implementation 'com.github.armcha:SpaceNavigationView:1.6.0' implementation 'com.fasterxml.jackson.core:jackson-databind:2.8.5' implementation 'com.fasterxml.jackson.core:jackson-core:2.8.5' implementation 'com.fasterxml.jackson.core:jackson-annotations:2.8.5' @@ -42,7 +41,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.github.lecho:hellocharts-library:1.5.8@aar' + implementation 'com.wdullaer:materialdatetimepicker:3.5.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' diff --git a/app/release/app-release.apk b/app/release/app-release.apk index 9fdb3a9..09d965c 100644 Binary files a/app/release/app-release.apk and b/app/release/app-release.apk differ diff --git a/app/release/output.json b/app/release/output.json index 351ec99..375651e 100644 --- a/app/release/output.json +++ b/app/release/output.json @@ -1 +1 @@ -[{"outputType":{"type":"APK"},"apkInfo":{"type":"MAIN","splits":[],"versionCode":1},"path":"app-release.apk","properties":{"packageId":"com.nauk.coinfolio","split":"","minSdkVersion":"21"}}] \ No newline at end of file +[{"outputType":{"type":"APK"},"apkInfo":{"type":"MAIN","splits":[],"versionCode":1},"path":"app-release.apk","properties":{"packageId":"com.nauk.coinfolio","split":"","minSdkVersion":"23"}}] \ No newline at end of file diff --git a/app/src/main/java/com/nauk/coinfolio/Activities/CurrencyDetailsActivity.java b/app/src/main/java/com/nauk/coinfolio/Activities/CurrencyDetailsActivity.java index 80a78d3..2cabb4d 100644 --- a/app/src/main/java/com/nauk/coinfolio/Activities/CurrencyDetailsActivity.java +++ b/app/src/main/java/com/nauk/coinfolio/Activities/CurrencyDetailsActivity.java @@ -5,7 +5,10 @@ import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; +import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; @@ -14,7 +17,6 @@ import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.Log; -import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; @@ -24,46 +26,71 @@ import android.widget.LinearLayout; import android.widget.TextView; import android.widget.ViewFlipper; +import com.binance.api.client.domain.account.Trade; import com.daimajia.swipe.SwipeLayout; -import com.db.chart.model.LineSet; -import com.db.chart.tooltip.Tooltip; +import com.github.mikephil.charting.charts.BarChart; +import com.github.mikephil.charting.charts.CandleStickChart; import com.github.mikephil.charting.charts.LineChart; +import com.github.mikephil.charting.data.BarData; +import com.github.mikephil.charting.data.BarDataSet; +import com.github.mikephil.charting.data.BarEntry; +import com.github.mikephil.charting.data.CandleData; +import com.github.mikephil.charting.data.CandleDataSet; +import com.github.mikephil.charting.data.CandleEntry; import com.github.mikephil.charting.data.Entry; 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.interfaces.datasets.ILineDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; import com.nauk.coinfolio.DataManagers.CurrencyData.CurrencyDataChart; +import com.nauk.coinfolio.DataManagers.CurrencyData.CurrencyDetailsList; import com.nauk.coinfolio.DataManagers.CurrencyData.Transaction; import com.nauk.coinfolio.DataManagers.DatabaseManager; +import com.nauk.coinfolio.DataManagers.ExchangeManager.BinanceManager; +import com.nauk.coinfolio.DataManagers.PreferencesManager; import com.nauk.coinfolio.R; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Locale; +import static java.lang.Math.abs; + /**Create a Parcelable**/ public class CurrencyDetailsActivity extends AppCompatActivity { private ViewFlipper viewFlipper; private LinearLayout transactionLayout; - private LinearLayout chartLayout; + private LinearLayout tradeLayout; private DatabaseManager databaseManager; //private String symbol; private Currency currency; private boolean hasBeenModified; - private Tooltip tip; - private int indexMax; - private int indexMin; private final static int HOUR = 0; private final static int DAY = 1; private final static int WEEK = 2; private final static int MONTH = 3; private final static int YEAR = 4; + private List dataChartList; + private LineChart lineChart; + private CandleStickChart candleStickChart; + private BarChart barChart; + private PreferencesManager preferencesManager; + private BinanceManager binanceManager; + private CurrencyDetailsList currencyDetailsList; + + private boolean displayLineChart; + + private Button lineChartButton; + private Button candleStickChartButton; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @@ -98,7 +125,6 @@ public class CurrencyDetailsActivity extends AppCompatActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - // Respond to the action bar's Up/Home button case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; @@ -113,35 +139,87 @@ public class CurrencyDetailsActivity extends AppCompatActivity { Intent intent = getIntent(); - //symbol = intent.getStringExtra("symbol"); currency = intent.getParcelableExtra("currency"); databaseManager = new DatabaseManager(this); + preferencesManager = new PreferencesManager(this); + currencyDetailsList = new CurrencyDetailsList(this); + + displayLineChart = true; viewFlipper = findViewById(R.id.vfCurrencyDetails); transactionLayout = findViewById(R.id.listTransactions); - chartLayout = findViewById(R.id.chartsLayout); + tradeLayout = findViewById(R.id.listTrades); + lineChart = findViewById(R.id.chartPriceView); + candleStickChart = findViewById(R.id.chartCandleStickView); + barChart = findViewById(R.id.chartVolumeView); + lineChartButton = findViewById(R.id.lineChartButton); + candleStickChartButton = findViewById(R.id.candleStickChartButton); + binanceManager = new BinanceManager(preferencesManager.getBinancePublicKey(), preferencesManager.getBinancePrivateKey()); + + lineChartButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + lineChartButton.setEnabled(false); + candleStickChartButton.setEnabled(true); + + lineChart.setVisibility(View.VISIBLE); + candleStickChart.setVisibility(View.GONE); + + displayLineChart = true; + } + }); + + candleStickChartButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + lineChartButton.setEnabled(true); + candleStickChartButton.setEnabled(false); + + lineChart.setVisibility(View.GONE); + candleStickChart.setVisibility(View.VISIBLE); + + displayLineChart = false; + } + }); + + setupActionBar(); drawTransactionList(); - initializeButtons(); + updateInfoTab(); - if(currency.getHistoryMinutes().size() > 0) + initializeButtons(); + initializeLineChart(lineChart); + initializeCandleStickChart(candleStickChart); + + updateChartTab(DAY, 1); + + BottomNavigationView navigation = findViewById(R.id.navigation_details); + navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); + + hasBeenModified = false; + + TradeUpdater updater = new TradeUpdater(); + updater.execute(); + } + + private void updateInfoTab() + { + ((TextView) findViewById(R.id.txtViewTotalSupply)).setText(""); + } + + private void setupActionBar() + { + if(currency.getBalance() == 0) { - drawChart(DAY, 1); + setTitle(" " + currency.getName()); } else { - TextView errorTextView = new TextView(this); - errorTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 750)); - errorTextView.setText("Not enough data"); - errorTextView.setTag("chart_layout"); - errorTextView.setGravity(Gravity.CENTER); - - chartLayout.addView(errorTextView, 0); + setTitle(" " + currency.getName() + " | " + currency.getBalance()); } - setTitle(" " + currency.getName()); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO); @@ -157,10 +235,6 @@ public class CurrencyDetailsActivity extends AppCompatActivity { getSupportActionBar().setIcon(new BitmapDrawable(Bitmap.createScaledBitmap(result, 120, 120, false))); - BottomNavigationView navigation = findViewById(R.id.navigation_details); - navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); - - hasBeenModified = false; } private void initializeButtons() @@ -182,6 +256,7 @@ public class CurrencyDetailsActivity extends AppCompatActivity { private void buttonEvent(View v) { v.setEnabled(false); + v.setElevation(convertDpToPx(8)); LinearLayout buttonLayout = (LinearLayout) v.getParent(); @@ -192,15 +267,23 @@ public class CurrencyDetailsActivity extends AppCompatActivity { if(button != v) { button.setEnabled(true); + button.setElevation(convertDpToPx(2)); } } - chartEvent((Button) v); + updateCharts((Button) v); } - private void chartEvent(Button button) + private float convertDpToPx(float dp) { - findViewById(R.id.chartView).setVisibility(View.GONE); + return dp * this.getResources().getDisplayMetrics().density; + } + + private void updateCharts(Button button) + { + findViewById(R.id.chartPriceView).setVisibility(View.GONE); + findViewById(R.id.chartCandleStickView).setVisibility(View.GONE); + findViewById(R.id.chartVolumeView).setVisibility(View.GONE); findViewById(R.id.progressLayoutChart).setVisibility(View.VISIBLE); String interval = button.getText().toString().substring(button.getText().toString().length()-2); @@ -208,13 +291,13 @@ public class CurrencyDetailsActivity extends AppCompatActivity { switch (interval) { case "1h": - drawChart(HOUR, 1); + updateChartTab(HOUR, 1); break; case "3h": - drawChart(HOUR, 3); + updateChartTab(HOUR, 3); break; case "1d": - drawChart(DAY, 1); + updateChartTab(DAY, 1); break; case "3d": currency.updateHistoryHours(this, new Currency.CurrencyCallBack() { @@ -223,7 +306,7 @@ public class CurrencyDetailsActivity extends AppCompatActivity { runOnUiThread(new Runnable() { @Override public void run() { - drawChart(CurrencyDetailsActivity.DAY, 3); + updateChartTab(CurrencyDetailsActivity.DAY, 3); } }); } @@ -236,20 +319,20 @@ public class CurrencyDetailsActivity extends AppCompatActivity { runOnUiThread(new Runnable() { @Override public void run() { - drawChart(CurrencyDetailsActivity.WEEK, 1); + updateChartTab(CurrencyDetailsActivity.WEEK, 11); } }); } }); break; case "1M": - currency.updateHistoryDays(this, new Currency.CurrencyCallBack() { + currency.updateHistoryHours(this, new Currency.CurrencyCallBack() { @Override public void onSuccess(Currency currency) { runOnUiThread(new Runnable() { @Override public void run() { - drawChart(CurrencyDetailsActivity.MONTH, 1); + updateChartTab(CurrencyDetailsActivity.MONTH, 1); } }); } @@ -262,7 +345,7 @@ public class CurrencyDetailsActivity extends AppCompatActivity { runOnUiThread(new Runnable() { @Override public void run() { - drawChart(CurrencyDetailsActivity.MONTH, 3); + updateChartTab(CurrencyDetailsActivity.MONTH, 3); } }); } @@ -275,7 +358,7 @@ public class CurrencyDetailsActivity extends AppCompatActivity { runOnUiThread(new Runnable() { @Override public void run() { - drawChart(CurrencyDetailsActivity.MONTH, 6); + updateChartTab(CurrencyDetailsActivity.MONTH, 6); } }); } @@ -288,7 +371,7 @@ public class CurrencyDetailsActivity extends AppCompatActivity { runOnUiThread(new Runnable() { @Override public void run() { - drawChart(CurrencyDetailsActivity.YEAR, 1); + updateChartTab(CurrencyDetailsActivity.YEAR, 1); } }); } @@ -297,10 +380,142 @@ public class CurrencyDetailsActivity extends AppCompatActivity { } } - private void drawChart(int timeUnit, int amout) + private void updateChartTab(int timeUnit, int amount) { - final LineChart lineChart = findViewById(R.id.chartView); + updateChartsData(timeUnit, amount); + drawPriceLineChart(); + drawPriceCandleStickChart(); + if(displayLineChart) + { + findViewById(R.id.chartPriceView).setVisibility(View.VISIBLE); + findViewById(R.id.progressLayoutChart).setVisibility(View.GONE); + } + else + { + findViewById(R.id.chartCandleStickView).setVisibility(View.VISIBLE); + 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 updateChartsData(int timeUnit, int amount) + { + dataChartList = new ArrayList<>(); + + switch (timeUnit) + { + case HOUR: + dataChartList = currency.getHistoryMinutes().subList(currency.getHistoryMinutes().size()-(60*amount), currency.getHistoryMinutes().size()); + break; + case DAY: + if(amount == 1) + { + dataChartList = currency.getHistoryMinutes(); + } + else + { + 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()); + break; + case MONTH: + switch (amount) + { + case 1: + dataChartList = currency.getHistoryHours(); + break; + case 3: + 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()); + break; + } + break; + case YEAR: + dataChartList = currency.getHistoryDays(); + break; + } + } + + private void drawVolumeChart() + { + initializeBarChart(barChart); + + barChart.setData(generateVolumeChartSet()); + barChart.invalidate(); + + findViewById(R.id.chartVolumeView).setVisibility(View.VISIBLE); + } + + private void initializeBarChart(BarChart barChart) + { + barChart.setDrawGridBackground(false); + barChart.setDrawBorders(false); + barChart.setDrawMarkers(true); + barChart.setDoubleTapToZoomEnabled(true); + barChart.setPinchZoom(true); + barChart.setScaleEnabled(false); + barChart.setDragEnabled(true); + barChart.getDescription().setEnabled(false); + barChart.getAxisLeft().setEnabled(false); + barChart.getAxisRight().setEnabled(false); + barChart.getLegend().setEnabled(false); + barChart.getXAxis().setEnabled(false); + barChart.setViewPortOffsets(0, 0, 0, 0); + barChart.setFitBars(true); + } + + private void drawPriceCandleStickChart() + { + candleStickChart.setData(generatePriceCandleStickChartSet()); + } + + private void drawPriceLineChart() + { + lineChart.setData(generatePriceLineChartSet()); + lineChart.getAxisLeft().setAxisMinValue(lineChart.getData().getYMin()); + + lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { + @Override + public void onValueSelected(Entry e, Highlight h) { + valueSelectedEvent(e); + } + + @Override + public void onNothingSelected() { + + } + }); + + lineChart.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View view, MotionEvent motionEvent) { + return toucheEvent(motionEvent); + } + }); + } + + private void initializeCandleStickChart(CandleStickChart candleStickChart) + { + candleStickChart.setDrawGridBackground(false); + candleStickChart.setDrawBorders(false); + candleStickChart.setDrawMarkers(true); + candleStickChart.getDescription().setEnabled(false); + candleStickChart.getAxisLeft().setEnabled(true); + candleStickChart.getAxisRight().setEnabled(true); + candleStickChart.getLegend().setEnabled(false); + candleStickChart.getXAxis().setEnabled(true); + candleStickChart.setViewPortOffsets(0, 0, 0, 0); + } + + private void initializeLineChart(LineChart lineChart) + { lineChart.setDrawGridBackground(false); lineChart.setDrawBorders(false); lineChart.setDrawMarkers(true); @@ -314,114 +529,422 @@ public class CurrencyDetailsActivity extends AppCompatActivity { lineChart.getLegend().setEnabled(false); lineChart.getXAxis().setEnabled(false); lineChart.setViewPortOffsets(0, 0, 0, 0); - - lineChart.setData(generateChartSet(timeUnit, amout)); - lineChart.getAxisLeft().setAxisMinValue(lineChart.getData().getYMin()); - - lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { - @Override - public void onValueSelected(Entry e, Highlight h) { - updateFluctuation(lineChart.getData().getDataSets().get(0).getEntryForIndex(0).getY(), e.getY()); - } - - @Override - public void onNothingSelected() { - - } - }); - - lineChart.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - if(motionEvent.getAction() == MotionEvent.ACTION_UP) - { - //lineChart.highlightValue(lineChart.getData().getDataSetCount()-1, 0); - lineChart.highlightValue(null); - updateFluctuation(lineChart.getData().getDataSets().get(0).getEntryForIndex(0).getY(), lineChart.getData().getDataSets().get(0).getEntryForIndex(lineChart.getData().getDataSets().get(0).getEntryCount() - 1).getY()); - - } - return false; - } - }); - - updateFluctuation(lineChart.getData().getDataSets().get(0).getEntryForIndex(0).getY(), lineChart.getData().getDataSets().get(0).getEntryForIndex(lineChart.getData().getDataSets().get(0).getEntryCount() - 1).getY()); - - findViewById(R.id.chartView).setVisibility(View.VISIBLE); - findViewById(R.id.progressLayoutChart).setVisibility(View.GONE); } - private LineData generateChartSet(int timeUnit, int amount) + private void valueSelectedEvent(Entry e) + { + int index = lineChart.getData().getDataSets().get(0).getEntryIndex(e); + String date; + String volumePlaceholder; + String pricePlaceholder; + String timestampPlaceholder; + + barChart.highlightValue(barChart.getData().getDataSets().get(0).getEntryForIndex(index).getX(), 0, index); + + if(dataChartList.size() > 200) + { + date = getDate(dataChartList.get((int) Math.floor(dataChartList.size() / 200) * index).getTimestamp() * 1000); + } + else + { + date = getDate(dataChartList.get(index).getTimestamp() * 1000); + } + + volumePlaceholder = getResources().getString(R.string.volumePlaceholder, numberConformer(barChart.getData().getDataSets().get(0).getEntryForIndex(index).getY())); + pricePlaceholder = getResources().getString(R.string.pricePlaceholder, numberConformer(e.getY())); + timestampPlaceholder = getResources().getString(R.string.timestampPlaceholder, date); + + ((TextView) findViewById(R.id.volumeHightlight)).setText(volumePlaceholder); + findViewById(R.id.volumeHightlight).setVisibility(View.VISIBLE); + ((TextView) findViewById(R.id.priceHightlight)).setText(pricePlaceholder); + findViewById(R.id.priceHightlight).setVisibility(View.VISIBLE); + ((TextView) findViewById(R.id.timestampHightlight)).setText(timestampPlaceholder); + findViewById(R.id.timestampHightlight).setVisibility(View.VISIBLE); + + } + + private boolean toucheEvent(MotionEvent motionEvent) + { + if(motionEvent.getAction() == MotionEvent.ACTION_UP) + { + lineChart.highlightValue(null); + updateFluctuation(lineChart.getData().getDataSets().get(0).getEntryForIndex(0).getY(), lineChart.getData().getDataSets().get(0).getEntryForIndex(lineChart.getData().getDataSets().get(0).getEntryCount() - 1).getY()); + barChart.highlightValues(null); + hideDataIndicators(); + } + + return false; + } + + private void hideDataIndicators() + { + ((TextView) findViewById(R.id.volumeHightlight)).setText(".\n."); + findViewById(R.id.volumeHightlight).setVisibility(View.INVISIBLE); + ((TextView) findViewById(R.id.priceHightlight)).setText(".\n."); + findViewById(R.id.priceHightlight).setVisibility(View.INVISIBLE); + ((TextView) findViewById(R.id.timestampHightlight)).setText(".\n."); + findViewById(R.id.timestampHightlight).setVisibility(View.INVISIBLE); + } + + private String getDate(long timeStamp){ + + try{ + SimpleDateFormat sdf = new SimpleDateFormat(" HH:mm dd/MM/yyyy", Locale.getDefault()); + Date netDate = (new Date(timeStamp)); + return sdf.format(netDate); + } + catch(Exception ex){ + return "xx"; + } + } + + private BarData generateVolumeChartSet() + { + BarDataSet dataSet; + ArrayList values = new ArrayList<>(); + + int offset = (int) Math.floor(dataChartList.size() / 200); + + if(offset < 1) + { + offset = 1; + } + + for(int i = 0, j = 0; i < dataChartList.size(); i += offset, j++) + { + values.add(new BarEntry(j, (float) dataChartList.get(j).getVolumeTo())); + } + + dataSet = new BarDataSet(values, "Volume"); + dataSet.setDrawIcons(false); + dataSet.setColor(Color.GRAY); + dataSet.setDrawValues(false); + dataSet.setHighlightEnabled(true); + dataSet.setHighLightColor(currency.getChartColor()); + + return new BarData(dataSet); + } + + private String numberConformer(double number) + { + String str; + DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK); + DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols(); + + symbols.setGroupingSeparator(' '); + formatter.setDecimalFormatSymbols(symbols); + + if(abs(number) > 1) + { + str = formatter.format(number); + } + else + { + str = String.format( Locale.UK, "%.4f", number); + } + + return str; + } + + private CandleData generatePriceCandleStickChartSet() + { + CandleDataSet dataSet; + ArrayList values = new ArrayList<>(); + + int offsetRange = (int) Math.floor(dataChartList.size() / 200); + + if(offsetRange < 1) + { + offsetRange = 1; + } + + for(int i = 0, j = 0; i < dataChartList.size(); i+= offsetRange, j++) + { + values.add(new CandleEntry(j, (float) dataChartList.get(i).getHigh() + , (float) dataChartList.get(i).getLow() + , (float) dataChartList.get(i).getOpen() + , (float) dataChartList.get(i).getClose())); + } + + dataSet = new CandleDataSet(values, "History"); + dataSet.setDrawIcons(false); + dataSet.setDrawValues(false); + dataSet.setDecreasingColor(getColor(R.color.decreaseCandle)); + dataSet.setShowCandleBar(true); + dataSet.setShadowColorSameAsCandle(true); + dataSet.setDecreasingPaintStyle(Paint.Style.FILL); + dataSet.setIncreasingColor(getColor(R.color.increaseCandle)); + dataSet.setIncreasingPaintStyle(Paint.Style.STROKE); + dataSet.setNeutralColor(getColor(R.color.increaseCandle)); + dataSet.setHighLightColor(getColor(R.color.colorAccent)); + dataSet.setDrawHorizontalHighlightIndicator(false); + + return new CandleData(dataSet); + } + + private LineData generatePriceLineChartSet() { LineDataSet dataSet; - List dataChartList = new ArrayList<>(); ArrayList values = new ArrayList<>(); - int counter = 0; - Calendar calendar = Calendar.getInstance(Locale.FRANCE); - String hour; - String minute; - String dayName = ""; - String dayNumber; - String monthName = ""; - String monthNumber; - int offset = 10; - int pointFormat = HOUR; + int offsetRange = (int) Math.floor(dataChartList.size() / 200); - switch (timeUnit) + if(offsetRange < 1) { - case HOUR: - dataChartList = currency.getHistoryMinutes().subList(currency.getHistoryMinutes().size()-(60*amount), currency.getHistoryMinutes().size()); - offset = 10 * amount; - pointFormat = HOUR; - break; - case DAY: - if(amount == 1) + offsetRange = 1; + } + + for(int i = 0, j = 0; i < dataChartList.size(); i += offsetRange, j++) + { + values.add(new Entry(j, (float) dataChartList.get(i).getOpen())); + } + + dataSet = new LineDataSet(values, "History"); + dataSet.setDrawIcons(false); + dataSet.setColor(currency.getChartColor()); + dataSet.setLineWidth(1); + dataSet.setDrawFilled(true); + dataSet.setFillColor(getColorWithAlpha(currency.getChartColor(), 0.5f)); + dataSet.setFormLineWidth(1); + dataSet.setFormSize(15); + dataSet.setDrawCircles(false); + dataSet.setDrawValues(false); + dataSet.setHighlightEnabled(true); + dataSet.setDrawHorizontalHighlightIndicator(false); + dataSet.setHighLightColor(currency.getChartColor()); + + Drawable fillDrawable = ContextCompat.getDrawable(this, R.drawable.linear_chart_gradient); + fillDrawable.setColorFilter(getColorWithAlpha(currency.getChartColor(), 0.5f), PorterDuff.Mode.SRC_ATOP); + + return new LineData(dataSet); + } + + private void updateGeneralData(float start, float end) + { + double totalVolume = dataChartList.get(0).getVolumeTo(); + double highestPrice = dataChartList.get(0).getOpen(); + double lowestPrice = dataChartList.get(0).getOpen(); + + updateFluctuation(start, end); + + ((TextView) findViewById(R.id.txtViewPriceStart)).setText(getResources().getString(R.string.currencyDollarPlaceholder, numberConformer(start))); + ((TextView) findViewById(R.id.txtViewPriceNow)).setText(getResources().getString(R.string.currencyDollarPlaceholder, numberConformer(end))); + + for(int i = 1; i < dataChartList.size(); i++) + { + totalVolume += dataChartList.get(i).getVolumeTo(); + + if(highestPrice < dataChartList.get(i).getOpen()) + { + highestPrice = dataChartList.get(i).getOpen(); + } + + if(lowestPrice > dataChartList.get(i).getOpen()) + { + lowestPrice = dataChartList.get(i).getOpen(); + } + } + + ((TextView) findViewById(R.id.totalVolume)).setText(getResources().getString(R.string.currencyDollarPlaceholder, numberConformer(totalVolume))); + ((TextView) findViewById(R.id.highestPrice)).setText(getResources().getString(R.string.currencyDollarPlaceholder, numberConformer(highestPrice))); + ((TextView) findViewById(R.id.lowestPrice)).setText(getResources().getString(R.string.currencyDollarPlaceholder, numberConformer(lowestPrice))); + } + + private void updateFluctuation(float start, float end) + { + float fluctuation = end - start; + float percentageFluctuation = (fluctuation / start * 100); + + if(percentageFluctuation < 0) + { + ((TextView) findViewById(R.id.txtViewPercentage)).setTextColor(getResources().getColor(R.color.red)); + } + else + { + ((TextView) findViewById(R.id.txtViewPercentage)).setTextColor(getResources().getColor(R.color.green)); + } + + ((TextView) findViewById(R.id.txtViewPercentage)).setText(getResources().getString(R.string.currencyPercentagePlaceholder, numberConformer(percentageFluctuation))); + } + + private int getColorWithAlpha(int color, float ratio) + { + int transColor; + int alpha = Math.round(Color.alpha(color) * ratio); + int r = Color.red(color); + int g = Color.green(color); + int b = Color.blue(color); + + transColor = Color.argb(alpha, r, g, b); + + return transColor; + } + + private void drawTradeList(HashMap> trades) + { + findViewById(R.id.tradeProgressBar).setVisibility(View.GONE); + + tradeLayout.removeAllViews(); + + for(String key : trades.keySet()) + { + for(int i = trades.get(key).size()-1; i >= 0; i--) + { + View view = LayoutInflater.from(this).inflate(R.layout.custom_trade_row, null); + TextView amountTxtView = view.findViewById(R.id.amountPurchased); + TextView purchasedPrice = view.findViewById(R.id.purchasedPrice); + TextView tradePair = view.findViewById(R.id.pair); + TextView dateTxtView = view.findViewById(R.id.tradeDate); + View tradeIndicator = view.findViewById(R.id.tradeIndicator); + + if(trades.get(key).get(i).isBuyer()) { - dataChartList = currency.getHistoryMinutes(); - offset = 10 * 24; - pointFormat = HOUR; + tradeIndicator.setBackgroundColor(getColor(R.color.green)); } else { - dataChartList = currency.getHistoryHours().subList(currency.getHistoryHours().size()-(24*amount), currency.getHistoryHours().size()); - offset = 24; - pointFormat = DAY; + tradeIndicator.setBackgroundColor(getColor(R.color.red)); } - break; - case WEEK: - dataChartList = currency.getHistoryHours().subList(currency.getHistoryHours().size()-168, currency.getHistoryHours().size()); - offset = 28; - pointFormat = DAY; - break; - case MONTH: - switch (amount) - { - case 1: - dataChartList = currency.getHistoryHours(); - offset = 124; - pointFormat = MONTH; - break; - case 3: - dataChartList = currency.getHistoryDays().subList(currency.getHistoryDays().size()-93, currency.getHistoryDays().size()); - offset = 15; - pointFormat = MONTH; - break; - case 6: - dataChartList = currency.getHistoryDays().subList(currency.getHistoryDays().size()-186, currency.getHistoryDays().size()); - offset = 31; - pointFormat = MONTH; - break; + + amountTxtView.setText(String.valueOf(trades.get(key).get(i).getQty())); + purchasedPrice.setText(trades.get(key).get(i).getPrice()); + dateTxtView.setText(getDate(trades.get(key).get(i).getTime())); + tradePair.setText(currency.getSymbol() + "/" + key); + + tradeLayout.addView(view); + } + } + } + + private void drawTransactionList() + { + transactionLayout.removeAllViews(); + + List transactionList = databaseManager.getCurrencyTransactions(currency.getSymbol()); + + for(int i = 0; i < transactionList.size(); i++) + { + View view = LayoutInflater.from(this).inflate(R.layout.custom_transaction_row, null); + TextView amountTxtView = view.findViewById(R.id.amountPurchased); + TextView valueTxtView = view.findViewById(R.id.puchasedValue); + TextView dateTxtView = view.findViewById(R.id.purchaseDate); + + dateTxtView.setText(getDate(transactionList.get(i).getTimestamp())); + + LinearLayout deleteLayout = view.findViewById(R.id.deleteTransactionLayout); + deleteLayout.setTag(transactionList.get(i).getTransactionId()); + + deleteLayout.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + preferencesManager.setMustUpdateSummary(true); + databaseManager.deleteTransactionFromId(Integer.parseInt(view.getTag().toString())); + drawTransactionList(); + hasBeenModified = true; } - break; - case YEAR: - dataChartList = currency.getHistoryDays(); - offset = 30; - pointFormat = YEAR; - break; + }); + + amountTxtView.setText(String.valueOf(transactionList.get(i).getAmount())); + + setupSwipeView(view); + + transactionLayout.addView(view); + } + } + + private void setupSwipeView(View view) + { + SwipeLayout swipeLayout = view.findViewById(R.id.swipeLayout); + + //set show mode. + swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown); + + //add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary) + swipeLayout.addDrag(SwipeLayout.DragEdge.Left, view.findViewById(R.id.bottom_wrapper)); + + swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() { + @Override + public void onClose(SwipeLayout layout) { + //when the SurfaceView totally cover the BottomView. + } + + @Override + public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) { + //you are swiping. + } + + @Override + public void onStartOpen(SwipeLayout layout) { + + } + + @Override + public void onOpen(SwipeLayout layout) { + //when the BottomView totally show. + } + + @Override + public void onStartClose(SwipeLayout layout) { + + } + + @Override + public void onHandRelease(SwipeLayout layout, float xvel, float yvel) { + //when user's hand released. + } + }); + } + + private class TradeUpdater extends AsyncTask + { + @Override + protected void onPreExecute() + { + super.onPreExecute(); + + findViewById(R.id.tradeProgressBar).setVisibility(View.VISIBLE); } - for(int i = 0; i < dataChartList.size(); i++) + @Override + protected void onProgressUpdate(Integer... values) { + super.onProgressUpdate(values); + } + + @Override + protected Void doInBackground(Void... params) + { + binanceManager.updateTrades(new BinanceManager.BinanceCallBack() { + @Override + public void onSuccess() { + final HashMap> trades = binanceManager.getTrades(); + + runOnUiThread(new Runnable() { + @Override + public void run() { + drawTradeList(trades); + } + }); + } + + @Override + public void onError(String error) { + + } + }, currency.getSymbol()); + + return null; + } + + @Override + protected void onPostExecute(Void result) + { + + } + } +} +/*for(int i = 0; i < dataChartList.size(); i++) + {*/ /*if(counter == offset) { calendar.setTimeInMillis(dataChartList.get(i).getTimestamp()*1000); @@ -543,350 +1066,5 @@ public class CurrencyDetailsActivity extends AppCompatActivity { counter++; lineSet.addPoint("", (float) dataChartList.get(i).getOpen()); }*/ - values.add(new Entry(i, (float) dataChartList.get(i).getOpen())); - } - - dataSet = new LineDataSet(values, "History"); - dataSet.setDrawIcons(false); - dataSet.setColor(currency.getChartColor()); - dataSet.setLineWidth(1); - dataSet.setDrawFilled(true); - dataSet.setFillColor(getColorWithAlpha(currency.getChartColor(), 0.5f)); - dataSet.setFormLineWidth(1); - dataSet.setFormSize(15); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setHighlightEnabled(true); - dataSet.setDrawHorizontalHighlightIndicator(false); - dataSet.setHighLightColor(currency.getChartColor()); - - return new LineData(dataSet); - } - - private void updateFluctuation(float start, float end) - { - float fluctuation = end - start; - float percentageFluctuation = (float) (fluctuation / start * 100); - - if(percentageFluctuation < 0) - { - ((TextView) findViewById(R.id.txtViewPercentage)).setTextColor(getResources().getColor(R.color.red)); - } - else - { - ((TextView) findViewById(R.id.txtViewPercentage)).setTextColor(getResources().getColor(R.color.green)); - } - - ((TextView) findViewById(R.id.txtViewPriceStart)).setText("$" + start); - ((TextView) findViewById(R.id.txtViewPriceNow)).setText("$" + end); - ((TextView) findViewById(R.id.txtViewPercentage)).setText(percentageFluctuation + "%"); - } - - private void updateFluctuation(LineData lineData) - { - ILineDataSet dataSet = lineData.getDataSets().get(0); - - float fluctuation = dataSet.getEntryForIndex(dataSet.getEntryCount() - 1).getY() - dataSet.getEntryForIndex(0).getY(); - float percentageFluctuation = (float) (fluctuation / dataSet.getEntryForIndex(0).getY() * 100); - - if(percentageFluctuation < 0) - { - ((TextView) findViewById(R.id.txtViewPercentage)).setTextColor(getResources().getColor(R.color.red)); - } - else - { - ((TextView) findViewById(R.id.txtViewPercentage)).setTextColor(getResources().getColor(R.color.green)); - } - - ((TextView) findViewById(R.id.txtViewPriceStart)).setText("$" + dataSet.getEntryForIndex(0).getY()); - ((TextView) findViewById(R.id.txtViewPriceNow)).setText("$" + dataSet.getEntryForIndex(dataSet.getEntryCount() - 1).getY()); - ((TextView) findViewById(R.id.txtViewPercentage)).setText(percentageFluctuation + "%"); - } - - /*private LineSet generateChartSet(int timeUnit, int amount) - { - List dataChartList = new ArrayList<>(); - LineSet lineSet = new LineSet(); - int counter = 0; - Calendar calendar = Calendar.getInstance(Locale.FRANCE); - String hour; - String minute; - String dayName = ""; - String dayNumber; - String monthName = ""; - String monthNumber; - int offset = 10; - int pointFormat = HOUR; - - switch (timeUnit) - { - case HOUR: - dataChartList = currency.getHistoryMinutes().subList(currency.getHistoryMinutes().size()-(60*amount), currency.getHistoryMinutes().size()); - offset = 10 * amount; - pointFormat = HOUR; - break; - case DAY: - if(amount == 1) - { - dataChartList = currency.getHistoryMinutes(); - offset = 10 * 24; - pointFormat = HOUR; - } - else - { - dataChartList = currency.getHistoryHours().subList(currency.getHistoryHours().size()-(24*amount), currency.getHistoryHours().size()); - offset = 24; - pointFormat = DAY; - } - break; - case WEEK: - dataChartList = currency.getHistoryHours().subList(currency.getHistoryHours().size()-168, currency.getHistoryHours().size()); - offset = 28; - pointFormat = DAY; - break; - case MONTH: - switch (amount) - { - case 1: - dataChartList = currency.getHistoryHours(); - offset = 124; - pointFormat = MONTH; - break; - case 3: - dataChartList = currency.getHistoryDays().subList(currency.getHistoryDays().size()-93, currency.getHistoryDays().size()); - offset = 15; - pointFormat = MONTH; - break; - case 6: - dataChartList = currency.getHistoryDays().subList(currency.getHistoryDays().size()-186, currency.getHistoryDays().size()); - offset = 31; - pointFormat = MONTH; - break; - } - break; - case YEAR: - dataChartList = currency.getHistoryDays(); - offset = 30; - pointFormat = YEAR; - break; - } - - for(int i = 0; i < dataChartList.size(); i++) - { - if(counter == offset) - { - calendar.setTimeInMillis(dataChartList.get(i).getTimestamp()*1000); - - switch (pointFormat) - { - case HOUR: - hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)); - minute = String.valueOf(calendar.get(Calendar.MINUTE)); - - if(hour.length() < 2) - { - hour = "0" + hour; - } - - if(minute.length() < 2) - { - minute = "0" + minute; - } - - lineSet.addPoint(hour + ":" + minute, (float) dataChartList.get(i).getOpen()); - break; - case DAY: - int dayIndex = calendar.get(Calendar.DAY_OF_WEEK)+1; - - switch (dayIndex) - { - case Calendar.MONDAY: - dayName = "Mon"; - break; - case Calendar.TUESDAY: - dayName = "Tue"; - break; - case Calendar.WEDNESDAY: - dayName = "Wed"; - break; - case Calendar.THURSDAY: - dayName = "Thu"; - break; - case Calendar.FRIDAY: - dayName = "Fri"; - break; - case Calendar.SATURDAY: - dayName = "Sat"; - break; - case Calendar.SUNDAY: - dayName = "Sun"; - break; - } - - lineSet.addPoint(dayName, (float) dataChartList.get(i).getOpen()); - break; - case MONTH: - dayNumber = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)+1); - monthNumber = String.valueOf(calendar.get(Calendar.MONTH)+1); - - if(dayNumber.length() < 2) - { - dayNumber = '0' + dayNumber; - } - - if(monthNumber.length() < 2) - { - monthNumber = '0' + monthNumber; - } - - lineSet.addPoint(dayNumber + "/" + monthNumber, (float) dataChartList.get(i).getOpen()); - break; - case YEAR: - int mb = calendar.get(Calendar.MONTH); - - switch (mb) - { - case Calendar.JANUARY: - monthName = "Jan"; - break; - case Calendar.FEBRUARY: - monthName = "Feb"; - break; - case Calendar.MARCH: - monthName = "Mar"; - break; - case Calendar.APRIL: - monthName = "Apr"; - break; - case Calendar.MAY: - monthName = "May"; - break; - case Calendar.JUNE: - monthName = "Jun"; - break; - case Calendar.JULY: - monthName = "Jul"; - break; - case Calendar.AUGUST: - monthName = "Aug"; - break; - case Calendar.SEPTEMBER: - monthName = "Sep"; - break; - case Calendar.OCTOBER: - monthName = "Oct"; - break; - case Calendar.NOVEMBER: - monthName = "Nov"; - break; - case Calendar.DECEMBER: - monthName = "Dec"; - break; - } - - lineSet.addPoint(monthName, (float) dataChartList.get(i).getOpen()); - break; - } - counter = 0; - } - else - { - counter++; - lineSet.addPoint("", (float) dataChartList.get(i).getOpen()); - } - } - - lineSet.setSmooth(true); - lineSet.setThickness(3); - lineSet.setFill(getColorWithAlpha(currency.getChartColor(), 0.5f)); - lineSet.setColor(currency.getChartColor()); - - return lineSet; - }*/ - - private int getColorWithAlpha(int color, float ratio) - { - int transColor; - int alpha = Math.round(Color.alpha(color) * ratio); - int r = Color.red(color); - int g = Color.green(color); - int b = Color.blue(color); - - transColor = Color.argb(alpha, r, g, b); - - return transColor; - } - - private void drawTransactionList() - { - transactionLayout.removeAllViews(); - - List transactionList = databaseManager.getCurrencyTransactions(currency.getSymbol()); - - for(int i = 0; i < transactionList.size(); i++) - { - View view = LayoutInflater.from(this).inflate(R.layout.custom_transaction_row, null); - TextView amountTxtView = view.findViewById(R.id.amountPurchased); - TextView valueTxtView = view.findViewById(R.id.puchasedValue); - TextView dateTxtView = view.findViewById(R.id.purchaseDate); - - LinearLayout deleteLayout = view.findViewById(R.id.deleteTransactionLayout); - deleteLayout.setTag(transactionList.get(i).getTransactionId()); - - deleteLayout.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - databaseManager.deleteTransactionFromId(Integer.parseInt(view.getTag().toString())); - drawTransactionList(); - hasBeenModified = true; - } - }); - - amountTxtView.setText(transactionList.get(i).getAmount() + ""); - - SwipeLayout swipeLayout = view.findViewById(R.id.swipeLayout); - - //set show mode. - swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown); - - //add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary) - swipeLayout.addDrag(SwipeLayout.DragEdge.Left, view.findViewById(R.id.bottom_wrapper)); - - swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() { - @Override - public void onClose(SwipeLayout layout) { - //when the SurfaceView totally cover the BottomView. - } - - @Override - public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) { - //you are swiping. - } - - @Override - public void onStartOpen(SwipeLayout layout) { - - } - - @Override - public void onOpen(SwipeLayout layout) { - //when the BottomView totally show. - } - - @Override - public void onStartClose(SwipeLayout layout) { - - } - - @Override - public void onHandRelease(SwipeLayout layout, float xvel, float yvel) { - //when user's hand released. - } - }); - - transactionLayout.addView(view); - } - - } - -} + /*values.add(new Entry(i, (float) dataChartList.get(i).getOpen())); + }*/ \ No newline at end of file diff --git a/app/src/main/java/com/nauk/coinfolio/Activities/CurrencySelectionActivity.java b/app/src/main/java/com/nauk/coinfolio/Activities/CurrencySelectionActivity.java index 364de08..da5c84c 100644 --- a/app/src/main/java/com/nauk/coinfolio/Activities/CurrencySelectionActivity.java +++ b/app/src/main/java/com/nauk/coinfolio/Activities/CurrencySelectionActivity.java @@ -1,30 +1,39 @@ package com.nauk.coinfolio.Activities; import android.content.Intent; +import android.os.AsyncTask; import android.os.Bundle; +import android.os.Looper; import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.CardView; import android.text.TextUtils; -import android.view.Menu; import android.view.View; import android.view.Window; import android.view.WindowManager; +import android.view.animation.Animation; +import android.view.animation.Transformation; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SearchView; +import com.nauk.coinfolio.DataManagers.BalanceManager; import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; -import com.nauk.coinfolio.LayoutManagers.CurrencyAdapter; +import com.nauk.coinfolio.DataManagers.CurrencyData.CurrencyDetailsList; +import com.nauk.coinfolio.DataManagers.DatabaseManager; +import com.nauk.coinfolio.DataManagers.PreferencesManager; +import com.nauk.coinfolio.LayoutManagers.CurrencyListAdapter; import com.nauk.coinfolio.R; import java.util.ArrayList; +import java.util.List; public class CurrencySelectionActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{ - private String[] currencySymbols; - private String[] currencyNames; - private CurrencyAdapter adapter; + private CurrencyListAdapter adapter; private ListView listView; private android.widget.Filter filter; + private CurrencyDetailsList currencyDetailsList; + private boolean isWatchList; @Override protected void onCreate(Bundle savedInstanceState) { @@ -35,17 +44,19 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear setContentView(R.layout.activity_add_currency); - Intent intent = getIntent(); - - currencySymbols = intent.getStringArrayExtra("currencyListSymbols"); - currencyNames = intent.getStringArrayExtra("currencyListNames"); + currencyDetailsList = new CurrencyDetailsList(this); setTitle("Select a coin"); - setupAdapter(); + Intent intent = getIntent(); + isWatchList = intent.getBooleanExtra("isWatchList", false); - setupList(); + ListLoader listLoader = new ListLoader(); + listLoader.execute(); + } + private void setupSearchView() + { SearchView searchView = findViewById(R.id.search_bar); searchView.setIconifiedByDefault(false); @@ -56,21 +67,17 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear private void setupAdapter() { - String[] currencyFullname = new String[currencyNames.length]; - - for(int i = 0; i < currencyFullname.length; i++) - { - currencyFullname[i] = currencyNames[i] + " " + currencySymbols[i]; - } + List currencyNames = currencyDetailsList.getCurrenciesName(); + List currencySymbols = currencyDetailsList.getCurrenciesSymbol(); ArrayList currencyArrayList = new ArrayList<>(); - for(int i = 0; i < currencyNames.length; i++) + for(int i = 0; i < currencyNames.size(); i++) { - currencyArrayList.add(new Currency(currencyNames[i], currencySymbols[i])); + currencyArrayList.add(new Currency(currencyNames.get(i), currencySymbols.get(i))); } - adapter = new CurrencyAdapter(this, currencyArrayList); + adapter = new CurrencyListAdapter(this, currencyArrayList); } private void setupList() @@ -84,10 +91,23 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { Currency selectedCurrency = (Currency) adapterView.getItemAtPosition(i); - Intent intent = new Intent(CurrencySelectionActivity.this, RecordTransactionActivity.class); - intent.putExtra("coin", selectedCurrency.getName()); - intent.putExtra("symbol", selectedCurrency.getSymbol()); - startActivity(intent); + + if(isWatchList) + { + PreferencesManager preferencesManager = new PreferencesManager(getApplicationContext()); + DatabaseManager databaseManager = new DatabaseManager(getApplicationContext()); + + databaseManager.addCurrencyToWatchlist(selectedCurrency); + preferencesManager.setMustUpdateWatchlist(true); + } + else + { + Intent intent = new Intent(CurrencySelectionActivity.this, RecordTransactionActivity.class); + intent.putExtra("coin", selectedCurrency.getName()); + intent.putExtra("symbol", selectedCurrency.getSymbol()); + startActivity(intent); + } + finish(); } }); @@ -95,27 +115,32 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear filter = adapter.getFilter(); } - @Override - public boolean onCreateOptionsMenu(Menu menu) - { - /*final AutoCompleteTextView searchAutoComplete = findViewById(R.id.search_bar); + private static void expand(final View v) { + v.measure(CardView.LayoutParams.MATCH_PARENT, CardView.LayoutParams.WRAP_CONTENT); + final int targetHeight = v.getMeasuredHeight(); - searchAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() { + // Older versions of android (pre API 21) cancel animations for views with a height of 0. + v.getLayoutParams().height = 1; + v.setVisibility(View.VISIBLE); + Animation a = new Animation() + { @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - Currency selectedCurrency = (Currency) adapterView.getItemAtPosition(i); - Intent intent = new Intent(CurrencySelectionActivity.this, RecordTransactionActivity.class); - intent.putExtra("coin", selectedCurrency.getName()); - intent.putExtra("symbol", selectedCurrency.getSymbol()); - startActivity(intent); - finish(); + protected void applyTransformation(float interpolatedTime, Transformation t) { + v.getLayoutParams().height = interpolatedTime == 1 + ? CardView.LayoutParams.WRAP_CONTENT + : (int)(targetHeight * interpolatedTime); + v.requestLayout(); } - }); - searchAutoComplete.setAdapter(adapter); - searchAutoComplete.setThreshold(0);*/ + @Override + public boolean willChangeBounds() { + return true; + } + }; - return true; + // 1dp/ms + a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density)); + v.startAnimation(a); } @Override @@ -136,4 +161,55 @@ public class CurrencySelectionActivity extends AppCompatActivity implements Sear { return false; } + + private class ListLoader extends AsyncTask + { + @Override + protected void onPreExecute() + { + super.onPreExecute(); + } + + @Override + protected void onProgressUpdate(Integer... values) + { + super.onProgressUpdate(values); + } + + @Override + protected Void doInBackground(Void... params) + { + if(Looper.myLooper() == null) + { + Looper.prepare(); + } + + currencyDetailsList.update(new BalanceManager.IconCallBack() { + @Override + public void onSuccess() { + setupAdapter(); + + setupList(); + + runOnUiThread(new Runnable() { + @Override + public void run() { + setupSearchView(); + + expand(findViewById(R.id.listContainerLayout)); + findViewById(R.id.currencyListProgressBar).setVisibility(View.GONE); + } + }); + } + }); + + return null; + } + + @Override + protected void onPostExecute(Void result) + { + + } + } } diff --git a/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivity.java b/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivity.java index b3f63a9..16f734e 100644 --- a/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivity.java +++ b/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivity.java @@ -6,7 +6,6 @@ import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; -import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; @@ -15,47 +14,40 @@ import android.support.annotation.NonNull; import android.support.design.widget.AppBarLayout; import android.support.design.widget.BottomNavigationView; import android.support.design.widget.CollapsingToolbarLayout; -import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; +import android.support.v4.view.ViewPager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.graphics.Palette; import android.support.v7.widget.Toolbar; import android.text.SpannableString; -import android.text.style.ForegroundColorSpan; -import android.text.style.RelativeSizeSpan; -import android.text.style.StyleSpan; import android.util.Log; -import android.view.DragEvent; import android.view.Gravity; +import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowManager; +import android.view.ViewParent; +import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.ViewFlipper; -import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.formatter.PercentFormatter; -import com.github.mikephil.charting.utils.ColorTemplate; -import com.luseen.spacenavigation.SpaceItem; -import com.luseen.spacenavigation.SpaceNavigationView; -import com.luseen.spacenavigation.SpaceOnClickListener; import com.nauk.coinfolio.DataManagers.BalanceManager; import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; import com.nauk.coinfolio.DataManagers.MarketCapManager; import com.nauk.coinfolio.DataManagers.PreferencesManager; import com.nauk.coinfolio.LayoutManagers.HomeLayoutGenerator; +import com.nauk.coinfolio.PagerAdapter; import com.nauk.coinfolio.R; import java.io.IOException; @@ -69,7 +61,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; -import java.util.Random; //Use WilliamChart for charts https://github.com/diogobernardino/WilliamChart @@ -84,46 +75,34 @@ import java.util.Random; public class HomeActivity extends AppCompatActivity { private PreferencesManager preferencesManager; - private HomeLayoutGenerator layoutGenerator; - private BalanceManager balanceManager; - private MarketCapManager marketCapManager; - - private int coinCounter; - private int iconCounter; - private int marketCapCounter; - private long lastTimestamp; - private boolean detailsChecker; - private boolean isDetailed; private CollapsingToolbarLayout toolbarLayout; - private SwipeRefreshLayout refreshLayout; - private LinearLayout currencyLayout; - private TextView toolbarSubtitle; - private Dialog loadingDialog; - private Handler handler; - private Runnable updateRunnable; private ViewFlipper viewFlipper; + private HomeLayoutGenerator layoutGenerator; + private BottomNavigationView bottomNavigationView; - private HashMap dominantCurrenciesColors; + private ViewPager viewPager; - private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener + + private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { - switch (item.getItemId()) { - case R.id.navigation_something: - - //((FloatingActionButton) findViewById(R.id.floatingAddButton)).hide(); - return true; - case R.id.navigation_view_list: - //((FloatingActionButton) findViewById(R.id.floatingAddButton)).show(); - //viewFlipper.setDisplayedChild(1); - return true; + item.setChecked(true); + switch (item.getItemId()) + { + case R.id.navigation_watchlist: + ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(false, true); + viewPager.setCurrentItem(0); + break; + case R.id.navigation_currencies_list: + viewPager.setCurrentItem(1); + break; case R.id.navigation_market_cap: - //((FloatingActionButton) findViewById(R.id.floatingAddButton)).hide(); - //viewFlipper.setDisplayedChild(2); - return true; + ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(false, true); + viewPager.setCurrentItem(2); + break; } return false; } @@ -136,72 +115,54 @@ public class HomeActivity extends AppCompatActivity { /**Interface setup**/ //Setup main interface - requestWindowFeature(Window.FEATURE_NO_TITLE); - this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + //requestWindowFeature(Window.FEATURE_NO_TITLE); + //getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); + //this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); + setContentView(R.layout.activity_currency_summary); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); - generateSplash(); + viewPager = findViewById(R.id.viewPager); + final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), 3); + + viewPager.setAdapter(adapter); + viewPager.setOffscreenPageLimit(2); + viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + bottomNavigationView.getMenu().getItem(position).setChecked(true); + + if(position % 2 == 0) + { + ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(false, true); + } + } + + @Override + public void onPageSelected(int position) { + + } + + @Override + public void onPageScrollStateChanged(int state) { + + } + }); //Objects initialization preferencesManager = new PreferencesManager(this); - layoutGenerator = new HomeLayoutGenerator(this); - balanceManager = new BalanceManager(this); - marketCapManager = new MarketCapManager(this); - handler = new Handler(); - updateRunnable = new Runnable() { - @Override - public void run() { - if (refreshLayout.isRefreshing()) - { - refreshLayout.setRefreshing(false); - - showErrorSnackbar(); - } - - if (loadingDialog.isShowing()) - { - loadingDialog.dismiss(); - - showErrorSnackbar(); - } - } - }; - - isDetailed = preferencesManager.getDetailOption(); //Layouts setup - refreshLayout = findViewById(R.id.swiperefresh); toolbarLayout = findViewById(R.id.toolbar_layout); - toolbarSubtitle = findViewById(R.id.toolbarSubtitle); - currencyLayout = findViewById(R.id.currencyListLayout); viewFlipper = findViewById(R.id.viewFlipperSummary); - viewFlipper.setDisplayedChild(1); - ImageButton addCurrencyButton = findViewById(R.id.floatingAddButton); - ImageButton detailsButton = findViewById(R.id.switch_button); - ImageButton settingsButton = findViewById(R.id.settings_button); - - toolbarLayout.setExpandedTitleGravity(Gravity.CENTER); - toolbarLayout.setCollapsedTitleGravity(Gravity.CENTER); + bottomNavigationView = findViewById(R.id.navigationSummary); + bottomNavigationView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener); + bottomNavigationView.setSelectedItemId(R.id.navigation_currencies_list); toolbarLayout.setForegroundGravity(Gravity.CENTER); - toolbarLayout.setTitle("US$0.00"); - toolbarSubtitle.setText("US$0.00"); - - /*BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation_home); - navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); - navigation.setSelectedItemId(R.id.navigation_view_list); - navigation.setFitsSystemWindows(true); - navigation.setItemBackgroundResource(R.color.colorAccent);*/ - - //Events setup - detailsButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - switchView(); - } - }); + ImageButton settingsButton = findViewById(R.id.settings_button); settingsButton.setBackground(this.getResources().getDrawable(R.drawable.ic_settings_black_24dp)); settingsButton.setOnClickListener(new View.OnClickListener() { @@ -212,171 +173,75 @@ public class HomeActivity extends AppCompatActivity { //overridePendingTransition(R.anim.activity_enter, R.anim.activity_exit); } }); - - refreshLayout.setOnRefreshListener( - new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - switch (viewFlipper.getDisplayedChild()) - { - case 0: - Log.d(getResources().getString(R.string.debug), "Watchlist"); - refreshLayout.setRefreshing(false); - break; - case 1: - updateAll(false); - break; - case 2: - Log.d(getResources().getString(R.string.debug), "Market cap"); - refreshLayout.setRefreshing(false); - break; - } - - } - } - ); - - addCurrencyButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent addIntent = new Intent(HomeActivity.this, CurrencySelectionActivity.class); - - String[] symbolList = new String[balanceManager.getCurrenciesSymbol().size()]; - symbolList = balanceManager.getCurrenciesSymbol().toArray(symbolList); - String[] nameList = new String[balanceManager.getCurrenciesName().size()]; - nameList = balanceManager.getCurrenciesName().toArray(nameList); - - addIntent.putExtra("currencyListSymbols", symbolList); - addIntent.putExtra("currencyListNames", nameList); - - startActivity(addIntent); - } - }); - - updateViewButtonIcon(); - - lastTimestamp = 0; - - setupNavBar(savedInstanceState); - - setupDominantCurrenciesColors(); } - private void setupDominantCurrenciesColors() + private void switchMainView() { - dominantCurrenciesColors = new HashMap<>(); + Log.d("coinfolio", "Should"); + ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(true, true); + findViewById(R.id.swiperefresh).setNestedScrollingEnabled(true); - dominantCurrenciesColors.put("BTC", -489456); - dominantCurrenciesColors.put("ETH", -13619152); - dominantCurrenciesColors.put("XRP", -16744256); - dominantCurrenciesColors.put("BCH", -1011696); - dominantCurrenciesColors.put("LTC", -4671304); - dominantCurrenciesColors.put("ADA", -16773080); - dominantCurrenciesColors.put("NEO", -9390048); - dominantCurrenciesColors.put("XLM", -11509656); - dominantCurrenciesColors.put("XMR", -499712); - dominantCurrenciesColors.put("EOS", -1513240); - dominantCurrenciesColors.put("IOT", -1513240); - dominantCurrenciesColors.put("DASH", -15175496); - dominantCurrenciesColors.put("XEM", -7829368); - dominantCurrenciesColors.put("TRX", -7829360); - dominantCurrenciesColors.put("ETC", -10448784); + findViewById(R.id.toolbar_layout).setFocusable(true); + ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(true, true); + ((AppBarLayout) findViewById(R.id.app_bar)).setActivated(true); + findViewById(R.id.app_bar).setClickable(true); + findViewById(R.id.nestedScrollViewLayout).setNestedScrollingEnabled(true); + + findViewById(R.id.app_bar).setEnabled(true); + findViewById(R.id.toolbar_layout).setNestedScrollingEnabled(true); + findViewById(R.id.coordinatorLayout).setNestedScrollingEnabled(true); + + findViewById(R.id.switch_button).setVisibility(View.VISIBLE); + + viewFlipper.setDisplayedChild(1); } - private void setupNavBar(Bundle savedInstanceState) + private void switchSecondaryViews(int itemIndex) { - final SpaceNavigationView spaceNavigationView = findViewById(R.id.space); - spaceNavigationView.initWithSaveInstanceState(savedInstanceState); - spaceNavigationView.addSpaceItem(new SpaceItem("WatchList", R.drawable.ic_remove_red_eye_black_24dp)); - spaceNavigationView.addSpaceItem(new SpaceItem("Market Cap.", R.drawable.ic_pie_chart_black_24dp)); - spaceNavigationView.setSpaceBackgroundColor(getResources().getColor(R.color.colorPrimary)); - spaceNavigationView.setCentreButtonIcon(R.drawable.ic_view_list_white_24dp); - spaceNavigationView.setCentreButtonColor(getResources().getColor(R.color.colorAccent)); - spaceNavigationView.setCentreButtonIconColorFilterEnabled(false); - spaceNavigationView.changeCurrentItem(-1); + Log.d("coinfolio", "Should not"); + ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(false, true); + findViewById(R.id.swiperefresh).setNestedScrollingEnabled(false); - spaceNavigationView.setSpaceOnClickListener(new SpaceOnClickListener() { - @Override - public void onCentreButtonClick() { - //Toast.makeText(MainActivity.this,"onCentreButtonClick", Toast.LENGTH_SHORT).show(); - ((FloatingActionButton) findViewById(R.id.floatingAddButton)).show(); - SpaceNavigationView nav = findViewById(R.id.space); + findViewById(R.id.toolbar_layout).setFocusable(false); + ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(false, true); + ((AppBarLayout) findViewById(R.id.app_bar)).setActivated(false); + findViewById(R.id.app_bar).setClickable(false); + findViewById(R.id.nestedScrollViewLayout).setNestedScrollingEnabled(false); - nav.changeCurrentItem(-1); + findViewById(R.id.app_bar).setEnabled(false); + findViewById(R.id.toolbar_layout).setNestedScrollingEnabled(false); + findViewById(R.id.coordinatorLayout).setNestedScrollingEnabled(false); - findViewById(R.id.toolbar_layout).setFocusable(true); - ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(true, true); - findViewById(R.id.nestedScrollViewLayout).setNestedScrollingEnabled(true); + findViewById(R.id.switch_button).setVisibility(View.GONE); - findViewById(R.id.app_bar).setEnabled(true); - findViewById(R.id.toolbar_layout).setNestedScrollingEnabled(true); - findViewById(R.id.coordinatorLayout).setNestedScrollingEnabled(true); - - findViewById(R.id.switch_button).setVisibility(View.VISIBLE); - - viewFlipper.setDisplayedChild(1); - } - - @Override - public void onItemClick(int itemIndex, String itemName) { - ((FloatingActionButton) findViewById(R.id.floatingAddButton)).hide(); - ((SpaceNavigationView) findViewById(R.id.space)).setCentreButtonIcon(R.drawable.ic_view_list_white_24dp); - - //0 : Watchlist - //1 : Market cap - findViewById(R.id.toolbar_layout).setFocusable(false); - ((AppBarLayout) findViewById(R.id.app_bar)).setExpanded(false, true); - findViewById(R.id.nestedScrollViewLayout).setNestedScrollingEnabled(false); - - findViewById(R.id.app_bar).setEnabled(false); - findViewById(R.id.toolbar_layout).setNestedScrollingEnabled(false); - findViewById(R.id.coordinatorLayout).setNestedScrollingEnabled(false); - - findViewById(R.id.switch_button).setVisibility(View.GONE); - - - - viewFlipper.setDisplayedChild(itemIndex * 2); - - if(itemIndex == 1) - { - ((PieChart) findViewById(R.id.marketCapPieChart)).animateX(1000); - } - } - - @Override - public void onItemReselected(int itemIndex, String itemName) { - //Toast.makeText(MainActivity.this, itemIndex + " " + itemName, Toast.LENGTH_SHORT).show(); - } - }); - } - - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - ((SpaceNavigationView) findViewById(R.id.space)).onSaveInstanceState(outState); - } - - private void showErrorSnackbar() - { - Snackbar.make(findViewById(R.id.currencyListLayout), "Error while updating data", Snackbar.LENGTH_LONG) - .setAction("Update", new View.OnClickListener() { - @Override - public void onClick(View view) { - updateAll(true); - } - }) - .show(); + viewFlipper.setDisplayedChild(itemIndex); } @Override protected void onResume() { super.onResume(); - Intent intent = getIntent(); + } - updateAll(intent.getBooleanExtra("update", false)); - ((SpaceNavigationView) findViewById(R.id.space)).changeCenterButtonIcon(R.drawable.ic_view_list_white_24dp); + private void addTestWatchlistCardview() + { + View view = LayoutInflater.from(this).inflate(R.layout.cardview_watchlist, null); + + ((TextView) view.findViewById(R.id.currencyFluctuationPercentageTextView)).setText("3%"); + ((TextView) view.findViewById(R.id.currencyFluctuationTextView)).setText("$3"); + ((TextView) view.findViewById(R.id.currencyNameTextView)).setText("TanguyCoin"); + ((TextView) view.findViewById(R.id.currencySymbolTextView)).setText("TGC"); + ((TextView) view.findViewById(R.id.currencyValueTextView)).setText("$100"); + + view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + view.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Log.d("coinfolio", "Clicked !"); + } + }); + + ((LinearLayout) findViewById(R.id.linearLayoutWatchlist)).addView(view); } @Override @@ -403,607 +268,6 @@ public class HomeActivity extends AppCompatActivity { return super.onOptionsItemSelected(item); } - private void switchView() - { - if(isDetailed) - { - isDetailed = false; - - adaptView(); - } - else - { - isDetailed = true; - - adaptView(); - } - } - - private void adaptView() - { - - currencyLayout.removeAllViews(); - - 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()) > 0.001 || currency.getHistoryMinutes() == null)) - { - //currencyLayout.addView(layoutGenerator.getInfoLayout(currency)); - currencyLayout.addView(layoutGenerator.getInfoLayout(currency, isDetailed)); - } - } - - updateViewButtonIcon(); - } - - private void updateAll(boolean mustUpdate) - { - if(System.currentTimeMillis()/1000 - lastTimestamp > 60 || mustUpdate) - { - lastTimestamp = System.currentTimeMillis() / 1000; - balanceManager.updateExchangeKeys(); - refreshLayout.setRefreshing(true); - - resetCounters(); - DataUpdater updater = new DataUpdater(); - updater.execute(); - - handler.postDelayed(updateRunnable, 10000); - } - else - { - if(refreshLayout.isRefreshing()) - { - refreshLayout.setRefreshing(false); - } - } - } - - private void resetCounters() - { - coinCounter = 0; - iconCounter = 0; - detailsChecker = false; - } - - private void getBitmapFromURL(String src, IconCallBack callBack) { - Bitmap result; - - try { - java.net.URL url = new java.net.URL(src); - HttpURLConnection connection = (HttpURLConnection) url - .openConnection(); - connection.setDoInput(true); - connection.connect(); - InputStream input = connection.getInputStream(); - result = BitmapFactory.decodeStream(input); - } catch (IOException e) { - e.printStackTrace(); - result = BitmapFactory.decodeResource(this.getResources(), - R.mipmap.icon_coinfolio); - result = Bitmap.createScaledBitmap(result, 50, 50, false); - } - - callBack.onSuccess(result); - } - - private void countIcons() - { - int offset = 0; - - for(int i = 0; i < balanceManager.getTotalBalance().size(); i++) - { - if(balanceManager.getTotalBalance().get(i).getSymbol().equals("USD")) - { - offset++; - } - } - - iconCounter++; - - if(balanceManager.getTotalBalance() != null) - { - if(balanceManager.getTotalBalance().size() == 0) - { - updateNoBalance(); - } - else - { - if(iconCounter == balanceManager.getTotalBalance().size() - offset) - { - Log.d(getResources().getString(R.string.debug), "Loading heavy"); - - UiHeavyLoadCalculator uiHeavyLoadCalculator = new UiHeavyLoadCalculator(); - uiHeavyLoadCalculator.execute(); - } - } - } - } - - private void updateNoBalance() - { - refreshLayout.setRefreshing(false); - - currencyLayout.removeAllViews(); - - if(loadingDialog.isShowing()) - { - loadingDialog.dismiss(); - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - toolbarLayout.setTitle("US$0.00"); - - toolbarSubtitle.setText("US$0.00"); - - toolbarSubtitle.setTextColor(-1275068417); - } - }); - } - - private void updateMarketCap() - { - marketCapCounter = 0; - - marketCapManager.updateTopCurrencies(new MarketCapManager.VolleyCallBack() { - @Override - public void onSuccess() - { - countCompletedMarketCapRequest(); - } - }); - - marketCapManager.updateMarketCap(new MarketCapManager.VolleyCallBack() { - @Override - public void onSuccess() { - countCompletedMarketCapRequest(); - } - }); - } - - @SuppressLint("ClickableViewAccessibility") - private void countCompletedMarketCapRequest() - { - marketCapCounter++; - - if(marketCapCounter == 2) - { - setupTextViewMarketCap(); - - findViewById(R.id.progressBarMarketCap).setVisibility(View.GONE); - findViewById(R.id.layoutProgressMarketCap).setVisibility(View.VISIBLE); - - List entries = new ArrayList<>(); - - ArrayList colors = new ArrayList<>(); - - final PieChart pieChart = findViewById(R.id.marketCapPieChart); - - float otherCurrenciesDominance = 0; - - for(Iterator i = marketCapManager.getDominance().keySet().iterator(); i.hasNext(); ) - { - String key = (String) i.next(); - entries.add(new PieEntry(marketCapManager.getDominance().get(key), key)); - otherCurrenciesDominance += marketCapManager.getDominance().get(key); - colors.add(dominantCurrenciesColors.get(key)); - } - entries.add(new PieEntry(100-otherCurrenciesDominance, "Others")); - colors.add(-12369084); - - PieDataSet set = new PieDataSet(entries, "Market Cap Dominance"); - set.setColors(colors); - set.setSliceSpace(1); - set.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE); - set.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE); - PieData data = new PieData(set); - data.setValueTextSize(10); - data.setValueFormatter(new PercentFormatter()); - pieChart.setData(data); - - pieChart.setDrawSlicesUnderHole(false); - pieChart.setUsePercentValues(true); - pieChart.setTouchEnabled(true); - - pieChart.setEntryLabelColor(Color.parseColor("#FF000000")); - - pieChart.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - switch (motionEvent.getAction()) - { - case MotionEvent.ACTION_DOWN: - refreshLayout.setEnabled(false); - break; - case MotionEvent.ACTION_MOVE: - break; - default: - refreshLayout.setEnabled(true); - break; - } - return false; - } - }); - - pieChart.getDescription().setEnabled(false); - pieChart.getLegend().setEnabled(false); - pieChart.setCenterText(generateCenterSpannableText()); - pieChart.invalidate(); // refresh - } - } - - private void setupTextViewMarketCap() - { - DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK); - DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols(); - - symbols.setGroupingSeparator(' '); - formatter.setDecimalFormatSymbols(symbols); - - ((TextView) findViewById(R.id.marketCapTextView)).setText(getResources().getString(R.string.market_cap_textview, formatter.format(marketCapManager.getMarketCap()))); - - ((TextView) findViewById(R.id.dayVolumeTotalMarketCap)).setText(getResources().getString(R.string.volume_market_cap_textview, formatter.format(marketCapManager.getDayVolume()))); - } - - private SpannableString generateCenterSpannableText() { - - SpannableString s = new SpannableString("Market Capitalization Dominance"); - return s; - } - - private void countCoins(boolean isCoin, boolean isDetails) - { - if(isCoin) - { - coinCounter++; - } - - if(isDetails) - { - detailsChecker = true; - } - - if(balanceManager.getTotalBalance() != null) - { - if(coinCounter == balanceManager.getTotalBalance().size() && detailsChecker) - { - IconDownloader iconDownloader = new IconDownloader(); - iconDownloader.execute(); - } - else - { - if(balanceManager.getTotalBalance().size() == 0) - { - Log.d("coinfolio", "Empty"); - - countIcons(); - } - } - } - } - - private void updateViewButtonIcon() - { - ImageButton imgButton = findViewById(R.id.switch_button); - - imgButton.setBackgroundColor(this.getResources().getColor(R.color.buttonColor)); - - if(isDetailed) - { - imgButton.setBackground(this.getResources().getDrawable(R.drawable.ic_unfold_less_black_24dp)); - preferencesManager.setDetailOption(true); - } - else - { - imgButton.setBackground(this.getResources().getDrawable(R.drawable.ic_details_black_24dp)); - preferencesManager.setDetailOption(false); - } - } - - private void generateSplash() - { - LinearLayout loadingLayout = new LinearLayout(this); - - loadingLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); - loadingLayout.setGravity(Gravity.CENTER); - loadingLayout.setOrientation(LinearLayout.VERTICAL); - - loadingDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen); - - TextView txtView = new TextView(this); - txtView.setText("Loading data..."); - txtView.setTextSize(20); - txtView.setGravity(Gravity.CENTER); - txtView.setTextColor(this.getResources().getColor(R.color.cardview_light_background)); - - ProgressBar progressBar = new ProgressBar(this); - progressBar.setIndeterminate(true); - - loadingLayout.setBackgroundColor(this.getResources().getColor(R.color.colorPrimaryDark)); - loadingLayout.addView(txtView); - loadingLayout.addView(progressBar); - - loadingDialog.setContentView(loadingLayout); - loadingDialog.show(); - } - - private class IconDownloader extends AsyncTask - { - @Override - protected void onPreExecute() - { - super.onPreExecute(); - } - - @Override - protected void onProgressUpdate(Integer... values) - { - super.onProgressUpdate(values); - } - - @Override - protected Void doInBackground(Void... params) - { - for (int i = 0; i < balanceManager.getTotalBalance().size(); i++) - { - final Currency localCurrency = balanceManager.getTotalBalance().get(i); - - if(balanceManager.getIconUrl(localCurrency.getSymbol()) != null) - { - getBitmapFromURL(balanceManager.getIconUrl(localCurrency.getSymbol()), new IconCallBack() { - @Override - public void onSuccess(Bitmap bitmapIcon) { - localCurrency.setIcon(bitmapIcon); - countIcons(); - } - }); - } - } - - return null; - } - - @Override - protected void onPostExecute(Void result) - { - - } - } - - private class UiHeavyLoadCalculator extends AsyncTask - { - - private float totalValue; - private float totalFluctuation; - private float totalFluctuationPercentage; - - @Override - protected void onPreExecute() - { - super.onPreExecute(); - - totalValue = 0; - totalFluctuation = 0; - totalFluctuationPercentage = 0; - } - - @Override - protected void onProgressUpdate(Integer... values) - { - super.onProgressUpdate(values); - } - - @Override - protected Void doInBackground(Void... params) - { - final List cardList = new ArrayList<>(); - - Looper.prepare(); - - balanceManager.sortCoins(); - - for(int i = 0; i < balanceManager.getTotalBalance().size(); i++) - { - final Currency localCurrency = balanceManager.getTotalBalance().get(i); - - if(localCurrency.getIcon() != null) - { - Palette.Builder builder = Palette.from(localCurrency.getIcon()); - - localCurrency.setChartColor(builder.generate().getDominantColor(0)); - - } - else - { - localCurrency.setChartColor(12369084); - } - - if(!localCurrency.getSymbol().equals("USD") && (localCurrency.getBalance() * localCurrency.getValue()) > 0.001) - { - localCurrency.setName(balanceManager.getCurrencyName(localCurrency.getSymbol())); - localCurrency.setId(balanceManager.getCurrencyId(localCurrency.getSymbol())); - totalValue += localCurrency.getValue() * localCurrency.getBalance(); - totalFluctuation += (localCurrency.getValue() * localCurrency.getBalance()) * (localCurrency.getDayFluctuationPercentage() / 100); - - cardList.add(layoutGenerator.getInfoLayout(localCurrency, true)); - } - - if(!localCurrency.getSymbol().equals("USD") && localCurrency.getHistoryMinutes() == null) - { - cardList.add(layoutGenerator.getInfoLayout(localCurrency, true)); - } - - balanceManager.getTotalBalance().set(i, localCurrency); - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - refreshLayout.setRefreshing(false); - currencyLayout.removeAllViews(); - - for(int i = 0; i < cardList.size(); i++) - { - currencyLayout.addView(cardList.get(i)); - } - - adaptView(); - } - }); - - toolbarLayout.setTitle("US$" + String.format("%.2f", totalValue)); - - if(totalFluctuation > 0) - { - runOnUiThread(new Runnable() { - @Override - public void run() { - toolbarSubtitle.setTextColor(getResources().getColor(R.color.increase)); - } - }); - } - else - { - runOnUiThread(new Runnable() { - @Override - public void run() { - toolbarSubtitle.setTextColor(getResources().getColor(R.color.decrease)); - } - }); - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - - totalFluctuationPercentage = totalFluctuation / (totalValue - totalFluctuation) *100; - - toolbarSubtitle.setText("US$" + String.format("%.2f", totalFluctuation) + " (" + String.format("%.2f", totalFluctuationPercentage) + "%)"); - - if(loadingDialog.isShowing()) - { - loadingDialog.dismiss(); - } - } - }); - - return null; - } - - @Override - protected void onPostExecute(Void result) - { - handler.removeCallbacks(updateRunnable); - } - } - - private class DataUpdater extends AsyncTask - { - @Override - protected void onPreExecute() - { - super.onPreExecute(); - } - - @Override - protected void onProgressUpdate(Integer... values) - { - super.onProgressUpdate(values); - } - - @Override - protected Void doInBackground(Void... params) - { - balanceManager.updateDetails(new BalanceManager.IconCallBack() { - @Override - public void onSuccess() - { - countCoins(false, true); - } - }); - - balanceManager.updateTotalBalance(new BalanceManager.VolleyCallBack() { - @Override - public void onSuccess() { - - final List balance = balanceManager.getTotalBalance(); - - if(balanceManager.getTotalBalance().size() > 0) - { - for(int i = 0; i < balanceManager.getTotalBalance().size(); i++) - { - balance.get(i).updateHistoryMinutes(getApplicationContext(), new Currency.CurrencyCallBack() { - @Override - public void onSuccess(Currency currency) { - countCoins(true, false); - } - }); - } - } - else - { - runOnUiThread(new Runnable() { - @Override - public void run() { - countCoins(false, false); - } - }); - } - } - - public void onError(String error) - { - switch (error) - { - case "com.android.volley.AuthFailureError": - preferencesManager.disableHitBTC(); - Snackbar.make(findViewById(R.id.viewFlipperSummary), "HitBTC synchronization error : Invalid keys", Snackbar.LENGTH_LONG) - .show(); - refreshLayout.setRefreshing(false); - updateAll(true); - break; - case "API-key format invalid.": - preferencesManager.disableBinance(); - Snackbar.make(findViewById(R.id.viewFlipperSummary), "Binance synchronization error : Invalid keys", Snackbar.LENGTH_LONG) - .show(); - updateAll(true); - break; - default: - Snackbar.make(findViewById(R.id.viewFlipperSummary), "Unexpected error", Snackbar.LENGTH_LONG) - .show(); - Log.d("coinfolio", error); - updateAll(true); - } - } - }); - - updateMarketCap(); - - /*marketCapManager.updateTopCurrencies(new BalanceManager.VolleyCallBack() { - @Override - public void onSuccess() { - - } - - @Override - public void onError(String error) { - - }});*/ - - return null; - } - - @Override - protected void onPostExecute(Void result) - { - - } - } - public interface IconCallBack { void onSuccess(Bitmap bitmap); diff --git a/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/MarketCapitalization.java b/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/MarketCapitalization.java new file mode 100644 index 0000000..cdc44f6 --- /dev/null +++ b/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/MarketCapitalization.java @@ -0,0 +1,245 @@ +package com.nauk.coinfolio.Activities.HomeActivityFragments; + +import android.annotation.SuppressLint; +import android.graphics.Color; +import android.support.design.widget.AppBarLayout; +import android.support.v4.app.Fragment; +import android.os.Bundle; +import android.support.v4.view.ViewPager; +import android.support.v4.widget.SwipeRefreshLayout; +import android.text.SpannableString; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewParent; +import android.widget.TextView; + +import com.github.mikephil.charting.charts.PieChart; +import com.github.mikephil.charting.data.PieData; +import com.github.mikephil.charting.data.PieDataSet; +import com.github.mikephil.charting.data.PieEntry; +import com.github.mikephil.charting.formatter.PercentFormatter; +import com.nauk.coinfolio.DataManagers.MarketCapManager; +import com.nauk.coinfolio.R; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +/** + * Created by Tiji on 13/04/2018. + */ + +public class MarketCapitalization extends Fragment { + + private int marketCapCounter; + + private MarketCapManager marketCapManager; + private HashMap dominantCurrenciesColors; + private SwipeRefreshLayout refreshLayout; + private long lastTimestamp; + + private View view; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) + { + view = inflater.inflate(R.layout.fragment_marketcap_homeactivity, container, false); + + setupDominantCurrenciesColors(); + + marketCapManager = new MarketCapManager(getContext()); + refreshLayout = view.findViewById(R.id.swiperefreshmarketcap); + + refreshLayout.setOnRefreshListener( + new SwipeRefreshLayout.OnRefreshListener() { + @Override + public void onRefresh() { + updateMarketCap(); + } + + } + ); + + lastTimestamp = 0; + + updateMarketCap(); + + return view; + } + + @Override + public void onResume() + { + super.onResume(); + } + + private void setupDominantCurrenciesColors() + { + dominantCurrenciesColors = new HashMap<>(); + + dominantCurrenciesColors.put("BTC", -489456); + dominantCurrenciesColors.put("ETH", -13619152); + dominantCurrenciesColors.put("XRP", -16744256); + dominantCurrenciesColors.put("BCH", -1011696); + dominantCurrenciesColors.put("LTC", -4671304); + dominantCurrenciesColors.put("EOS", -1513240); + dominantCurrenciesColors.put("ADA", -16773080); + dominantCurrenciesColors.put("XLM", -11509656); + dominantCurrenciesColors.put("MIOTA", -1513240); + dominantCurrenciesColors.put("NEO", -9390048); + dominantCurrenciesColors.put("XMR", -499712); + dominantCurrenciesColors.put("DASH", -15175496); + dominantCurrenciesColors.put("XEM", -7829368); + dominantCurrenciesColors.put("TRX", -7829360); + dominantCurrenciesColors.put("ETC", -10448784); + } + + private void updateMarketCap() + { + if(System.currentTimeMillis() / 1000 - lastTimestamp > 60) + { + if(!refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(true); + } + + marketCapCounter = 0; + + lastTimestamp = System.currentTimeMillis() / 1000; + + marketCapManager.updateTopCurrencies(new MarketCapManager.VolleyCallBack() { + @Override + public void onSuccess() + { + countCompletedMarketCapRequest(); + } + }); + + marketCapManager.updateMarketCap(new MarketCapManager.VolleyCallBack() { + @Override + public void onSuccess() { + countCompletedMarketCapRequest(); + } + }); + } + else + { + if(refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(false); + } + } + } + + @SuppressLint("ClickableViewAccessibility") + private void countCompletedMarketCapRequest() + { + marketCapCounter++; + + if(marketCapCounter == 2) + { + setupTextViewMarketCap(); + + view.findViewById(R.id.progressBarMarketCap).setVisibility(View.GONE); + view.findViewById(R.id.layoutProgressMarketCap).setVisibility(View.VISIBLE); + + List entries = new ArrayList<>(); + + ArrayList colors = new ArrayList<>(); + + float otherCurrenciesDominance = 0; + + for(Iterator i = marketCapManager.getDominance().keySet().iterator(); i.hasNext(); ) + { + String key = (String) i.next(); + entries.add(new PieEntry(marketCapManager.getDominance().get(key), key)); + otherCurrenciesDominance += marketCapManager.getDominance().get(key); + colors.add(dominantCurrenciesColors.get(key)); + } + + entries.add(new PieEntry(100-otherCurrenciesDominance, "Others")); + colors.add(-12369084); + + PieDataSet set = new PieDataSet(entries, "Market Cap Dominance"); + set.setColors(colors); + set.setSliceSpace(1); + set.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE); + set.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE); + + PieData data = new PieData(set); + data.setValueTextSize(10); + data.setValueFormatter(new PercentFormatter()); + + setupPieChart(data); + + if(refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(false); + } + } + } + + private void setupPieChart(PieData data) + { + PieChart pieChart = view.findViewById(R.id.marketCapPieChart); + + pieChart.setData(data); + pieChart.setDrawSlicesUnderHole(false); + pieChart.setUsePercentValues(true); + pieChart.setTouchEnabled(true); + + pieChart.setEntryLabelColor(Color.parseColor("#FF000000")); + + pieChart.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View view, MotionEvent motionEvent) { + switch (motionEvent.getAction()) + { + case MotionEvent.ACTION_DOWN: + refreshLayout.setEnabled(false); + getActivity().findViewById(R.id.viewPager).setEnabled(false); + break; + case MotionEvent.ACTION_MOVE: + break; + default: + refreshLayout.setEnabled(true); + getActivity().findViewById(R.id.viewPager).setEnabled(true); + break; + } + return false; + } + }); + + pieChart.getDescription().setEnabled(false); + pieChart.getLegend().setEnabled(false); + pieChart.setCenterText(generateCenterSpannableText()); + pieChart.invalidate(); + } + + private SpannableString generateCenterSpannableText() { + + SpannableString spannableString = new SpannableString("Market Capitalization Dominance"); + return spannableString; + } + + private void setupTextViewMarketCap() + { + DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK); + DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols(); + + symbols.setGroupingSeparator(' '); + formatter.setDecimalFormatSymbols(symbols); + + ((TextView) view.findViewById(R.id.marketCapTextView)).setText(getActivity().getResources().getString(R.string.market_cap_textview, formatter.format(marketCapManager.getMarketCap()))); + + ((TextView) view.findViewById(R.id.dayVolumeTotalMarketCap)).setText(getActivity().getResources().getString(R.string.volume_market_cap_textview, formatter.format(marketCapManager.getDayVolume()))); + } +} diff --git a/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/Summary.java b/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/Summary.java new file mode 100644 index 0000000..090f8f4 --- /dev/null +++ b/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/Summary.java @@ -0,0 +1,685 @@ +package com.nauk.coinfolio.Activities.HomeActivityFragments; + +import android.app.Dialog; +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Color; +import android.os.AsyncTask; +import android.os.Handler; +import android.os.Looper; +import android.support.design.widget.CollapsingToolbarLayout; +import android.support.v4.app.Fragment; +import android.os.Bundle; +import android.support.v4.widget.SwipeRefreshLayout; +import android.support.v7.graphics.Palette; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.Button; +import android.widget.ImageButton; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; + +import com.nauk.coinfolio.Activities.CurrencySelectionActivity; +import com.nauk.coinfolio.Activities.HomeActivity; +import com.nauk.coinfolio.DataManagers.BalanceManager; +import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; +import com.nauk.coinfolio.DataManagers.PreferencesManager; +import com.nauk.coinfolio.LayoutManagers.HomeLayoutGenerator; +import com.nauk.coinfolio.R; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.util.List; + +/** + * Created by Tiji on 13/04/2018. + */ + +public class Summary extends Fragment { + + private LinearLayout currencyLayout; + private PreferencesManager preferencesManager; + private BalanceManager balanceManager; + private HomeLayoutGenerator layoutGenerator; + private View view; + private SwipeRefreshLayout refreshLayout; + private Dialog loadingDialog; + + private TextView toolbarSubtitle; + private CollapsingToolbarLayout toolbarLayout; + private Handler handler; + + private Runnable updateRunnable; + + private int coinCounter; + private int iconCounter; + private float totalValue; + private boolean detailsChecker; + protected float totalFluctuation; + private long lastTimestamp; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) + { + view = inflater.inflate(R.layout.fragment_summary_homeactivity, container, false); + + currencyLayout = view.findViewById(R.id.currencyListLayout); + preferencesManager = new PreferencesManager(getActivity()); + balanceManager = new BalanceManager(getActivity()); + layoutGenerator = new HomeLayoutGenerator(getActivity()); + refreshLayout = view.findViewById(R.id.swiperefreshsummary); + toolbarSubtitle = getActivity().findViewById(R.id.toolbarSubtitle); + toolbarLayout = getActivity().findViewById(R.id.toolbar_layout); + + totalValue = 0; + totalFluctuation = 0; + lastTimestamp = 0; + + handler = new Handler(); + updateRunnable = new Runnable() { + @Override + public void run() { + if (refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(false); + + showErrorSnackbar(); + } + + if (loadingDialog.isShowing()) + { + loadingDialog.dismiss(); + + showErrorSnackbar(); + } + } + }; + + refreshLayout.setOnRefreshListener( + new SwipeRefreshLayout.OnRefreshListener() { + @Override + public void onRefresh() { + updateAll(false); + } + + } + ); + + handler.postDelayed(updateRunnable, 10000); + + Button addCurrencyButton = view.findViewById(R.id.buttonAddTransaction); + + addCurrencyButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent addIntent = new Intent(getActivity(), CurrencySelectionActivity.class); + + startActivity(addIntent); + } + }); + + ImageButton detailsButton = getActivity().findViewById(R.id.switch_button); + detailsButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + preferencesManager.setDetailOption(!preferencesManager.getDetailOption()); + updateViewButtonIcon(); + switchView(); + } + }); + + updateTitle(); + + updateAll(true); + + generateSplashScreen(); + + return view; + } + + private void generateSplashScreen() + { + LinearLayout loadingLayout = new LinearLayout(getActivity()); + + loadingLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + loadingLayout.setGravity(Gravity.CENTER); + loadingLayout.setOrientation(LinearLayout.VERTICAL); + + loadingDialog = new Dialog(getActivity(), android.R.style.Theme_Black_NoTitleBar_Fullscreen); + + TextView txtView = new TextView(getActivity()); + txtView.setText("Loading data..."); + txtView.setTextSize(20); + txtView.setGravity(Gravity.CENTER); + txtView.setTextColor(this.getResources().getColor(R.color.cardview_light_background)); + + ProgressBar progressBar = new ProgressBar(getActivity()); + progressBar.setIndeterminate(true); + + loadingLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.colorPrimaryDark)); + loadingLayout.addView(txtView); + loadingLayout.addView(progressBar); + + loadingDialog.setContentView(loadingLayout); + loadingDialog.show(); + } + + @Override + public void onResume() { + super.onResume(); + + updateAll(preferencesManager.mustUpdateSummary()); + + updateViewButtonIcon(); + + displayBalance(preferencesManager.isBalanceHidden()); + } + + private void updateAll(boolean mustUpdate) + { + if(System.currentTimeMillis()/1000 - lastTimestamp > 60 || mustUpdate) + { + if(!refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(true); + } + + lastTimestamp = System.currentTimeMillis() / 1000; + balanceManager.updateExchangeKeys(); + refreshLayout.setRefreshing(true); + + resetCounters(); + DataUpdater updater = new DataUpdater(); + updater.execute(); + + } + else + { + if(refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(false); + } + } + } + + private void showErrorSnackbar() + { + /*Snackbar.make(getActivity().findViewById(R.id.viewFlipperSummary), "Error while updating data", Snackbar.LENGTH_LONG) + .setAction("Update", new View.OnClickListener() { + @Override + public void onClick(View view) { + + } + }) + .show();*/ + } + + private void resetCounters() + { + coinCounter = 0; + iconCounter = 0; + detailsChecker = false; + + totalValue = 0; + totalFluctuation = 0; + } + + private void switchView() + { + if(preferencesManager.getDetailOption()) + { + adaptView(); + } + else + { + adaptView(); + } + } + + private void adaptView() + { + currencyLayout.removeAllViews(); + + 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()) > 0.001 || currency.getHistoryMinutes() == null)) + { + currencyLayout.addView(layoutGenerator.getInfoLayout(currency, preferencesManager.getDetailOption(), totalValue, preferencesManager.isBalanceHidden())); + } + } + } + + private void countCoins(boolean isCoin, boolean isDetails) + { + if(isCoin) + { + coinCounter++; + } + + if(isDetails) + { + detailsChecker = true; + } + + if(balanceManager.getTotalBalance() != null) + { + if(coinCounter == balanceManager.getTotalBalance().size() && detailsChecker) + { + IconDownloader iconDownloader = new IconDownloader(); + iconDownloader.execute(); + } + else + { + if(balanceManager.getTotalBalance().size() == 0) + { + countIcons(); + } + } + } + } + + + private void countIcons() + { + int offset = 0; + + for(int i = 0; i < balanceManager.getTotalBalance().size(); i++) + { + if(balanceManager.getTotalBalance().get(i).getSymbol().equals("USD")) + { + offset++; + } + } + + iconCounter++; + + if(balanceManager.getTotalBalance() != null) + { + if(balanceManager.getTotalBalance().size() == 0) + { + updateNoBalance(); + } + else + { + if(iconCounter == balanceManager.getTotalBalance().size() - offset) + { + Log.d(getResources().getString(R.string.debug), "Loading heavy"); + + UiHeavyLoadCalculator uiHeavyLoadCalculator = new UiHeavyLoadCalculator(); + uiHeavyLoadCalculator.execute(); + } + } + } + } + + private void updateNoBalance() + { + refreshLayout.setRefreshing(false); + + currencyLayout.removeAllViews(); + + if(loadingDialog.isShowing()) + { + loadingDialog.dismiss(); + } + + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + + updateTitle(); + } + }); + } + + protected void updateTitle() + { + float totalFluctuationPercentage = totalFluctuation / (totalValue - totalFluctuation) * 100; + + if(preferencesManager.isBalanceHidden()) + { + toolbarLayout.setTitle(getResources().getString(R.string.currencyPercentagePlaceholder, String.format("%.2f", totalFluctuationPercentage))); + toolbarSubtitle.setVisibility(View.GONE); + + if(totalFluctuation > 0) + { + toolbarLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.increase)); + toolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.increase)); + } + else + { + toolbarLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.decrease)); + toolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.decrease)); + } + } + else + { + toolbarLayout.setTitle(getResources().getString(R.string.currencyDollarPlaceholder, String.format("%.2f", totalValue))); + toolbarLayout.setCollapsedTitleTextColor(Color.WHITE); + toolbarLayout.setExpandedTitleColor(Color.WHITE); + + toolbarSubtitle.setVisibility(View.VISIBLE); + + if(totalFluctuation > 0) + { + toolbarSubtitle.setTextColor(getResources().getColor(R.color.increase)); + } + else + { + toolbarSubtitle.setTextColor(getResources().getColor(R.color.decrease)); + } + + if(totalFluctuation == 0) + { + toolbarSubtitle.setText(getResources().getString(R.string.currencyDollarPlaceholder, "0.00")); + toolbarSubtitle.setTextColor(-1275068417); + + } + else + { + toolbarSubtitle.setText("US$" + String.format("%.2f", totalFluctuation) + " (" + String.format("%.2f", totalFluctuationPercentage) + "%)"); + } + } + } + + private class UiHeavyLoadCalculator extends AsyncTask + { + + @Override + protected void onPreExecute() + { + super.onPreExecute(); + + totalValue = 0; + totalFluctuation = 0; + } + + @Override + protected void onProgressUpdate(Integer... values) + { + super.onProgressUpdate(values); + } + + private void updateChartColor(Currency currency) + { + if(currency.getIcon() != null) + { + Palette.Builder builder = Palette.from(currency.getIcon()); + + currency.setChartColor(builder.generate().getDominantColor(0)); + } + else + { + currency.setChartColor(12369084); + } + } + + private void loadCurrency(Currency currency) + { + if(!currency.getSymbol().equals("USD") && (currency.getBalance() * currency.getValue()) > 0.001) + { + currency.setName(balanceManager.getCurrencyName(currency.getSymbol())); + currency.setId(balanceManager.getCurrencyId(currency.getSymbol())); + totalValue += currency.getValue() * currency.getBalance(); + totalFluctuation += (currency.getValue() * currency.getBalance()) * (currency.getDayFluctuationPercentage() / 100); + } + } + + private void refreshCurrencyList() + { + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + currencyLayout.removeAllViews(); + + for(int i = 0; i < balanceManager.getTotalBalance().size(); i++) + { + Currency currency = balanceManager.getTotalBalance().get(i); + + if(!currency.getSymbol().equals("USD") && (currency.getBalance() * currency.getValue()) > 0.001) { + currencyLayout.addView(layoutGenerator.getInfoLayout(currency, preferencesManager.getDetailOption(), totalValue, preferencesManager.isBalanceHidden())); + } + } + + adaptView(); + } + }); + } + + @Override + protected Void doInBackground(Void... params) + { + if(Looper.myLooper() == null) + { + Looper.prepare(); + } + + balanceManager.sortCoins(); + + for(int i = 0; i < balanceManager.getTotalBalance().size(); i++) + { + final Currency localCurrency = balanceManager.getTotalBalance().get(i); + + updateChartColor(localCurrency); + + loadCurrency(localCurrency); + + balanceManager.getTotalBalance().set(i, localCurrency); + } + + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + updateTitle(); + } + }); + + if(loadingDialog.isShowing()) + { + loadingDialog.dismiss(); + } + + return null; + } + + @Override + protected void onPostExecute(Void result) + { + refreshLayout.setRefreshing(false); + refreshCurrencyList(); + handler.removeCallbacks(updateRunnable); + } + } + + private void getBitmapFromURL(String src, HomeActivity.IconCallBack callBack) { + Bitmap result; + + try { + java.net.URL url = new java.net.URL(src); + HttpURLConnection connection = (HttpURLConnection) url + .openConnection(); + connection.setDoInput(true); + connection.connect(); + InputStream input = connection.getInputStream(); + result = BitmapFactory.decodeStream(input); + } catch (IOException e) { + e.printStackTrace(); + result = BitmapFactory.decodeResource(this.getResources(), + R.mipmap.icon_coinfolio); + result = Bitmap.createScaledBitmap(result, 50, 50, false); + } + + callBack.onSuccess(result); + } + + private void updateViewButtonIcon() + { + ImageButton imgButton = getActivity().findViewById(R.id.switch_button); + + imgButton.setBackgroundColor(this.getResources().getColor(R.color.buttonColor)); + + if(preferencesManager.getDetailOption()) + { + imgButton.setBackground(this.getResources().getDrawable(R.drawable.ic_unfold_less_black_24dp)); + } + else + { + imgButton.setBackground(this.getResources().getDrawable(R.drawable.ic_details_black_24dp)); + } + } + + private void displayBalance(boolean hideBalance) + { + updateTitle(); + + if(hideBalance) + { + for(int i = 0; i < currencyLayout.getChildCount(); i++) + { + currencyLayout.getChildAt(i).findViewById(R.id.currencyPortfolioDominance).setVisibility(View.VISIBLE); + currencyLayout.getChildAt(i).findViewById(R.id.percentageOwnedTextView).setVisibility(View.VISIBLE); + currencyLayout.getChildAt(i).findViewById(R.id.currencyOwnedInfoLayout).setVisibility(View.GONE); + } + } + else + { + for(int i = 0; i < currencyLayout.getChildCount(); i++) + { + currencyLayout.getChildAt(i).findViewById(R.id.currencyPortfolioDominance).setVisibility(View.INVISIBLE); + currencyLayout.getChildAt(i).findViewById(R.id.percentageOwnedTextView).setVisibility(View.GONE); + currencyLayout.getChildAt(i).findViewById(R.id.currencyOwnedInfoLayout).setVisibility(View.VISIBLE); + } + } + } + + private class IconDownloader extends AsyncTask + { + @Override + protected void onPreExecute() + { + super.onPreExecute(); + } + + @Override + protected void onProgressUpdate(Integer... values) + { + super.onProgressUpdate(values); + } + + @Override + protected Void doInBackground(Void... params) + { + for (int i = 0; i < balanceManager.getTotalBalance().size(); i++) + { + final Currency localCurrency = balanceManager.getTotalBalance().get(i); + + if(balanceManager.getIconUrl(localCurrency.getSymbol()) != null) + { + getBitmapFromURL(balanceManager.getIconUrl(localCurrency.getSymbol()), new HomeActivity.IconCallBack() { + @Override + public void onSuccess(Bitmap bitmapIcon) { + localCurrency.setIcon(bitmapIcon); + countIcons(); + } + }); + } + } + + return null; + } + + @Override + protected void onPostExecute(Void result) + { + + } + } + + + private class DataUpdater extends AsyncTask + { + @Override + protected Void doInBackground(Void... params) + { + balanceManager.updateDetails(new BalanceManager.IconCallBack() { + @Override + public void onSuccess() + { + countCoins(false, true); + } + }); + + balanceManager.updateTotalBalance(new BalanceManager.VolleyCallBack() { + @Override + public void onSuccess() { + + final List balance = balanceManager.getTotalBalance(); + + if(balanceManager.getTotalBalance().size() > 0) + { + for(int i = 0; i < balanceManager.getTotalBalance().size(); i++) + { + balance.get(i).updateHistoryMinutes(getActivity(), new Currency.CurrencyCallBack() { + @Override + public void onSuccess(Currency currency) { + countCoins(true, false); + } + }); + } + } + else + { + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + countCoins(false, false); + } + }); + } + } + + public void onError(String error) + { + /*switch (error) + { + case "com.android.volley.AuthFailureError": + preferencesManager.disableHitBTC(); + Snackbar.make(findViewById(R.id.viewFlipperSummary), "HitBTC synchronization error : Invalid keys", Snackbar.LENGTH_LONG) + .show(); + refreshLayout.setRefreshing(false); + updateAll(true); + break; + case "API-key format invalid.": + preferencesManager.disableBinance(); + Snackbar.make(findViewById(R.id.viewFlipperSummary), "Binance synchronization error : Invalid keys", Snackbar.LENGTH_LONG) + .show(); + updateAll(true); + break; + default: + Snackbar.make(findViewById(R.id.viewFlipperSummary), "Unexpected error", Snackbar.LENGTH_LONG) + .show(); + Log.d("coinfolio", error); + updateAll(true); + }*/ + } + }); + + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + } + } + +} diff --git a/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/Watchlist.java b/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/Watchlist.java new file mode 100644 index 0000000..8994fda --- /dev/null +++ b/app/src/main/java/com/nauk/coinfolio/Activities/HomeActivityFragments/Watchlist.java @@ -0,0 +1,449 @@ +package com.nauk.coinfolio.Activities.HomeActivityFragments; + +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Color; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffColorFilter; +import android.graphics.drawable.Drawable; +import android.os.AsyncTask; +import android.support.design.widget.AppBarLayout; +import android.support.v4.app.Fragment; +import android.os.Bundle; +import android.support.v4.view.ViewPager; +import android.support.v4.widget.SwipeRefreshLayout; +import android.support.v7.graphics.Palette; +import android.support.v7.widget.CardView; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewParent; +import android.view.animation.Animation; +import android.view.animation.Transformation; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.github.mikephil.charting.charts.LineChart; +import com.github.mikephil.charting.data.Entry; +import com.github.mikephil.charting.data.LineData; +import com.github.mikephil.charting.data.LineDataSet; +import com.nauk.coinfolio.Activities.CurrencyDetailsActivity; +import com.nauk.coinfolio.Activities.CurrencySelectionActivity; +import com.nauk.coinfolio.Activities.HomeActivity; +import com.nauk.coinfolio.DataManagers.BalanceManager; +import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; +import com.nauk.coinfolio.DataManagers.CurrencyData.CurrencyDataChart; +import com.nauk.coinfolio.DataManagers.CurrencyData.CurrencyDetailsList; +import com.nauk.coinfolio.DataManagers.PreferencesManager; +import com.nauk.coinfolio.DataManagers.WatchlistManager; +import com.nauk.coinfolio.R; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import static java.lang.Math.abs; + +/** + * Created by Tiji on 13/04/2018. + */ + +public class Watchlist extends Fragment { + + private WatchlistManager watchlistManager; + private View view; + private int watchlistCounter; + private CurrencyDetailsList currencyDetailsList; + private SwipeRefreshLayout refreshLayout; + private long lastTimestamp; + private PreferencesManager preferencesManager; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) + { + view = inflater.inflate(R.layout.fragment_watchlist_homeactivity, container, false); + + refreshLayout = view.findViewById(R.id.swiperefreshwatchlist); + currencyDetailsList = new CurrencyDetailsList(getContext()); + preferencesManager = new PreferencesManager(getContext()); + + lastTimestamp = 0; + + watchlistManager = new WatchlistManager(getContext()); + + updateWatchlist(true); + + refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { + @Override + public void onRefresh() { + updateWatchlist(false); + } + }); + + Button addWatchlistButton = view.findViewById(R.id.buttonAddWatchlist); + addWatchlistButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent selectionIntent = new Intent(getActivity(), CurrencySelectionActivity.class); + selectionIntent.putExtra("isWatchList", true); + startActivity(selectionIntent); + } + }); + + return view; + } + + private void collapseView(View view) + { + collapse(view.findViewById(R.id.collapsableLayout)); + } + + private void extendView(View view) + { + expand(view.findViewById(R.id.collapsableLayout)); + view.findViewById(R.id.LineChartView).invalidate(); + } + + private static void expand(final View v) { + v.measure(CardView.LayoutParams.MATCH_PARENT, CardView.LayoutParams.WRAP_CONTENT); + final int targetHeight = v.getMeasuredHeight(); + + // Older versions of android (pre API 21) cancel animations for views with a height of 0. + v.getLayoutParams().height = 1; + v.setVisibility(View.VISIBLE); + Animation a = new Animation() + { + @Override + protected void applyTransformation(float interpolatedTime, Transformation t) { + v.getLayoutParams().height = interpolatedTime == 1 + ? CardView.LayoutParams.WRAP_CONTENT + : (int)(targetHeight * interpolatedTime); + v.requestLayout(); + } + + @Override + public boolean willChangeBounds() { + return true; + } + }; + + // 1dp/ms + a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density)); + v.startAnimation(a); + } + + private static void collapse(final View v) { + final int initialHeight = v.getMeasuredHeight(); + + Animation a = new Animation() + { + @Override + protected void applyTransformation(float interpolatedTime, Transformation t) { + if(interpolatedTime == 1){ + v.setVisibility(View.GONE); + }else{ + v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime); + v.requestLayout(); + } + } + + @Override + public boolean willChangeBounds() { + return true; + } + }; + + // 1dp/ms + a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density)); + v.startAnimation(a); + } + + + @Override + public void onResume() + { + super.onResume(); + + updateWatchlist(preferencesManager.mustUpdateWatchlist()); + } + + private void updateWatchlist(boolean mustUpdate) + { + if(System.currentTimeMillis()/1000 - lastTimestamp > 60 || mustUpdate) + { + if(!refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(true); + } + + lastTimestamp = System.currentTimeMillis()/1000; + + watchlistManager.updateWatchlist(); + + currencyDetailsList.update(new BalanceManager.IconCallBack() { + @Override + public void onSuccess() { + WatchlistUpdater watchlistUpdater = new WatchlistUpdater(); + watchlistUpdater.execute(); + } + }); + } + else + { + if(refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(false); + } + } + } + + private void countWatchlist() + { + watchlistCounter++; + + if(watchlistCounter >= watchlistManager.getWatchlist().size()) + { + ((LinearLayout) view.findViewById(R.id.linearLayoutWatchlist)).removeAllViews(); + + for(final Currency currency : watchlistManager.getWatchlist()) + { + View card = LayoutInflater.from(getContext()).inflate(R.layout.cardview_watchlist, null); + + ((TextView) card.findViewById(R.id.currencyFluctuationPercentageTextView)).setText(getResources().getString(R.string.currencyPercentagePlaceholder, numberConformer(currency.getDayFluctuationPercentage()))); + ((TextView) card.findViewById(R.id.currencyFluctuationTextView)).setText(getResources().getString(R.string.currencyDollarParenthesisPlaceholder, numberConformer(currency.getDayFluctuation()))); + ((TextView) card.findViewById(R.id.currencyNameTextView)).setText(currency.getName()); + ((TextView) card.findViewById(R.id.currencySymbolTextView)).setText(getResources().getString(R.string.currencySymbolPlaceholder, currency.getSymbol())); + ((ImageView) card.findViewById(R.id.currencyIcon)).setImageBitmap(currency.getIcon()); + ((TextView) card.findViewById(R.id.currencyValueTextView)).setText(getResources().getString(R.string.currencyDollarPlaceholder, numberConformer(currency.getValue()))); + + Drawable arrowDrawable = ((ImageView) card.findViewById(R.id.detailsArrow)).getDrawable(); + arrowDrawable.mutate(); + arrowDrawable.setColorFilter(new PorterDuffColorFilter(currency.getChartColor(), PorterDuff.Mode.SRC_IN)); + arrowDrawable.invalidateSelf(); + + updateColor(card, currency); + + card.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + card.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if(view.findViewById(R.id.collapsableLayout).getVisibility() == View.VISIBLE) + { + collapseView(view); + } + else + { + extendView(view); + } + } + }); + + card.findViewById(R.id.LineChartView).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent intent = new Intent(getActivity(), CurrencyDetailsActivity.class); + intent.putExtra("currency", currency); + getActivity().getApplicationContext().startActivity(intent); + } + }); + + if(currency.getHistoryMinutes() != null) + { + setupLineChart(card, currency); + } + + ((LinearLayout) view.findViewById(R.id.linearLayoutWatchlist)).addView(card, 0); + } + + if(refreshLayout.isRefreshing()) + { + refreshLayout.setRefreshing(false); + } + } + } + private LineData generateData(Currency currency) + { + LineDataSet dataSet; + List dataChartList = currency.getHistoryMinutes(); + ArrayList values = new ArrayList<>(); + + Log.d("coinfolio", "Generating data for " + currency.getSymbol()); + for(int i = 0; i < dataChartList.size(); i+=10) + { + values.add(new Entry(i, (float) dataChartList.get(i).getOpen())); + } + + dataSet = new LineDataSet(values, "History"); + dataSet.setDrawIcons(false); + dataSet.setColor(currency.getChartColor()); + dataSet.setLineWidth(1); + dataSet.setDrawFilled(true); + dataSet.setFillColor(getColorWithAplha(currency.getChartColor(), 0.5f)); + dataSet.setFormLineWidth(1); + dataSet.setFormSize(15); + dataSet.setDrawCircles(false); + dataSet.setDrawValues(false); + dataSet.setHighlightEnabled(false); + + return new LineData(dataSet); + } + + private int getColorWithAplha(int color, float ratio) + { + int transColor; + int alpha = Math.round(Color.alpha(color) * ratio); + int r = Color.red(color); + int g = Color.green(color); + int b = Color.blue(color); + + transColor = Color.argb(alpha, r, g, b); + + return transColor ; + } + + private void setupLineChart(View view, final Currency currency) + { + LineChart lineChart = view.findViewById(R.id.LineChartView); + + lineChart.setDrawGridBackground(false); + lineChart.setDrawBorders(false); + lineChart.setDrawMarkers(false); + lineChart.setDoubleTapToZoomEnabled(false); + lineChart.setPinchZoom(false); + lineChart.setScaleEnabled(false); + lineChart.setDragEnabled(false); + lineChart.getDescription().setEnabled(false); + lineChart.getAxisLeft().setEnabled(false); + lineChart.getAxisRight().setEnabled(false); + lineChart.getLegend().setEnabled(false); + lineChart.getXAxis().setEnabled(false); + lineChart.setViewPortOffsets(0, 0, 0, 0); + lineChart.setData(generateData(currency)); + } + + private void updateColor(View card, Currency currency) + { + if(currency.getDayFluctuation() > 0) + { + ((TextView) card.findViewById(R.id.currencyFluctuationPercentageTextView)).setTextColor(getResources().getColor(R.color.increase)); + ((TextView) card.findViewById(R.id.currencyFluctuationTextView)).setTextColor(getResources().getColor(R.color.increase)); + } + else + { + ((TextView) card.findViewById(R.id.currencyFluctuationPercentageTextView)).setTextColor(getResources().getColor(R.color.decrease)); + ((TextView) card.findViewById(R.id.currencyFluctuationTextView)).setTextColor(getResources().getColor(R.color.decrease)); + } + } + + 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 getBitmapFromURL(String src, HomeActivity.IconCallBack callBack) { + Bitmap result; + + try { + java.net.URL url = new java.net.URL(src); + HttpURLConnection connection = (HttpURLConnection) url + .openConnection(); + connection.setDoInput(true); + connection.connect(); + InputStream input = connection.getInputStream(); + result = BitmapFactory.decodeStream(input); + } catch (IOException e) { + e.printStackTrace(); + result = BitmapFactory.decodeResource(this.getResources(), + R.mipmap.icon_coinfolio); + result = Bitmap.createScaledBitmap(result, 50, 50, false); + } + + callBack.onSuccess(result); + } + + private void updateChartColor(Currency currency) + { + if(currency.getIcon() != null) + { + Palette.Builder builder = Palette.from(currency.getIcon()); + + currency.setChartColor(builder.generate().getDominantColor(0)); + } + else + { + currency.setChartColor(12369084); + } + } + + private class WatchlistUpdater extends AsyncTask + { + @Override + protected void onPreExecute() + { + watchlistCounter = 0; + } + + @Override + protected Void doInBackground(Void... voids) { + for(final Currency currency : watchlistManager.getWatchlist()) + { + currency.updateHistoryMinutes(getActivity(), new Currency.CurrencyCallBack() { + @Override + public void onSuccess(final Currency sucessCurrency) { + if(getIconUrl(sucessCurrency.getSymbol()) != null) + { + getBitmapFromURL(getIconUrl(sucessCurrency.getSymbol()), new HomeActivity.IconCallBack() { + @Override + public void onSuccess(Bitmap bitmapIcon) { + sucessCurrency.setIcon(bitmapIcon); + updateChartColor(currency); + countWatchlist(); + } + }); + } + } + }); + } + return null; + } + } + + private String numberConformer(double number) + { + String str; + + if(abs(number) > 1) + { + str = String.format( Locale.UK, "%.2f", number); + } + else + { + str = String.format( Locale.UK, "%.4f", number); + } + + return str; + } +} diff --git a/app/src/main/java/com/nauk/coinfolio/Activities/RecordTransactionActivity.java b/app/src/main/java/com/nauk/coinfolio/Activities/RecordTransactionActivity.java index aa07931..28374d9 100644 --- a/app/src/main/java/com/nauk/coinfolio/Activities/RecordTransactionActivity.java +++ b/app/src/main/java/com/nauk/coinfolio/Activities/RecordTransactionActivity.java @@ -3,21 +3,35 @@ package com.nauk.coinfolio.Activities; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; +import android.util.Log; import android.view.View; import android.widget.Button; +import android.widget.DatePicker; +import android.widget.EditText; import android.widget.TextView; +import android.widget.TimePicker; +import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; import com.nauk.coinfolio.DataManagers.DatabaseManager; +import com.nauk.coinfolio.DataManagers.PreferencesManager; import com.nauk.coinfolio.R; +import java.text.SimpleDateFormat; +import java.util.Calendar; + public class RecordTransactionActivity extends AppCompatActivity { private String coin; private String symbol; - private TextView symbolTxtView; - private TextView amountTxtView; + private EditText amountTxtView; + private TextView purchasedDate; private Button validateButton; private DatabaseManager databaseManager; + private Calendar calendar; + private SimpleDateFormat sdf; + private PreferencesManager preferenceManager; + private EditText purchasedPrice; + private Currency currency; @Override protected void onCreate(Bundle savedInstanceState) { @@ -30,22 +44,93 @@ public class RecordTransactionActivity extends AppCompatActivity { setTitle("Add " + coin + " transaction"); + sdf = new SimpleDateFormat(" HH:mm dd/MM/yyyy"); + + calendar = Calendar.getInstance(); + + currency = new Currency(coin, symbol); + databaseManager = new DatabaseManager(this); + preferenceManager = new PreferencesManager(this); validateButton = findViewById(R.id.validateButton); - amountTxtView = findViewById(R.id.currencyAmount); + purchasedDate = findViewById(R.id.purchaseDate); + purchasedPrice = findViewById(R.id.purchasePrice); + + //purchasedPrice.setText(); + purchasedDate.setText(sdf.format(calendar.getTime())); + + purchasedDate.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + createDatePicker(); + } + }); validateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - databaseManager.addCurrencyToManualCurrency(symbol, Double.parseDouble(amountTxtView.getText().toString())); + databaseManager.addCurrencyToManualCurrency(symbol, Double.parseDouble(amountTxtView.getText().toString()), calendar.getTime(), purchasedPrice.getText().toString()); + preferenceManager.setMustUpdateSummary(true); Intent intent = new Intent(RecordTransactionActivity.this, HomeActivity.class); - intent.putExtra("update", true); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent); finish(); } }); + + currency.getTimestampPrice(this, new Currency.PriceCallBack() { + @Override + public void onSuccess(String price) { + purchasedPrice.setText(price); + } + }, calendar.getTimeInMillis() / 1000); + } + + 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); + purchasedDate.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); + purchasedDate.setText(sdf.format(calendar.getTime())); + + currency.getTimestampPrice(RecordTransactionActivity.this, new Currency.PriceCallBack() { + @Override + public void onSuccess(String price) { + purchasedPrice.setText(price); + } + }, calendar.getTimeInMillis() / 1000); + Log.d("coinfolio", "Time : " + calendar.getTimeInMillis()); + } + }, + calendar.get(Calendar.HOUR_OF_DAY), + calendar.get(Calendar.MINUTE), + true + ).show(); } } diff --git a/app/src/main/java/com/nauk/coinfolio/Activities/SettingsActivity.java b/app/src/main/java/com/nauk/coinfolio/Activities/SettingsActivity.java index 40e91e8..9f032d5 100644 --- a/app/src/main/java/com/nauk/coinfolio/Activities/SettingsActivity.java +++ b/app/src/main/java/com/nauk/coinfolio/Activities/SettingsActivity.java @@ -20,6 +20,7 @@ import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.RingtonePreference; +import android.preference.SwitchPreference; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyPermanentlyInvalidatedException; import android.security.keystore.KeyProperties; @@ -131,8 +132,6 @@ public class SettingsActivity extends AppCompatPreferenceActivity { return true; } - Log.d("coinfolio", "hello"); - return super.onOptionsItemSelected(item); } @@ -198,7 +197,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity { */ protected boolean isValidFragment(String fragmentName) { return PreferenceFragment.class.getName().equals(fragmentName) - //|| GeneralPreferenceFragment.class.getName().equals(fragmentName) + || GeneralPreferenceFragment.class.getName().equals(fragmentName) || DataSyncPreferenceFragment.class.getName().equals(fragmentName) || NotificationPreferenceFragment.class.getName().equals(fragmentName) || ExchangePreferenceFragment.class.getName().equals(fragmentName); @@ -216,12 +215,21 @@ public class SettingsActivity extends AppCompatPreferenceActivity { addPreferencesFromResource(R.xml.pref_general); setHasOptionsMenu(true); - // Bind the summaries of EditText/List/Dialog/Ringtone preferences - // to their values. When their values change, their summaries are - // updated to reflect the new value, per the Android Design - // guidelines. - bindPreferenceSummaryToValue(findPreference("example_text")); - bindPreferenceSummaryToValue(findPreference("example_list")); + findPreference("hide_balance").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + boolean isChecked = ((SwitchPreference) findPreference("hide_balance")).isChecked(); + + SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext()); + + SharedPreferences.Editor editor = preferences.edit(); + + editor.putBoolean("hide_balance", isChecked); + editor.apply(); + + return isChecked; + } + }); } @Override @@ -259,6 +267,38 @@ public class SettingsActivity extends AppCompatPreferenceActivity { bindPreferenceSummaryToValue(findPreference("hitbtc_privatekey")); bindPreferenceSummaryToValue(findPreference("binance_privatekey")); + findPreference("enable_hitbtc").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + boolean isChecked = ((SwitchPreference) findPreference("enable_hitbtc")).isChecked(); + + SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext()); + + SharedPreferences.Editor editor = preferences.edit(); + + editor.putBoolean("mustUpdateSummary", true); + editor.apply(); + + return isChecked; + } + }); + + findPreference("enable_binance").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + boolean isChecked = ((SwitchPreference) findPreference("enable_binance")).isChecked(); + + SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext()); + + SharedPreferences.Editor editor = preferences.edit(); + + editor.putBoolean("mustUpdateSummary", true); + editor.apply(); + + return isChecked; + } + }); + startFingerprintProtocol(); } @@ -280,7 +320,6 @@ public class SettingsActivity extends AppCompatPreferenceActivity { if(preferences.getBoolean("enable_fingerprint", false)) { - newFragment.setCancelable(false); newFragment.show(getFragmentManager(), "dialog"); diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/BalanceManager.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/BalanceManager.java index be4cf06..5dc3515 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/BalanceManager.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/BalanceManager.java @@ -10,6 +10,7 @@ import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; +import com.nauk.coinfolio.DataManagers.CurrencyData.CurrencyDetailsList; import com.nauk.coinfolio.DataManagers.ExchangeManager.BinanceManager; import com.nauk.coinfolio.DataManagers.ExchangeManager.HitBtcManager; import com.nauk.coinfolio.R; @@ -46,6 +47,7 @@ public class BalanceManager { private LinkedHashMap coinInfosHashmap; private PreferencesManager preferenceManager; private DatabaseManager databaseManager; + private CurrencyDetailsList currencyDetailsList; private int balanceCounter; @@ -65,37 +67,20 @@ public class BalanceManager { databaseManager = new DatabaseManager(context); hitBtcManagers = new ArrayList<>(); binanceManagers = new ArrayList<>(); + currencyDetailsList = new CurrencyDetailsList(context); balanceCounter = 0; } - public List getCurrenciesName() - { - List 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 getBiggestCurrencies() { List currenciesDetails = new ArrayList<>(); int index = 0; - Iterator coinIterator = coinInfosHashmap.keySet().iterator(); + Iterator coinIterator = currencyDetailsList.getCoinInfosHashmap().keySet().iterator(); while(index < 11) { - //currenciesDetails.add(index, coinInfosHashmap.keySet().iterator().next()); index++; Log.d("coinfolio", "For " + index + " : " + coinIterator.next()); @@ -104,28 +89,6 @@ public class BalanceManager { return currenciesDetails; } - public List getOrders() - { - List currenciesOrder = new ArrayList<>(); - - for(String symbol : coinInfosHashmap.keySet()) - { - try { - JSONObject jsonObject = new JSONObject(coinInfosHashmap.get(symbol)); - currenciesOrder.add(jsonObject.getString("SortOrder")); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - return currenciesOrder; - } - - public List getCurrenciesSymbol() - { - return new ArrayList<>(coinInfosHashmap.keySet()); - } - public void updateExchangeKeys() { String publicKey = preferenceManager.getHitBTCPublicKey(); @@ -158,7 +121,7 @@ public class BalanceManager { { boolean isUpdated = false; - manualBalances = databaseManager.getAllCurrencyFromManualCurrency(); + manualBalances = databaseManager.getAllCurrenciesFromManualCurrency(); if(binanceManagers.size() > 0) { @@ -290,7 +253,8 @@ public class BalanceManager { public void updateDetails(final IconCallBack callBack) { - StringRequest strRequest = new StringRequest(Request.Method.GET, detailUrl, + currencyDetailsList.update(callBack); + /*StringRequest strRequest = new StringRequest(Request.Method.GET, detailUrl, new Response.Listener() { @Override public void onResponse(String response) { @@ -306,7 +270,7 @@ public class BalanceManager { } }); - requestQueue.add(strRequest); + requestQueue.add(strRequest);*/ } public String getIconUrl(String symbol) @@ -314,7 +278,7 @@ public class BalanceManager { String url; try { - JSONObject jsonObject = new JSONObject(coinInfosHashmap.get(symbol)); + JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol)); url = "https://www.cryptocompare.com" + jsonObject.getString("ImageUrl") + "?width=50"; } catch (NullPointerException e) { Log.d(context.getResources().getString(R.string.debug), symbol + " has no icon URL"); @@ -332,7 +296,7 @@ public class BalanceManager { String currencyName = null; try { - JSONObject jsonObject = new JSONObject(coinInfosHashmap.get(symbol)); + JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol)); currencyName = jsonObject.getString("CoinName"); } catch (JSONException e) { e.printStackTrace(); @@ -346,7 +310,7 @@ public class BalanceManager { int id = 0; try { - JSONObject jsonObject = new JSONObject(coinInfosHashmap.get(symbol)); + JSONObject jsonObject = new JSONObject(currencyDetailsList.getCoinInfosHashmap().get(symbol)); id = jsonObject.getInt("Id"); } catch (JSONException e) { e.printStackTrace(); @@ -355,32 +319,6 @@ public class BalanceManager { return id; } - private void processDetailResult(String response, final IconCallBack callBack) - { - response = response.substring(response.indexOf("\"Data\"") + 7, response.lastIndexOf("},\"Type\":100}")); - 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]); - - coinInfosHashmap.put(jsonObject.getString("Symbol"), tab[i]); - } catch (JSONException e) { - Log.d(context.getResources().getString(R.string.debug), "ImageUrl not found."); - } - } - - sortDetails(); - - callBack.onSuccess(); - } - private void sortDetails() { LinkedHashMap sortedHashmap = new LinkedHashMap<>(); diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/Currency.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/Currency.java index 5befeb7..2f6ea8e 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/Currency.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/Currency.java @@ -3,6 +3,12 @@ package com.nauk.coinfolio.DataManagers.CurrencyData; import android.graphics.Bitmap; import android.os.Parcel; import android.os.Parcelable; +import android.util.Log; + +import com.nauk.coinfolio.R; + +import org.json.JSONException; +import org.json.JSONObject; import java.util.ArrayList; import java.util.List; @@ -28,21 +34,12 @@ public class Currency implements Parcelable { private CurrencyDataRetriever dataRetriver; private Bitmap icon; private int chartColor; - - public Currency(Currency currency) - { - this.id = currency.id; - this.name = currency.name; - this.symbol = currency.symbol; - this.value = currency.value; - this.balance = currency.balance; - this.dayFluctuationPercentage = currency.getDayFluctuationPercentage(); - this.dayFluctuation = currency.getDayFluctuation(); - this.historyMinutes = currency.historyMinutes; - this.dataRetriver = currency.getDataRetriver(); - this.icon = currency.icon; - this.chartColor = currency.chartColor; - } + private int circulatingSupply; + private int totalSupply; + private double marketCapitalization; + private List socialMediaLinks; + private String algorithm; + //private String proofType public Currency(String symbol, double balance) { @@ -63,6 +60,41 @@ public class Currency implements Parcelable { this.symbol = symbol; } + //public Currency(int id, String symbol, String name, String algorithm, String proofType, ) + + public void getTimestampPrice(android.content.Context context, final PriceCallBack callBack, long timestamp) + { + dataRetriver = new CurrencyDataRetriever(context); + + dataRetriver.getPriceTimestamp(symbol, new CurrencyDataRetriever.DataChartCallBack() { + @Override + public void onSuccess(List dataChart) {} + + @Override + public void onSuccess(String price) { + callBack.onSuccess(price); + } + }, timestamp); + } + + public static String getIconUrl(String currencyDetails) + { + String url; + + try { + JSONObject jsonObject = new JSONObject(currencyDetails); + url = "https://www.cryptocompare.com" + jsonObject.getString("ImageUrl") + "?width=50"; + } 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 void updateHistoryMinutes(android.content.Context context, final CurrencyCallBack callBack) { dataRetriver = new CurrencyDataRetriever(context); @@ -84,6 +116,9 @@ public class Currency implements Parcelable { callBack.onSuccess(Currency.this); } + + @Override + public void onSuccess(String result){} }, CurrencyDataRetriever.MINUTES); } @@ -97,6 +132,9 @@ public class Currency implements Parcelable { callBack.onSuccess(Currency.this); } + + @Override + public void onSuccess(String price) {} }, CurrencyDataRetriever.HOURS); } @@ -110,9 +148,18 @@ public class Currency implements Parcelable { callBack.onSuccess(Currency.this); } + + @Override + public void onSuccess(String price) {} }, CurrencyDataRetriever.DAYS); } + public void updateDetails(android.content.Context context, final CurrencyCallBack callBack) + { + dataRetriver = new CurrencyDataRetriever(context); + + } + public void setId(int id) { this.id = id; @@ -237,6 +284,9 @@ public class Currency implements Parcelable { void onSuccess(Currency currency); } + public interface PriceCallBack { + void onSuccess(String price); + } @Override public int describeContents() { diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDataChart.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDataChart.java index 31cc654..4173c5e 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDataChart.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDataChart.java @@ -9,19 +9,23 @@ import android.os.Parcelable; public class CurrencyDataChart implements Parcelable { - long timestamp; - double close; - double high; - double low; - double open; + private long timestamp; + private double close; + private double high; + private double low; + private double open; + private double volumeFrom; + private double volumeTo; - public CurrencyDataChart(long timestamp, double close, double high, double low, double open) + public CurrencyDataChart(long timestamp, double close, double high, double low, double open, double volumeFrom, double volumeTo) { this.timestamp = timestamp; this.close = close; this.high = high; this.low = low; this.open = open; + this.volumeFrom = volumeFrom; + this.volumeTo = volumeTo; } public double getOpen() @@ -34,11 +38,41 @@ public class CurrencyDataChart implements Parcelable { return close; } + public double getVolumeTo() + { + return volumeTo; + } + + public double getVolumeFrom() + { + return volumeFrom; + } + public long getTimestamp() { return timestamp; } + public void setClose(double close) { + this.close = close; + } + + public double getHigh() { + return high; + } + + public void setHigh(double high) { + this.high = high; + } + + public double getLow() { + return low; + } + + public void setLow(double low) { + this.low = low; + } + @Override public int describeContents() { return 0; @@ -51,6 +85,8 @@ public class CurrencyDataChart implements Parcelable { dest.writeDouble(this.high); dest.writeDouble(this.low); dest.writeDouble(this.open); + dest.writeDouble(this.volumeFrom); + dest.writeDouble(this.volumeTo); } protected CurrencyDataChart(Parcel in) { @@ -59,6 +95,8 @@ public class CurrencyDataChart implements Parcelable { this.high = in.readDouble(); this.low = in.readDouble(); this.open = in.readDouble(); + this.volumeFrom = in.readDouble(); + this.volumeTo = in.readDouble(); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDataRetriever.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDataRetriever.java index b7e59ab..c18e916 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDataRetriever.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDataRetriever.java @@ -1,5 +1,6 @@ package com.nauk.coinfolio.DataManagers.CurrencyData; +import android.provider.ContactsContract; import android.util.Log; import com.android.volley.Request; @@ -42,7 +43,58 @@ public class CurrencyDataRetriever { requestQueue = Volley.newRequestQueue(context); } + private void getPriceTimestamp(final String symbolCurrencyFrom, String symbolCurrencyTo, final DataChartCallBack callBack, long timestamp) + { + final String requestUrl = "https://min-api.cryptocompare.com/data/pricehistorical?fsym=" + symbolCurrencyFrom + "&tsyms=" + symbolCurrencyTo + "&ts=" + timestamp; + + StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl, + new Response.Listener() { + @Override + public void onResponse(String response) { + Log.d("coinfolio", response + " " + requestUrl); + callBack.onSuccess(processPriceTimestampResult(response)); + } + }, + new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + + } + }); + + requestQueue.add(stringRequest); + } + + private String processPriceTimestampResult(String result) + { + result = result.substring(result.lastIndexOf(':')+1); + result = result.substring(0, result.indexOf('}')); + + return result; + } + private void updateHistory(final String symbolCurrencyFrom, String symbolCyrrencyTo, final DataChartCallBack callBack, int timeUnit) + { + String requestUrl = getRequestUrl(timeUnit, symbolCurrencyFrom, symbolCyrrencyTo); + + StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl, + new Response.Listener() { + @Override + public void onResponse(String response) { + callBack.onSuccess(processHistoryResult(response)); + } + }, + new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + callBack.onSuccess((List) null); + } + }); + + requestQueue.add(stringRequest); + } + + private String getRequestUrl(int timeUnit, String symbolCurrencyFrom, String symbolCyrrencyTo) { String requestUrl = null; @@ -59,21 +111,7 @@ public class CurrencyDataRetriever { break; } - StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl, - new Response.Listener() { - @Override - public void onResponse(String response) { - callBack.onSuccess(processHistoryResult(response)); - } - }, - new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - callBack.onSuccess(null); - } - }); - - requestQueue.add(stringRequest); + return requestUrl; } private List processHistoryResult(String response) @@ -99,13 +137,7 @@ public class CurrencyDataRetriever { try { JSONObject jsonObject = new JSONObject(tab[i]); - long timestamp = Long.parseLong(jsonObject.getString("time")); - double close = Double.parseDouble(jsonObject.getString("close")); - double high = Double.parseDouble(jsonObject.getString("high")); - double low = Double.parseDouble(jsonObject.getString("low")); - double open = Double.parseDouble(jsonObject.getString("open")); - - dataChart.add(new CurrencyDataChart(timestamp, close, high, low, open)); + dataChart.add(parseJSON(jsonObject)); } catch (JSONException e) { Log.d(context.getResources().getString(R.string.debug_volley), "API Request error: " + e + " index: " + i); @@ -120,11 +152,29 @@ public class CurrencyDataRetriever { return dataChart; } - void updateHistory(String symbolCurrencyFrom, final DataChartCallBack callBack, int timeUnit) + private CurrencyDataChart parseJSON(JSONObject jsonObject) throws JSONException { + + long timestamp = Long.parseLong(jsonObject.getString("time")); + double close = Double.parseDouble(jsonObject.getString("close")); + double high = Double.parseDouble(jsonObject.getString("high")); + double low = Double.parseDouble(jsonObject.getString("low")); + double open = Double.parseDouble(jsonObject.getString("open")); + double volumeFrom = Double.parseDouble(jsonObject.getString("volumefrom")); + double volumeTo = Double.parseDouble(jsonObject.getString("volumeto")); + + return new CurrencyDataChart(timestamp, close, high, low, open, volumeFrom, volumeTo); + } + + public void getPriceTimestamp(String symbolCurrencyFrom, final DataChartCallBack callBack, long timestamp) + { + getPriceTimestamp(symbolCurrencyFrom, "USD", callBack, timestamp); + } + + public void updateHistory(String symbolCurrencyFrom, final DataChartCallBack callBack, int timeUnit) { if(symbolCurrencyFrom.equals("USD")) { - callBack.onSuccess(null); + callBack.onSuccess((List) null); } else { @@ -132,7 +182,34 @@ public class CurrencyDataRetriever { } } + /*public void updateCryptocompareDetails(int id, final Currency.CurrencyCallBack callBack) + { + String requestUrl = getRequestUrl(timeUnit, symbolCurrencyFrom, symbolCyrrencyTo); + + StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl, + new Response.Listener() { + @Override + public void onResponse(String response) { + callBack.onSuccess(); + } + }, + new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + callBack.onSuccess(); + } + }); + + requestQueue.add(stringRequest); + }*/ + + public void updateCoinMarketCapDetails() + { + + } + public interface DataChartCallBack { void onSuccess(List dataChart); + void onSuccess(String price); } } diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDetailsList.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDetailsList.java new file mode 100644 index 0000000..0456eb9 --- /dev/null +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/CurrencyDetailsList.java @@ -0,0 +1,149 @@ +package com.nauk.coinfolio.DataManagers.CurrencyData; + +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.nauk.coinfolio.Activities.HomeActivity; +import com.nauk.coinfolio.DataManagers.BalanceManager; +import com.nauk.coinfolio.R; + +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://www.cryptocompare.com/api/data/coinlist/"; + private RequestQueue requestQueue; + private LinkedHashMap coinInfosHashmap; + private android.content.Context context; + + public CurrencyDetailsList(android.content.Context context) + { + this.context = context; + requestQueue = Volley.newRequestQueue(context); + } + + public void update(final BalanceManager.IconCallBack callBack) + { + StringRequest strRequest = new StringRequest(Request.Method.GET, DETAILURL, + new Response.Listener() { + @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); + } + + + private void processDetailResult(String response, final BalanceManager.IconCallBack callBack) + { + response = response.substring(response.indexOf("\"Data\"") + 7, response.lastIndexOf("},\"Type\":100}")); + 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]); + + coinInfosHashmap.put(jsonObject.getString("Symbol"), tab[i]); + } catch (JSONException e) { + Log.d(context.getResources().getString(R.string.debug), "ImageUrl not found."); + } + } + + sortDetails(); + + callBack.onSuccess(); + } + + private void sortDetails() + { + LinkedHashMap sortedHashmap = new LinkedHashMap<>(); + List listInfos = new ArrayList<>(coinInfosHashmap.values()); + List 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 getCoinInfosHashmap() { + return coinInfosHashmap; + } + + public List getCurrenciesName() + { + List 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 getCurrenciesSymbol() + { + return new ArrayList<>(coinInfosHashmap.keySet()); + } +} diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/Transaction.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/Transaction.java index ac05f62..507cfa2 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/Transaction.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/CurrencyData/Transaction.java @@ -9,14 +9,17 @@ public class Transaction { private int transactionId; private String symbol; private double amount; + private long timestamp; private double purchasedPrice; private boolean isMined; - public Transaction(int transactionId, String symbol, double amount) + public Transaction(int transactionId, String symbol, double amount, long timestamp, double purchasedPrice) { this.transactionId = transactionId; this.symbol = symbol; this.amount = amount; + this.timestamp = timestamp; + this.purchasedPrice = purchasedPrice; } public int getTransactionId() { @@ -39,7 +42,22 @@ public class Transaction { return amount; } + public long getTimestamp() + { + return timestamp; + } + public void setAmount(double amount) { this.amount = amount; } + + public void setPurchasedPrice(double purchasedPrice) + { + this.purchasedPrice = purchasedPrice; + } + + public double getPurchasedPrice() + { + return purchasedPrice; + } } diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/DatabaseManager.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/DatabaseManager.java index 4afe2df..7219f2d 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/DatabaseManager.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/DatabaseManager.java @@ -5,11 +5,13 @@ import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; import com.nauk.coinfolio.DataManagers.CurrencyData.Transaction; import java.util.ArrayList; +import java.util.Date; import java.util.List; /** @@ -18,12 +20,13 @@ import java.util.List; public class DatabaseManager extends SQLiteOpenHelper{ - private static final int DATABASE_VERSION = 5; + private static final int DATABASE_VERSION = 6; private static final String DATABASE_NAME = "Currencies.db"; private static final String TABLE_MANUAL_CURRENCIES = "ManualCurrencies"; private static final String TABLE_EXCHANGE_KEYS = "ExchangeKeys"; + private static final String TABLE_WATCHLIST = "Watchlist"; private static final String KEY_CURRENCY_ID = "idCurrency"; private static final String KEY_CURRENCY_SYMBOL = "symbol"; @@ -38,6 +41,11 @@ public class DatabaseManager extends SQLiteOpenHelper{ private static final String KEY_EXCHANGE_PUBLIC_KEY = "publicKey"; private static final String KEY_EXCHANGE_SECRET_KEY = "secretKey"; + 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 DatabaseManager(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); @@ -51,8 +59,8 @@ public class DatabaseManager extends SQLiteOpenHelper{ + KEY_CURRENCY_SYMBOL + " VARCHAR(4)," + KEY_CURRENCY_NAME + " VARCHAR(45)," + KEY_CURRENCY_BALANCE + " TEXT," - + KEY_CURRENCY_DATE + " DATE," - + KEY_CURRENCY_PURCHASED_PRICE + " TEXT," + + KEY_CURRENCY_DATE + " TEXT," + + KEY_CURRENCY_PURCHASED_PRICE + " REAL," + KEY_CURRENCY_IS_MINED + " INTEGER" + ");"); @@ -63,6 +71,13 @@ public class DatabaseManager extends SQLiteOpenHelper{ + KEY_EXCHANGE_SECRET_KEY + " TEXT" + ");"); + db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_WATCHLIST + "(" + + KEY_WATCHLIST_ID + " INTEGER PRIMARY KEY," + + KEY_WATCHLIST_SYMBOL + " VARCHAR(4)," + + KEY_WATCHLIST_NAME + " TEXT," + + KEY_WATCHLIST_POSITION + " INTEGER" + + ");"); + //loadSample(db); } @@ -71,25 +86,55 @@ public class DatabaseManager extends SQLiteOpenHelper{ { db.execSQL("DROP TABLE IF EXISTS " + TABLE_MANUAL_CURRENCIES); db.execSQL("DROP TABLE IF EXISTS " + TABLE_EXCHANGE_KEYS); + db.execSQL("DROP TABLE IF EXISTS " + TABLE_WATCHLIST); onCreate(db); } - public void addCurrencyToManualCurrency(String symbol, double balance) + public void addCurrencyToWatchlist(Currency currency) + { + SQLiteDatabase db = this.getWritableDatabase(); + ContentValues values = new ContentValues(); + + values.put(KEY_WATCHLIST_SYMBOL, currency.getSymbol()); + values.put(KEY_WATCHLIST_NAME, currency.getName()); + + db.insert(TABLE_WATCHLIST, null, values); + db.close(); + } + + public List getAllCurrenciesFromWatchlist() + { + String searchQuerry = "SELECT * FROM " + TABLE_WATCHLIST; + SQLiteDatabase db = this.getWritableDatabase(); + Cursor resultatList = db.rawQuery(searchQuerry, null); + + List currencyList = new ArrayList<>(); + + while(resultatList.moveToNext()) + { + currencyList.add(new Currency(resultatList.getString(2), resultatList.getString(1))); + } + + return currencyList; + } + + public void addCurrencyToManualCurrency(String symbol, double balance, Date date, String purchasedPrice) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_CURRENCY_SYMBOL, symbol); values.put(KEY_CURRENCY_BALANCE, balance); - //values.put(KEY_CURRENCY_DATE, getDate()); + values.put(KEY_CURRENCY_DATE, date.getTime()); + values.put(KEY_CURRENCY_PURCHASED_PRICE, purchasedPrice); //values.put(KEY_CURRENCY_PURCHASED_PRICE, something); db.insert(TABLE_MANUAL_CURRENCIES, null, values); db.close(); } - public List getAllCurrencyFromManualCurrency() + public List getAllCurrenciesFromManualCurrency() { String searchQuerry = "SELECT * FROM " + TABLE_MANUAL_CURRENCIES; SQLiteDatabase db = this.getWritableDatabase(); @@ -100,6 +145,7 @@ public class DatabaseManager extends SQLiteOpenHelper{ while(resultatList.moveToNext()) { currencyList.add(new Currency(resultatList.getString(1), resultatList.getDouble(3))); + Log.d("coinfolio", "Database output : " + resultatList.getString(1)); } resultatList.close(); @@ -109,20 +155,17 @@ public class DatabaseManager extends SQLiteOpenHelper{ return currencyList; } - //public HashMap getCurrencyTransactions(String symbol) public List getCurrencyTransactions(String symbol) { String searchQuerry = "SELECT * FROM " + TABLE_MANUAL_CURRENCIES + " WHERE symbol='" + symbol.toUpperCase() + "'"; SQLiteDatabase db = this.getWritableDatabase(); Cursor resultatList = db.rawQuery(searchQuerry, null); - //HashMap transactionList = new HashMap<>(); List transactionList = new ArrayList<>(); while(resultatList.moveToNext()) { - //transactionList.put(resultatList.getInt(0), resultatList.getDouble(3)); - transactionList.add(new Transaction(resultatList.getInt(0), resultatList.getString(1), resultatList.getDouble(3))); + transactionList.add(new Transaction(resultatList.getInt(0), resultatList.getString(1), resultatList.getDouble(3), resultatList.getLong(4), resultatList.getLong(5))); } resultatList.close(); diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/ExchangeManager/BinanceManager.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/ExchangeManager/BinanceManager.java index a035ca1..402394c 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/ExchangeManager/BinanceManager.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/ExchangeManager/BinanceManager.java @@ -1,13 +1,19 @@ package com.nauk.coinfolio.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.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.request.OrderRequest; import com.binance.api.client.exception.BinanceApiException; import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -21,8 +27,7 @@ public class BinanceManager { private String privateKey; private List balance; - - public BinanceManager(){} + private HashMap> trades; public BinanceManager(String publicKey, String privateKey) { @@ -32,7 +37,6 @@ public class BinanceManager { public void updateBalance(BinanceCallBack callBack) { - Map accountBalanceCache; BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(publicKey, privateKey); BinanceApiRestClient client = factory.newRestClient(); @@ -56,14 +60,46 @@ public class BinanceManager { } } - public void setPublicKey(String publicKey) + public void updateTrades(BinanceCallBack callBack, String symbol) { - this.publicKey = publicKey; + trades = new HashMap<>(); + + trades.put("BTC", updateTrades(null, symbol, "BTC")); + + trades.put("ETH", updateTrades(null, symbol, "ETH")); + + trades.put("USDT", updateTrades(null, symbol, "USDT")); + + callBack.onSuccess(); } - public void setPrivateKey(String privateKey) + public List updateTrades(BinanceCallBack callBack, String symbol, String pairSymbol) { - this.privateKey = privateKey; + List presentTrades = new ArrayList<>(); + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(publicKey, privateKey); + BinanceApiRestClient client = factory.newRestClient(); + + if(!symbol.equals(pairSymbol)) + { + try { + presentTrades = client.getMyTrades(symbol + pairSymbol); + + } catch (BinanceApiException e) { + try { + presentTrades = client.getMyTrades(pairSymbol + symbol); + + } catch (BinanceApiException f) { + f.printStackTrace(); + } + } + } + + if(callBack != null) + { + callBack.onSuccess(); + } + + return presentTrades; } public List getBalance() @@ -71,6 +107,11 @@ public class BinanceManager { return balance; } + public HashMap> getTrades() + { + return trades; + } + public interface BinanceCallBack { void onSuccess(); void onError(String error); diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/ExchangeManager/HitBtcManager.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/ExchangeManager/HitBtcManager.java index 43c7a91..0102501 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/ExchangeManager/HitBtcManager.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/ExchangeManager/HitBtcManager.java @@ -36,12 +36,6 @@ public class HitBtcManager { private List balance; private android.content.Context context; - public HitBtcManager(android.content.Context context) - { - this.context = context; - requestQueue = Volley.newRequestQueue(context); - } - public HitBtcManager(android.content.Context context, String publicKey, String privateKey) { this.context = context; @@ -53,27 +47,9 @@ public class HitBtcManager { public void updateBalance(final HitBtcCallBack callBack) { - JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, hitBalanceUrl, - new Response.Listener() { - @Override - public void onResponse(JSONArray response) { - if (response.length() > 0) { - parseBalance(response); - } else { - //No balance - } - - callBack.onSuccess(); - } - }, - new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - Log.e(context.getResources().getString(R.string.debug), "API Error : " + error); - callBack.onError(error.toString()); - } - } - ) { + JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, hitBalanceUrl + , getResponseListener(callBack), getErrorResponseListener(callBack)) + { @Override public Map getHeaders() throws AuthFailureError { Map headers = new HashMap<>(); @@ -89,6 +65,31 @@ public class HitBtcManager { requestQueue.add(arrayRequest); } + private Response.Listener getResponseListener(final HitBtcCallBack callBack) + { + return new Response.Listener() { + @Override + public void onResponse(JSONArray response) { + if (response.length() > 0) { + parseBalance(response); + } + + callBack.onSuccess(); + } + }; + } + + private Response.ErrorListener getErrorResponseListener(final HitBtcCallBack callBack) + { + return new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + Log.e(context.getResources().getString(R.string.debug), "API Error : " + error); + callBack.onError(error.toString()); + } + }; + } + private void parseBalance(JSONArray response) { balance = new ArrayList<>(); @@ -109,16 +110,6 @@ public class HitBtcManager { } } - public void setPublicKey(String publicKey) - { - this.publicKey = publicKey; - } - - private void setPrivateKey(String privateKey) - { - this.privateKey = privateKey; - } - public List getBalance() { return balance; diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/MarketCapManager.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/MarketCapManager.java index 9cf3b5e..1045f5d 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/MarketCapManager.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/MarketCapManager.java @@ -24,7 +24,6 @@ public class MarketCapManager { private static final String topCurrenciesUrl = "https://api.coinmarketcap.com/v1/ticker/?limit=9"; private static final String marketCapUrl = "https://api.coinmarketcap.com/v1/global/"; - private android.content.Context context; private RequestQueue requestQueue; private String topRequestResult[]; private long marketCap; @@ -32,8 +31,6 @@ public class MarketCapManager { public MarketCapManager(android.content.Context context) { - this.context = context; - requestQueue = Volley.newRequestQueue(context); } @@ -127,8 +124,8 @@ public class MarketCapManager { for(int i = 0; i < topRequestResult.length; i++) { - try { - topRequestResult[i] += "}"; + topRequestResult[i] += "}"; + /*try { JSONObject jsonObject = new JSONObject(topRequestResult[i]); @@ -136,7 +133,7 @@ public class MarketCapManager { } catch (JSONException e) { e.printStackTrace(); - } + }*/ } } diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/PreferencesManager.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/PreferencesManager.java index b787925..706107f 100644 --- a/app/src/main/java/com/nauk/coinfolio/DataManagers/PreferencesManager.java +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/PreferencesManager.java @@ -14,23 +14,14 @@ public class PreferencesManager { private SharedPreferences settingPreferences; private SharedPreferences currencyList; private SharedPreferences preferencesList; - android.content.Context context; public PreferencesManager(android.content.Context context) { - this.context = context; settingPreferences = PreferenceManager.getDefaultSharedPreferences(context); currencyList = context.getSharedPreferences(currencyListFile, 0); preferencesList = context.getSharedPreferences(preferencesFile, 0); } - public void addCurrency(String symbol, double balance) - { - SharedPreferences.Editor editor = currencyList.edit(); - editor.putString(symbol, String.valueOf(balance)); - editor.apply(); - } - public void setDetailOption(boolean isExtended) { SharedPreferences.Editor editor = preferencesList.edit(); @@ -58,6 +49,11 @@ public class PreferencesManager { return settingPreferences.getBoolean("enable_hitbtc", false); } + public boolean isBalanceHidden() + { + return settingPreferences.getBoolean("hide_balance", false); + } + public void disableHitBTC() { SharedPreferences.Editor editor = settingPreferences.edit(); @@ -86,4 +82,42 @@ public class PreferencesManager { editor.putBoolean("enable_binance", false); editor.apply(); } + + public void setMustUpdateWatchlist(boolean mustUpdate) + { + SharedPreferences.Editor editor = settingPreferences.edit(); + editor.putBoolean("mustUpdateWatchlist", mustUpdate); + editor.apply(); + } + + public boolean mustUpdateWatchlist() + { + boolean mustUpdate = settingPreferences.getBoolean("mustUpdateWatchlist", false); + + if(mustUpdate) + { + setMustUpdateWatchlist(false); + } + + return mustUpdate; + } + + public void setMustUpdateSummary(boolean mustUpdate) + { + SharedPreferences.Editor editor = settingPreferences.edit(); + editor.putBoolean("mustUpdateSummary", mustUpdate); + editor.apply(); + } + + public boolean mustUpdateSummary() + { + boolean mustUpdate = settingPreferences.getBoolean("mustUpdateSummary", false); + + if(mustUpdate) + { + setMustUpdateSummary(false); + } + + return mustUpdate; + } } diff --git a/app/src/main/java/com/nauk/coinfolio/DataManagers/WatchlistManager.java b/app/src/main/java/com/nauk/coinfolio/DataManagers/WatchlistManager.java new file mode 100644 index 0000000..59453f0 --- /dev/null +++ b/app/src/main/java/com/nauk/coinfolio/DataManagers/WatchlistManager.java @@ -0,0 +1,37 @@ +package com.nauk.coinfolio.DataManagers; + +import com.android.volley.RequestQueue; +import com.android.volley.toolbox.Volley; +import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; + +import java.util.List; + +/** + * Created by Tiji on 13/04/2018. + */ + +public class WatchlistManager { + + private android.content.Context context; + private RequestQueue requestQueue; + private DatabaseManager databaseManager; + private List watchlistCurrencies; + + public WatchlistManager(android.content.Context context) + { + this.context = context; + + requestQueue = Volley.newRequestQueue(context); + databaseManager = new DatabaseManager(context); + } + + public void updateWatchlist() + { + watchlistCurrencies = databaseManager.getAllCurrenciesFromWatchlist(); + } + + public List getWatchlist() + { + return watchlistCurrencies; + } +} diff --git a/app/src/main/java/com/nauk/coinfolio/FingerprintToolkit/FingerprintDialogFragment.java b/app/src/main/java/com/nauk/coinfolio/FingerprintToolkit/FingerprintDialogFragment.java index 86ab29e..71c82e9 100644 --- a/app/src/main/java/com/nauk/coinfolio/FingerprintToolkit/FingerprintDialogFragment.java +++ b/app/src/main/java/com/nauk/coinfolio/FingerprintToolkit/FingerprintDialogFragment.java @@ -32,8 +32,6 @@ public class FingerprintDialogFragment extends DialogFragment{ View view = inflater.inflate(R.layout.fragment_fingerprint_scanner, container); - //getDialog().getWindow().setLayout(getResources().getDimensionPixelSize(R.dimen.fingerprint_dialog_width), getResources().getDimensionPixelSize(R.dimen.fingerprint_dialog_height)); - view.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { diff --git a/app/src/main/java/com/nauk/coinfolio/FingerprintToolkit/FingerprintHandler.java b/app/src/main/java/com/nauk/coinfolio/FingerprintToolkit/FingerprintHandler.java index bdbc661..0eae113 100644 --- a/app/src/main/java/com/nauk/coinfolio/FingerprintToolkit/FingerprintHandler.java +++ b/app/src/main/java/com/nauk/coinfolio/FingerprintToolkit/FingerprintHandler.java @@ -37,7 +37,6 @@ public class FingerprintHandler extends FingerprintManager.AuthenticationCallbac @Override public void onAuthenticationError(int errMsgId, CharSequence errString) { - //Toast.makeText(context, "Authentification error\n" + errString, Toast.LENGTH_LONG).show(); if(dialogFragment.isVisible()) { dialogFragment.wrongFingerprint("Error"); @@ -56,7 +55,6 @@ public class FingerprintHandler extends FingerprintManager.AuthenticationCallbac @Override public void onAuthenticationFailed() { - //Toast.makeText(context, "Authentification failed", Toast.LENGTH_LONG).show(); if(dialogFragment.isVisible()) { dialogFragment.wrongFingerprint("Wrong fingerprint"); @@ -75,8 +73,6 @@ public class FingerprintHandler extends FingerprintManager.AuthenticationCallbac @Override public void onAuthenticationHelp(int helpMsgIf, CharSequence helpString) { - //Toast.makeText(context, "Authentification help\n" + helpString, Toast.LENGTH_LONG).show(); - if(dialogFragment.isVisible()) { dialogFragment.wrongFingerprint(helpString.toString()); @@ -95,9 +91,6 @@ public class FingerprintHandler extends FingerprintManager.AuthenticationCallbac @Override public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { - //Toast.makeText(context, "Success !", Toast.LENGTH_LONG).show(); - //dialogFragment.dismiss(); - dialogFragment.correctFingerprint(); new Handler().postDelayed(new Runnable() { @Override diff --git a/app/src/main/java/com/nauk/coinfolio/LayoutManagers/CurrencyAdapter.java b/app/src/main/java/com/nauk/coinfolio/LayoutManagers/CurrencyListAdapter.java similarity index 85% rename from app/src/main/java/com/nauk/coinfolio/LayoutManagers/CurrencyAdapter.java rename to app/src/main/java/com/nauk/coinfolio/LayoutManagers/CurrencyListAdapter.java index 5691fd8..404440e 100644 --- a/app/src/main/java/com/nauk/coinfolio/LayoutManagers/CurrencyAdapter.java +++ b/app/src/main/java/com/nauk/coinfolio/LayoutManagers/CurrencyListAdapter.java @@ -17,12 +17,12 @@ import java.util.ArrayList; * Created by Guitoune on 17/01/2018. */ -public class CurrencyAdapter extends ArrayAdapter { +public class CurrencyListAdapter extends ArrayAdapter { private ArrayList tempCurrency, suggestions; private Context context; - public CurrencyAdapter(Context context, ArrayList objects) { + public CurrencyListAdapter(Context context, ArrayList objects) { super(context, android.R.layout.simple_list_item_1, objects); this.tempCurrency = new ArrayList(objects); this.suggestions = new ArrayList(objects); @@ -31,20 +31,25 @@ public class CurrencyAdapter extends ArrayAdapter { } @Override - public View getView(int position, View convertView, ViewGroup parent) { + public View getView(int position, View convertView, ViewGroup parent) + { Currency currency = getItem(position); + if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_currency_row, parent, false); } + TextView currencyName = convertView.findViewById(R.id.currencyName); TextView currencySymbol = convertView.findViewById(R.id.currencySymbol); + if (currencyName != null) currencyName.setText(currency.getName()); + if(currencySymbol != null) { currencySymbol.setText(currency.getSymbol()); } - // Now assign alternate color for rows + if (position % 2 == 0) convertView.setBackgroundColor(context.getResources().getColor(R.color.listBackground2)); else @@ -74,7 +79,7 @@ public class CurrencyAdapter extends ArrayAdapter { int found = 0; String temp = constraint.toString().toLowerCase(); - while(i < tempCurrency.size() && found < 25) + while(i < tempCurrency.size() && found < 50) { Currency currency = tempCurrency.get(i); if (currency.getName().toLowerCase().startsWith(temp) @@ -85,14 +90,6 @@ public class CurrencyAdapter extends ArrayAdapter { i++; } - - /*for (Currency currency : tempCurrency) { - if (currency.getName().toLowerCase().startsWith(temp) - || currency.getSymbol().toLowerCase().startsWith(temp)) { - suggestions.add(currency); - } - }*/ - FilterResults filterResults = new FilterResults(); filterResults.values = suggestions; filterResults.count = suggestions.size(); diff --git a/app/src/main/java/com/nauk/coinfolio/LayoutManagers/HomeLayoutGenerator.java b/app/src/main/java/com/nauk/coinfolio/LayoutManagers/HomeLayoutGenerator.java index 6196e3f..223b62b 100644 --- a/app/src/main/java/com/nauk/coinfolio/LayoutManagers/HomeLayoutGenerator.java +++ b/app/src/main/java/com/nauk/coinfolio/LayoutManagers/HomeLayoutGenerator.java @@ -5,16 +5,17 @@ import android.content.Intent; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; +import android.graphics.drawable.Drawable; +import android.support.v7.widget.CardView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; +import android.view.animation.Animation; +import android.view.animation.Transformation; import android.widget.ImageView; +import android.widget.ProgressBar; import android.widget.TextView; -import com.db.chart.model.ChartSet; -import com.db.chart.model.LineSet; -import com.db.chart.renderer.AxisRenderer; -import com.db.chart.view.LineChartView; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; @@ -24,9 +25,8 @@ import com.nauk.coinfolio.DataManagers.CurrencyData.Currency; import com.nauk.coinfolio.DataManagers.CurrencyData.CurrencyDataChart; import com.nauk.coinfolio.R; +import java.text.DecimalFormat; import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -38,32 +38,141 @@ import static java.lang.Math.abs; public class HomeLayoutGenerator { - android.content.Context context; + private android.content.Context context; public HomeLayoutGenerator(Context context) { this.context = context; } - public View getInfoLayout(final Currency currency, boolean isExtended) + public View getInfoLayout(final Currency currency, boolean isExtended, float totalValue, boolean isBalanceHidden) { - - View view = LayoutInflater.from(context).inflate(R.layout.cardview_currency, null); + View view = LayoutInflater.from(context).inflate(R.layout.cardview_currency, null, true); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - if(view.findViewById(R.id.LineChartView).getVisibility() == View.VISIBLE || view.findViewById(R.id.errorTextView).getVisibility() == View.VISIBLE) + if(view.findViewById(R.id.collapsableLayout).getVisibility() == View.VISIBLE) { collapseView(view); } else { - extendView(currency, view); + extendView(view); } } }); + updateCardViewInfos(view, currency, totalValue, isBalanceHidden); + + view.findViewById(R.id.LineChartView).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent intent = new Intent(context.getApplicationContext(), CurrencyDetailsActivity.class); + intent.putExtra("currency", currency); + context.getApplicationContext().startActivity(intent); + } + }); + + if(currency.getHistoryMinutes() != null) + { + setupLineChart(view, currency); + } + + if(isExtended) + { + extendView(view); + } + else + { + collapseView(view); + } + + updateColor(view, currency); + + return view; + } + + private static void expand(final View v) { + v.measure(CardView.LayoutParams.MATCH_PARENT, CardView.LayoutParams.WRAP_CONTENT); + final int targetHeight = v.getMeasuredHeight(); + + // Older versions of android (pre API 21) cancel animations for views with a height of 0. + v.getLayoutParams().height = 1; + v.setVisibility(View.VISIBLE); + Animation a = new Animation() + { + @Override + protected void applyTransformation(float interpolatedTime, Transformation t) { + v.getLayoutParams().height = interpolatedTime == 1 + ? CardView.LayoutParams.WRAP_CONTENT + : (int)(targetHeight * interpolatedTime); + v.requestLayout(); + } + + @Override + public boolean willChangeBounds() { + return true; + } + }; + + // 1dp/ms + a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density)); + v.startAnimation(a); + } + + private static void collapse(final View v) { + final int initialHeight = v.getMeasuredHeight(); + + Animation a = new Animation() + { + @Override + protected void applyTransformation(float interpolatedTime, Transformation t) { + if(interpolatedTime == 1){ + v.setVisibility(View.GONE); + }else{ + v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime); + v.requestLayout(); + } + } + + @Override + public boolean willChangeBounds() { + return true; + } + }; + + // 1dp/ms + a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density)); + v.startAnimation(a); + } + + private void setupLineChart(View view, final Currency currency) + { + LineChart lineChart = view.findViewById(R.id.LineChartView); + + lineChart.setDrawGridBackground(false); + lineChart.setDrawBorders(false); + lineChart.setDrawMarkers(false); + lineChart.setDoubleTapToZoomEnabled(false); + lineChart.setPinchZoom(false); + lineChart.setScaleEnabled(false); + lineChart.setDragEnabled(false); + lineChart.getDescription().setEnabled(false); + lineChart.getAxisLeft().setEnabled(false); + lineChart.getAxisRight().setEnabled(false); + lineChart.getLegend().setEnabled(false); + lineChart.getXAxis().setEnabled(false); + lineChart.setViewPortOffsets(0, 0, 0, 0); + lineChart.setData(generateData(currency)); + } + + private void updateCardViewInfos(View view, Currency currency, float totalValue, boolean isBalanceHidden) + { + double value = currency.getValue() * currency.getBalance(); + double percentage = value / totalValue * 100; + DecimalFormat df = new DecimalFormat(".##"); + ((ImageView) view.findViewById(R.id.currencyIcon)) .setImageBitmap(currency.getIcon()); ((TextView) view.findViewById(R.id.currencyNameTextView)) @@ -81,114 +190,43 @@ public class HomeLayoutGenerator { .setText(context.getResources().getString(R.string.currencyPercentagePlaceholder, numberConformer(currency.getDayFluctuationPercentage()))); ((TextView) view.findViewById(R.id.currencyFluctuationTextView)) .setText(context.getResources().getString(R.string.currencyDollarParenthesisPlaceholder, numberConformer(currency.getDayFluctuation()))); - ((ImageView) view.findViewById(R.id.detailsArrow)) - .getDrawable().setColorFilter(new PorterDuffColorFilter(currency.getChartColor(), PorterDuff.Mode.SRC_IN)); - view.findViewById(R.id.errorTextView).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(context.getApplicationContext(), CurrencyDetailsActivity.class); - intent.putExtra("currency", currency); - context.getApplicationContext().startActivity(intent); - } - }); + Drawable arrowDrawable = ((ImageView) view.findViewById(R.id.detailsArrow)).getDrawable(); + arrowDrawable.mutate(); + arrowDrawable.setColorFilter(new PorterDuffColorFilter(currency.getChartColor(), PorterDuff.Mode.SRC_IN)); + arrowDrawable.invalidateSelf(); - if(currency.getHistoryMinutes() != null) + Drawable progressBarDrawable = ((ProgressBar) view.findViewById(R.id.currencyPortfolioDominance)).getProgressDrawable(); + progressBarDrawable.mutate(); + progressBarDrawable.setColorFilter(new PorterDuffColorFilter(currency.getChartColor(), PorterDuff.Mode.SRC_IN)); + progressBarDrawable.invalidateSelf(); + + ((ProgressBar) view.findViewById(R.id.currencyPortfolioDominance)).setProgress((int) Math.round(percentage)); + ((TextView) view.findViewById(R.id.percentageOwnedTextView)).setText(context.getResources().getString(R.string.currencyPercentagePlaceholder, df.format(percentage))); + + if(isBalanceHidden) { - LineChart lineChart = view.findViewById(R.id.LineChartView); - - lineChart.setDrawGridBackground(false); - lineChart.setDrawBorders(false); - lineChart.setDrawMarkers(false); - lineChart.setDoubleTapToZoomEnabled(false); - lineChart.setPinchZoom(false); - lineChart.setScaleEnabled(false); - lineChart.setDragEnabled(false); - lineChart.getDescription().setEnabled(false); - lineChart.getAxisLeft().setEnabled(false); - lineChart.getAxisRight().setEnabled(false); - lineChart.getLegend().setEnabled(false); - lineChart.getXAxis().setEnabled(false); - lineChart.setViewPortOffsets(0, 0, 0, 0); - lineChart.setData(generateData(currency)); - - lineChart.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(context.getApplicationContext(), CurrencyDetailsActivity.class); - intent.putExtra("currency", currency); - context.getApplicationContext().startActivity(intent); - } - }); - } - - if(isExtended) - { - extendView(currency, view); + view.findViewById(R.id.currencyPortfolioDominance).setVisibility(View.VISIBLE); + view.findViewById(R.id.percentageOwnedTextView).setVisibility(View.VISIBLE); + view.findViewById(R.id.currencyOwnedInfoLayout).setVisibility(View.GONE); } else { - collapseView(view); + view.findViewById(R.id.currencyPortfolioDominance).setVisibility(View.INVISIBLE); + view.findViewById(R.id.percentageOwnedTextView).setVisibility(View.GONE); + view.findViewById(R.id.currencyOwnedInfoLayout).setVisibility(View.VISIBLE); } - - updateColor(view, currency); - - return view; } private void collapseView(View view) { - view.findViewById(R.id.separationLayout).setVisibility(View.GONE); - view.findViewById(R.id.frameLayoutChart).setVisibility(View.GONE); - view.findViewById(R.id.LineChartView).setVisibility(View.GONE); - view.findViewById(R.id.errorTextView).setVisibility(View.GONE); - view.findViewById(R.id.detailsArrow).setVisibility(View.GONE); + collapse(view.findViewById(R.id.collapsableLayout)); } - private void extendView(Currency currency, View view) + private void extendView(View view) { - view.findViewById(R.id.separationLayout).setVisibility(View.VISIBLE); - view.findViewById(R.id.detailsArrow).setVisibility(View.VISIBLE); - view.findViewById(R.id.frameLayoutChart).setVisibility(View.VISIBLE); - - if(currency.getHistoryMinutes() != null) - { - view.findViewById(R.id.LineChartView).setVisibility(View.VISIBLE); - ((LineChart) view.findViewById(R.id.LineChartView)).invalidate(); - view.findViewById(R.id.errorTextView).setVisibility(View.GONE); - } - else - { - view.findViewById(R.id.LineChartView).setVisibility(View.GONE); - - view.findViewById(R.id.errorTextView).setVisibility(View.VISIBLE); - } - - } - - private List getAxisBorders(Currency currency) - { - List borders = new ArrayList<>(); - - List dataChartList = currency.getHistoryMinutes(); - - borders.add(0, currency.getHistoryMinutes().get(0).getOpen()); - borders.add(1, currency.getHistoryMinutes().get(0).getOpen()); - - for(int i = 0; i < dataChartList.size(); i++) - { - if(borders.get(0) > dataChartList.get(i).getOpen()) - { - borders.set(0, dataChartList.get(i).getOpen()); - } - - if(borders.get(1) < dataChartList.get(i).getOpen()) - { - borders.set(1, dataChartList.get(i).getOpen()); - } - } - - return borders; + expand(view.findViewById(R.id.collapsableLayout)); + view.findViewById(R.id.LineChartView).invalidate(); } private void updateColor(View view, Currency currency) @@ -215,6 +253,7 @@ public class HomeLayoutGenerator { List dataChartList = currency.getHistoryMinutes(); ArrayList values = new ArrayList<>(); + Log.d("coinfolio", "Generating data for " + currency.getSymbol()); for(int i = 0; i < dataChartList.size(); i+=10) { values.add(new Entry(i, (float) dataChartList.get(i).getOpen())); @@ -242,7 +281,9 @@ public class HomeLayoutGenerator { int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); + transColor = Color.argb(alpha, r, g, b); + return transColor ; } @@ -252,11 +293,11 @@ public class HomeLayoutGenerator { if(abs(number) > 1) { - str = String.format( Locale.UK, "%.2f", number); + str = String.format( Locale.UK, "%.2f", number).replaceAll("\\.?0*$", ""); } else { - str = String.format( Locale.UK, "%.4f", number); + str = String.format( Locale.UK, "%.4f", number).replaceAll("\\.?0*$", ""); } return str; diff --git a/app/src/main/java/com/nauk/coinfolio/PagerAdapter.java b/app/src/main/java/com/nauk/coinfolio/PagerAdapter.java new file mode 100644 index 0000000..d098777 --- /dev/null +++ b/app/src/main/java/com/nauk/coinfolio/PagerAdapter.java @@ -0,0 +1,49 @@ +package com.nauk.coinfolio; + +import android.app.Dialog; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentStatePagerAdapter; + +import com.nauk.coinfolio.Activities.HomeActivityFragments.MarketCapitalization; +import com.nauk.coinfolio.Activities.HomeActivityFragments.Summary; +import com.nauk.coinfolio.Activities.HomeActivityFragments.Watchlist; + +/** + * Created by Tiji on 13/04/2018. + */ + +public class PagerAdapter extends FragmentStatePagerAdapter { + + private int numOfTabs; + + public PagerAdapter(FragmentManager fm, int numOfTabs) + { + super(fm); + this.numOfTabs = numOfTabs; + } + + @Override + public Fragment getItem(int position) { + switch (position) + { + case 0: + Watchlist watchlist = new Watchlist(); + return watchlist; + case 1: + Summary summary = new Summary(); + return summary; + case 2: + MarketCapitalization marketCapitalization = new MarketCapitalization(); + return marketCapitalization; + default: + return null; + } + } + + @Override + public int getCount() { + return numOfTabs; + } +} diff --git a/app/src/main/res/color/home_color_bottombar.xml b/app/src/main/res/color/home_color_bottombar.xml index b8cae12..5fafac5 100644 --- a/app/src/main/res/color/home_color_bottombar.xml +++ b/app/src/main/res/color/home_color_bottombar.xml @@ -1,5 +1,5 @@ - + \ No newline at end of file diff --git a/app/src/main/res/drawable/button_dashed_background.xml b/app/src/main/res/drawable/button_dashed_background.xml new file mode 100644 index 0000000..9af5197 --- /dev/null +++ b/app/src/main/res/drawable/button_dashed_background.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/drop_shadow_cardview.xml b/app/src/main/res/drawable/drop_shadow_cardview.xml new file mode 100644 index 0000000..e5fbdff --- /dev/null +++ b/app/src/main/res/drawable/drop_shadow_cardview.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/expand_collapse_button_animation.xml b/app/src/main/res/drawable/expand_collapse_button_animation.xml new file mode 100644 index 0000000..45c0a19 --- /dev/null +++ b/app/src/main/res/drawable/expand_collapse_button_animation.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/gradient_background.xml b/app/src/main/res/drawable/gradient_background.xml index 2dd82b0..24074e2 100644 --- a/app/src/main/res/drawable/gradient_background.xml +++ b/app/src/main/res/drawable/gradient_background.xml @@ -1,9 +1,7 @@ + android:startColor="@color/colorPrimary" + android:endColor="@color/colorPrimaryDark" + android:angle="0"/> \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_view_list_white_24dp.xml b/app/src/main/res/drawable/ic_view_list_black_24dp.xml similarity index 90% rename from app/src/main/res/drawable/ic_view_list_white_24dp.xml rename to app/src/main/res/drawable/ic_view_list_black_24dp.xml index 222dc3b..78118c1 100644 --- a/app/src/main/res/drawable/ic_view_list_white_24dp.xml +++ b/app/src/main/res/drawable/ic_view_list_black_24dp.xml @@ -4,6 +4,6 @@ android:viewportWidth="24.0" android:viewportHeight="24.0"> diff --git a/app/src/main/res/drawable/linear_chart_gradient.xml b/app/src/main/res/drawable/linear_chart_gradient.xml new file mode 100644 index 0000000..5222848 --- /dev/null +++ b/app/src/main/res/drawable/linear_chart_gradient.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_add_currency.xml b/app/src/main/res/layout/activity_add_currency.xml index ee16a26..1da3f91 100644 --- a/app/src/main/res/layout/activity_add_currency.xml +++ b/app/src/main/res/layout/activity_add_currency.xml @@ -19,10 +19,30 @@ android:layout_gravity="center|top" android:background="@color/listBackground"/> - + android:layout_height="match_parent" + android:visibility="gone"> + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_currency_details.xml b/app/src/main/res/layout/activity_currency_details.xml index 7d3fa03..b476d46 100644 --- a/app/src/main/res/layout/activity_currency_details.xml +++ b/app/src/main/res/layout/activity_currency_details.xml @@ -18,11 +18,33 @@ android:layout_height="match_parent" android:orientation="vertical"> + + +