Skip to content

Commit

Permalink
Completed new cards values
Browse files Browse the repository at this point in the history
  • Loading branch information
Javinator9889 committed Mar 4, 2018
1 parent e97b566 commit 7acf264
Show file tree
Hide file tree
Showing 8 changed files with 215 additions and 24 deletions.
4 changes: 3 additions & 1 deletion app/src/main/AndroidManifest.xml
Expand Up @@ -35,7 +35,7 @@
<activity
android:name=".License"
android:configChanges="orientation"
android:screenOrientation="portrait"></activity>
android:screenOrientation="portrait"/>
<activity
android:name=".SpinnerActivity"
android:configChanges="orientation"
Expand All @@ -46,6 +46,8 @@
android:name=".BackgroundJobs.JobSchedulerService"
android:permission="android.permission.BIND_JOB_SERVICE"
tools:ignore="InnerclassSeparator" />
<service android:name=".BackgroundJobs.CacheJobSchedulerService"
android:permission="android.permission.BIND_JOB_SERVICE" />

</application>

Expand Down
@@ -0,0 +1,120 @@
package javinator9889.bitcoinpools.BackgroundJobs;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;

import javax.net.ssl.HttpsURLConnection;

import javinator9889.bitcoinpools.BitCoinApp;
import javinator9889.bitcoinpools.CacheManaging;
import javinator9889.bitcoinpools.Constants;
import javinator9889.bitcoinpools.JSONTools.JSONTools;
import javinator9889.bitcoinpools.NetTools.net;

/**
* Created by Javinator9889 on 04/03/2018.
*
* Controls cache
*/

public class CacheJobSchedulerService extends JobService {
private boolean jobWorking = false;
private boolean jobCancelled = false;

private Handler jobHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
System.out.println("Handling message");
if (!jobCancelled) {
try {
System.out.println("Updating cache");
updateCache();
System.out.println("Cache updated");
jobWorking = false;
jobFinished((JobParameters) msg.obj, false);
return false;
} catch (NullPointerException e) {
e.printStackTrace();
jobWorking = false;
jobFinished((JobParameters) msg.obj, true);
return false;
}
}
return false;
}
});

@Override
public boolean onStartJob(JobParameters params) {
jobWorking = true;
jobCancelled = false;
jobHandler.sendMessage(Message.obtain(jobHandler, 2, params));
Log.d("CACHEJOB", "Starting cache job");
return jobWorking;
}

@Override
public boolean onStopJob(JobParameters params) {
jobCancelled = true;
boolean needsReschedule = jobWorking;
jobHandler.removeMessages(2);
jobFinished(params, needsReschedule);
return needsReschedule;
}

private void updateCache() {
String date = new SimpleDateFormat("dd-MM-yyyy", Locale.US).format(Calendar.getInstance().getTime());
CacheManaging cache = CacheManaging.newInstance(BitCoinApp.getAppContext());
try {
cache.setupFile();
net request = new net();
request.execute(Constants.STATS_URL);
HashMap<String, Float> valuesObtained = JSONTools.convert2HashMap(request.get());
HashMap<String, String> newValuesToSave = new LinkedHashMap<>();
newValuesToSave.put("date", date);
for (String key : valuesObtained.keySet()) {
newValuesToSave.put(key, String.valueOf(valuesObtained.get(key)));
System.out.println(key + " | " + valuesObtained.get(key));
}
cache.writeCache(newValuesToSave);
} catch (Exception e) {
e.printStackTrace();
throw new NullPointerException("Impossible to obtain values");
}
}

/*private JSONObject getHTTPSRequest(String requestUrl) throws Exception {
Thread httpsRequestThread = new Thread(new Runnable() {
@Override
public void run() {
StringBuilder response = new StringBuilder();
URL urlObject = new URL(requestUrl);
HttpsURLConnection connection = (HttpsURLConnection) urlObject.openConnection();
connection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
bufferedReader.close();
return new JSONObject(response.toString());
}
})
}*/
}
35 changes: 34 additions & 1 deletion app/src/main/java/javinator9889/bitcoinpools/BitCoinApp.java
Expand Up @@ -15,6 +15,14 @@

import com.crashlytics.android.Crashlytics;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javinator9889.bitcoinpools.BackgroundJobs.CacheJobSchedulerService;
import javinator9889.bitcoinpools.BackgroundJobs.JobSchedulerService;

/**
Expand All @@ -41,11 +49,19 @@ public void onCreate() {
SHARED_PREFERENCES = getSharedPreferences(Constants.SHARED_PREFERENCES.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
initSharedPreferences();
startBackgroundJobs();
try {
System.out.println(CacheManaging.newInstance(this).readCache());
} catch (Exception e) {
System.out.println("No cache values found");
}
super.onCreate();
Log.d(Constants.LOG.BCTAG, Constants.LOG.CREATED_APP);
}

private static void startBackgroundJobs() {
JobScheduler globalJobScheduler = (JobScheduler) APPLICATION_CONTEXT.getSystemService(Context.JOB_SCHEDULER_SERVICE);
List<JobInfo> pendingJobs = globalJobScheduler != null ? globalJobScheduler.getAllPendingJobs() : new ArrayList<JobInfo>(0);

JobScheduler mJobScheduler = (JobScheduler) APPLICATION_CONTEXT.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(APPLICATION_CONTEXT.getPackageName(), JobSchedulerService.class.getName()));

Expand All @@ -58,6 +74,23 @@ private static void startBackgroundJobs() {
if (mJobScheduler.schedule(builder.build()) == JobScheduler.RESULT_FAILURE) {
Log.e(Constants.LOG.BCTAG, Constants.LOG.NO_INIT + "JobScheduler" + mJobScheduler.getAllPendingJobs().toString());
}

JobScheduler cacheJobScheduler = (JobScheduler) APPLICATION_CONTEXT.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder cacheBuilder = new JobInfo.Builder(2, new ComponentName(APPLICATION_CONTEXT.getPackageName(), CacheJobSchedulerService.class.getName()));


cacheBuilder.setPeriodic(TimeUnit.DAYS.toMillis(1));
cacheBuilder.setPersisted(Constants.PERSISTED);
cacheBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
cacheBuilder.setBackoffCriteria(Constants.BACKOFF_CRITERIA, JobInfo.BACKOFF_POLICY_LINEAR);

if ((pendingJobs.size() != 0) && !(pendingJobs.contains(cacheBuilder.build()))) {
assert cacheJobScheduler != null;
if (cacheJobScheduler.schedule(cacheBuilder.build()) == JobScheduler.RESULT_FAILURE) {
Log.e(Constants.LOG.BCTAG, Constants.LOG.NO_INIT + "JobScheduler" + mJobScheduler.getAllPendingJobs().toString());
}
} else
System.out.println("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE EL JOB YA EXISTE");
}

private void initSharedPreferences() {
Expand Down Expand Up @@ -87,7 +120,7 @@ public static boolean isOnline() {
ConnectivityManager connectionManager = (ConnectivityManager) getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
assert connectionManager != null;
NetworkInfo netInfo = connectionManager.getActiveNetworkInfo();
return ((netInfo != null) && netInfo.isConnectedOrConnecting());
return ((netInfo != null) && netInfo.isConnected());
}

public static String appVersion() {
Expand Down
Expand Up @@ -65,7 +65,7 @@ public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerV
switch (position) {
case 0:
float newPrice = Float.parseFloat(content.getBody().replaceAll("[^\\d.]", ""));
float oldPrice = Float.parseFloat(content.getOldData());
float oldPrice = Float.parseFloat(decimalFormat.format(Float.parseFloat(content.getOldData())));
System.out.println("Comparing: " + newPrice + " | " + oldPrice);
float pricePercentage = percentageCalculator(newPrice, oldPrice);
switch (Float.compare(pricePercentage, 0f)) {
Expand All @@ -86,7 +86,7 @@ public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerV
break;
case 1:
float newPower = Float.parseFloat(content.getBody().replaceAll("[^\\d.]", ""));
float oldPower = Float.parseFloat(content.getOldData());
float oldPower = Float.parseFloat(decimalFormat.format(Float.parseFloat(content.getOldData())));
System.out.println("Comparing: " + newPower + " | " + oldPower);
float powerPercentage = percentageCalculator(newPower, oldPower);
switch (Float.compare(powerPercentage, 0f)) {
Expand All @@ -107,9 +107,14 @@ public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerV
break;
case 2:
float newDifficulty = Float.parseFloat(content.getBody().replaceAll("[^\\d.]", ""));
float oldDifficulty = Float.parseFloat(content.getOldData());
float oldDifficulty = Float.parseFloat(decimalFormat.format(Float.parseFloat(content.getOldData())));
System.out.println("Comparing: " + newDifficulty + " | " + oldDifficulty);
float difficultyPercentage = - percentageCalculator(newDifficulty, oldDifficulty);
float difficultyPercentage;
float result = percentageCalculator(newDifficulty, oldDifficulty);
if (result == 0)
difficultyPercentage = 0;
else
difficultyPercentage = - result;
switch (Float.compare(difficultyPercentage, 0f)) {
case 0:
holder.oldData.setText("0%");
Expand All @@ -128,7 +133,7 @@ public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerV
break;
case 3:
float newBlock = Float.parseFloat(content.getBody().replaceAll("[^\\d.]", ""));
float oldBlock = Float.parseFloat(content.getOldData()) / 10;
float oldBlock = Float.parseFloat(decimalFormat.format(Float.parseFloat(content.getOldData()) / 10));
System.out.println("Comparing: " + newBlock + " | " + oldBlock);
float blockPercentage = percentageCalculator(newBlock, oldBlock);
switch (Float.compare(blockPercentage, 0f)) {
Expand All @@ -149,9 +154,14 @@ public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerV
break;
case 4:
float newMinutes = Float.parseFloat(content.getBody().replaceAll("[^\\d.]", ""));
float oldMinutes = Float.parseFloat(content.getOldData());
float oldMinutes = Float.parseFloat(decimalFormat.format(Float.parseFloat(content.getOldData())));
System.out.println("Comparing: " + newMinutes + " | " + oldMinutes);
float minutesPercentage = - percentageCalculator(newMinutes, oldMinutes);
float minutesPercentage;
float resultMinutes = percentageCalculator(newMinutes, oldMinutes);
if (resultMinutes == 0)
minutesPercentage = 0;
else
minutesPercentage = - resultMinutes;
switch (Float.compare(minutesPercentage, 0f)) {
case 0:
holder.oldData.setText("0%");
Expand All @@ -170,9 +180,14 @@ public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerV
break;
case 5:
float newBtcFees = Float.parseFloat(content.getBody().replaceAll("[^\\d.]", ""));
float oldBtcFees = Float.parseFloat(content.getOldData()) / 10000000;
float oldBtcFees = Float.parseFloat(decimalFormat.format(Float.parseFloat(content.getOldData()) / 10000000));
System.out.println("Comparing: " + newBtcFees + " | " + oldBtcFees);
float feePercentage = - percentageCalculator(newBtcFees, oldBtcFees);
float feePercentage;
float resultFees = percentageCalculator(newBtcFees, oldBtcFees);
if (resultFees == 0)
feePercentage = 0;
else
feePercentage = - resultFees;
switch (Float.compare(feePercentage, 0f)) {
case 0:
holder.oldData.setText("0%");
Expand All @@ -191,7 +206,7 @@ public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerV
break;
case 6:
float newTrans = Float.parseFloat(content.getBody().replaceAll("[^\\d.]", ""));
float oldTrans = Float.parseFloat(content.getOldData());
float oldTrans = Float.parseFloat(decimalFormat.format(Float.parseFloat(content.getOldData())));
System.out.println("Comparing: " + newTrans + " | " + oldTrans);
float transPercentage = percentageCalculator(newTrans, oldTrans);
switch (Float.compare(transPercentage, 0f)) {
Expand All @@ -212,7 +227,7 @@ public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerV
break;
case 7:
float newBenefit = Float.parseFloat(content.getBody().replaceAll("[^\\d.]", ""));
float oldBenefit = Float.parseFloat(content.getOldData()) / 100;
float oldBenefit = Float.parseFloat(decimalFormat.format(Float.parseFloat(content.getOldData()) / 100));
System.out.println("Comparing: " + newBenefit + " | " + oldBenefit);
float benefitPercentage = percentageCalculator(newBenefit, oldBenefit);
switch (Float.compare(benefitPercentage, 0f)) {
Expand Down Expand Up @@ -318,10 +333,14 @@ public boolean onLongClick(View v) {
* @return difference in percentage of values
*/
private float percentageCalculator(float newValue, float oldValue) {
float difference = newValue - oldValue;
float averageValues = (newValue + oldValue) / 2;
float diffDividedAverage = difference / averageValues;
return (diffDividedAverage * 100);
if (newValue == oldValue)
return 0;
else {
float difference = newValue - oldValue;
float averageValues = (newValue + oldValue) / 2;
float diffDividedAverage = difference / averageValues;
return (diffDividedAverage * 100);
}
}

@Override
Expand Down
Expand Up @@ -145,9 +145,22 @@ public void onClick(View v) {
DESTINATIONLINECHART.invalidate();

FRAGMENT_CONTEXT = createdView.getContext();
((TextView) createdView.findViewById(R.id.longPressInfo)).setText(R.string.longclick);

return createdView;
String longPressInfo;
try {
CacheManaging cache = CacheManaging.newInstance(createdView.getContext());
String date = cache.readCache().get("date");
if (date != null) {
longPressInfo = getString(R.string.longclick) + "\n" +
getString(R.string.comparationDate) + date;
} else
longPressInfo = getString(R.string.longclick);
((TextView) createdView.findViewById(R.id.longPressInfo)).setText(longPressInfo);
return createdView;
} catch (Exception e) {
longPressInfo = getString(R.string.longclick);
((TextView) createdView.findViewById(R.id.longPressInfo)).setText(longPressInfo);
return createdView;
}
}

private void setupValues() {
Expand Down Expand Up @@ -400,17 +413,18 @@ private HashMap<String, String> getCachedMap(Map<String, Float> newValues) {
}
try {
HashMap<String, String> oldCache = cache.readCache();
if (oldCache == null) {
HashMap<String, String> newCacheValues = new LinkedHashMap<>();
if (oldCache != null) {
/*HashMap<String, String> newCacheValues = new LinkedHashMap<>();
newCacheValues.put("date",
new SimpleDateFormat("dd-MM-yyyy").format(Calendar.getInstance().getTime()));
for (String key : newValues.keySet()) {
newCacheValues.put(key, newValues.get(key).toString());
//System.out.println(key + " | " + newValues.get(key).toString());
}
cache.writeCache(newCacheValues);
return null;
} else return oldCache;
return null;*/
return oldCache;
} else return null;
} catch (IOException | ClassNotFoundException e) {
System.out.println("Error while reading cache. Full trace: " + e.getMessage());
e.printStackTrace();
Expand Down
Expand Up @@ -44,6 +44,7 @@
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;

Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-es/strings.xml
Expand Up @@ -188,4 +188,5 @@
Si ocurre esto a menudo, por favor contacta a <a href="mailto:javialonso007@hotmail.es">esta dirección de correo</a>
]]>
</string>
<string name="comparationDate">Porcentajes comparados con la fecha: </string>
</resources>
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Expand Up @@ -217,4 +217,5 @@ SOFTWARE.<br />
If this happens to you usually, please contact me to <a href="mailto:javialonso007@hotmail.es">this email.</a>
]]>
</string>
<string name="comparationDate">Percentages compared with the date: </string>
</resources>

0 comments on commit 7acf264

Please sign in to comment.