how to access a variable from another class using interface in javafx? - java

I've two class autoCompleteTextfiled.java and BillingController.java.
AutocompleteTextFilled is a custom class. When I select a popup I'm getting result.
code is below:
private void populatePopup(List<String> searchResult) {
List<CustomMenuItem> menuItems = new LinkedList<>();
// If you'd like more entries, modify this line.
int maxEntries = 10;
int count = Math.min(searchResult.size(), maxEntries);
for (int i = 0; i < count; i++)
{
final String result = searchResult.get(i);
Label entryLabel = new Label(result);
CustomMenuItem item = new CustomMenuItem(entryLabel, true);
item.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent actionEvent) {
setText(result);
selectedTextFromMenu(result);
entriesPopup.hide();
}
});
menuItems.add(item);
}
entriesPopup.getItems().clear();
entriesPopup.getItems().addAll(menuItems);
}
private void selectedTextFromMenu(String result) {
AutoCompleteTextField autoCompleteTextField = new AutoCompleteTextField();
ItemSelectedListener mListener = new BillingController();
autoCompleteTextField.registerOnGeekEventListener(mListener);
autoCompleteTextField.selectItemListener(result);
}
public interface ItemSelectedListener
{
void getSelectedResult(String result);
}
public void registerOnGeekEventListener(ItemSelectedListener mListener)
{
this.itemSelectedListener = mListener;
}
public void selectItemListener(String result)
{
if (this.itemSelectedListener != null) {
itemSelectedListener.getSelectedResult(result);
}
}
but i trying to access a result from BillingControllerClass to AutoCompleteTextFiled returns null.
#Override
public void getSelectedResult(String result) {
System.out.println("The pin has been changed>"+billingItemDetails.size());//billingItemDetails retunes 0
for (int j= 0; j<billingItemDetails.size();j++)
{
ItemListRequestAndResponseModel.item_list item_list = billingItemDetails.get(j);
if (item_list.getItem_name().equals(result))
{
System.out.println("The pin has been changed---->"+result);
txtFieldId.setText(item_list.getShort_code());//Textfiledis retunes null
}
}
}
}
But billingItemDetails(Arraylist) retuns 0. But initially ArrayList have a data.
Please Help me.

Related

Cannot resolve constructor 'BaseBar(java.time.ZonedDateTime, java.lang.Double)'?

So I'm an amateur Android developer and have an issue.
My app uses this library (https://github.com/ta4j/ta4j) but after updating it to the latest stable release I'm having these errors!
Here's the error:
Cannot resolve constructor 'BaseBar(java.time.ZonedDateTime, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double)'
Here's the java code of my class:
public class RVCardAdapter extends RecyclerView.Adapter<RVCardAdapter.CryptoViewHolder> {
//globals
private List<SingleCryptoData> mCryptos;
private int mExpandedPosition;
//private int previousExpandedPosition = -1;
//default constructor
public RVCardAdapter() {
super();
mCryptos = new ArrayList<>();
}
//this refreshes the list
public void clear() {
mCryptos.clear();
notifyDataSetChanged();
}
//this adds the POJO passed into the crypto list
public void addData(SingleCryptoData crypto) {
mCryptos.add(crypto);
notifyDataSetChanged();
}
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#NonNull
#Override
public CryptoViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cryptocurrency_card, viewGroup, false);
return new CryptoViewHolder(v);
}
//onBindViewHolder binds the data to the layout elements for each crypto
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull CryptoViewHolder cryptoViewHolder, int i) {
//loading animation
FiftyShadesOf fiftyShades = new FiftyShadesOf(cryptoViewHolder.mCardViewDetails.getContext());
fiftyShades.on(cryptoViewHolder.mSignal, cryptoViewHolder.mCardViewDetails, cryptoViewHolder.mSignalStrength);
fiftyShades.fadein(true);
fiftyShades.start();
//set up output formatting
Currency usd = Currency.getInstance("USD");
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
currencyFormat.setCurrency(usd);
NumberFormat twoDecimalFormat = DecimalFormat.getInstance(Locale.US);
twoDecimalFormat.setRoundingMode(RoundingMode.FLOOR);
twoDecimalFormat.setMinimumFractionDigits(0);
twoDecimalFormat.setMaximumFractionDigits(2);
//TODO get display POJO data
cryptoViewHolder.mCryptoName.setText(mCryptos.get(i).getName());
cryptoViewHolder.mCryptoValue.setText(currencyFormat.format(mCryptos.get(i).getRaw().getPrice()));
cryptoViewHolder.mCryptoSymbol.setText(mCryptos.get(i).getRaw().getFromSymbol());
cryptoViewHolder.mCryptoDetailsVolume.setText(twoDecimalFormat.format(mCryptos.get(i).getRaw().getVolume24Hour()) + " " + mCryptos.get(i).getRaw().getFromSymbol());
cryptoViewHolder.mCryptoDetailsLow.setText(currencyFormat.format(mCryptos.get(i).getRaw().getLow24Hour()));
cryptoViewHolder.mCryptoDetailsHigh.setText(currencyFormat.format(mCryptos.get(i).getRaw().getHigh24Hour()));
cryptoViewHolder.mCryptoDetailsOpen.setText(currencyFormat.format(mCryptos.get(i).getRaw().getOpen24Hour()));
cryptoViewHolder.mCryptoDetailsPercentChange.setText(twoDecimalFormat.format(mCryptos.get(i).getRaw().getChangePercent24Hour()) + " %");
//color percent change depending on value
if (mCryptos.get(i).getRaw().getChangePercent24Hour() >= 0) {
cryptoViewHolder.mCryptoDetailsPercentChange.setTextColor(Color.parseColor("#52BE80"));
} else {
cryptoViewHolder.mCryptoDetailsPercentChange.setTextColor(Color.RED);
}
//handles expanding animation
//TODO stop first card from expanding
final boolean isExpanded = cryptoViewHolder.getAdapterPosition() == mExpandedPosition;
cryptoViewHolder.mCardViewDetails.setVisibility((isExpanded) ? View.VISIBLE : View.GONE);
cryptoViewHolder.itemView.setActivated(isExpanded);
// if (isExpanded)
// previousExpandedPosition = cryptoViewHolder.getAdapterPosition();
cryptoViewHolder.itemView.setOnClickListener(v -> {
mExpandedPosition = (isExpanded) ? -1 : cryptoViewHolder.getAdapterPosition();
//notifyItemChanged(previousExpandedPosition); //this used to close the
notifyItemChanged(cryptoViewHolder.getAdapterPosition());
});
//HISTODATA API
CryptoCompareAPI service = ServiceFactory.createRetrofitRx(CryptoCompareAPI.class, CryptoCompareAPI.BASE_URL);
if (android.os.Build.VERSION.SDK_INT >= 26){
//DAYS OF HISTORY TO GET FOR EACH CRYPTO
int historyDays = 14;
service.getHistoricalData(mCryptos.get(i).getRaw().getFromSymbol(), "USD", historyDays, "CryptoAnalysis")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<HistoData>() {
#Override
public void onSubscribe(Disposable d) {
}
//in histodata, the last element is the newest, and is yesterday. it will be at position [days]
#Override
public void onNext(HistoData histoData) {
TimeSeries series = new BaseTimeSeries("Strategy");
//TODO make usable on API 21+
ZonedDateTime endTime = ZonedDateTime.now().minusDays(historyDays);
//loop for each day of results in histodata
for (int i = 0; i < histoData.getData().size(); i++) {
//create a new base bar
Bar bar = new BaseBar(
endTime.plusDays(i),
histoData.getData().get(i).getOpen(),
histoData.getData().get(i).getHigh(),
histoData.getData().get(i).getLow(),
histoData.getData().get(i).getClose(),
histoData.getData().get(i).getVolumeTo()
);
series.addBar(bar);
}
//RUN ANALYSIS
Signal signal = TechnicalAnalysis.getSignal(series);
//INFLATE LAYOUT STUFF
cryptoViewHolder.mSignal.setText(signal.getSignalResult());
cryptoViewHolder.mRsiValue.setVisibility(View.VISIBLE);
cryptoViewHolder.mRsiValue.setText(String.valueOf((int) signal.getRsiStrength()));
cryptoViewHolder.mMomentumValue.setVisibility(View.VISIBLE);
cryptoViewHolder.mMomentumValue.setText(String.valueOf((int) signal.getMomentumStrength()));
cryptoViewHolder.mEmaValue.setVisibility(View.VISIBLE);
cryptoViewHolder.mEmaValue.setText(String.valueOf((int) signal.getEmaStrength()));
//cryptoViewHolder.mSignalStrength.setText("(" + String.valueOf(signal.getSignalStrength()) + ")");
}
#Override
public void onError(Throwable e) {
if (e.getMessage() != null)
Log.e("Histo API Error", e.getMessage());
}
#Override
public void onComplete() {
fiftyShades.stop();
}
});
} else {
int historyDays = 14;
service.getHistoricalData(mCryptos.get(i).getRaw().getFromSymbol(), "USD", historyDays, "CryptoAnalysis")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<HistoData>() {
#Override
public void onSubscribe(Disposable d) {
}
//in histodata, the last element is the newest, and is yesterday. it will be at position [days]
#Override
public void onNext(HistoData histoData) {
TimeSeries series = new BaseTimeSeries("Strategy");
//RUN ANALYSIS
Signal signal = TechnicalAnalysis.getSignal(series);
//INFLATE LAYOUT STUFF
cryptoViewHolder.mSignal.setText(signal.getSignalResult());
}
#Override
public void onError(Throwable e) {
if (e.getMessage() != null)
Log.e("Histo API Error", e.getMessage());
}
#Override
public void onComplete() {
fiftyShades.stop();
}
});
}
}
#Override
public int getItemCount() {
return mCryptos.size();
}
static class CryptoViewHolder extends RecyclerView.ViewHolder {
CardView mCardView;
TextView mCryptoDetailsOpen;
TextView mCryptoDetailsHigh;
TextView mCryptoDetailsLow;
TextView mCryptoDetailsVolume;
TextView mCryptoDetailsPercentChange;
TextView mCryptoName;
TextView mCryptoValue;
TextView mCryptoSymbol;
ConstraintLayout mCardViewDetails;
TextView mSignal;
TextView mRsiValueLabel;
TextView mRsiValue;
TextView mEmaValueLabel;
TextView mEmaValue;
TextView mMomentumValueLabel;
TextView mMomentumValue;
TextView mSignalStrength;
TextView mLowerApi;
CryptoViewHolder(View itemView) {
super(itemView);
mCryptoDetailsHigh = itemView.findViewById(R.id.crypto_details_high);
mCryptoDetailsOpen = itemView.findViewById(R.id.crypto_details_open);
mCryptoDetailsLow = itemView.findViewById(R.id.crypto_details_low);
mCryptoDetailsVolume = itemView.findViewById(R.id.crypto_details_volume);
mCryptoDetailsPercentChange = itemView.findViewById(R.id.crypto_details_percent_change);
mCardViewDetails = itemView.findViewById(R.id.card_view_details);
mCardView = itemView.findViewById(R.id.card_view);
mCryptoName = itemView.findViewById(R.id.crypto_name);
mCryptoValue = itemView.findViewById(R.id.crypto_value);
mCryptoSymbol = itemView.findViewById(R.id.crypto_symbol);
mSignal = itemView.findViewById(R.id.signal);
if (android.os.Build.VERSION.SDK_INT >= 26) {
mRsiValue = itemView.findViewById(R.id.rsi_indicator_value);
mRsiValue.setVisibility(View.VISIBLE);
mEmaValue = itemView.findViewById(R.id.ema_indicator_value);
mEmaValue.setVisibility(View.VISIBLE);
mMomentumValue = itemView.findViewById(R.id.momentum_indicator_value);
mMomentumValue.setVisibility(View.VISIBLE);
mRsiValueLabel = itemView.findViewById(R.id.rsi_value_label);
mRsiValueLabel.setVisibility(View.VISIBLE);
mEmaValueLabel = itemView.findViewById(R.id.ema_value_label);
mEmaValueLabel.setVisibility(View.VISIBLE);
mMomentumValueLabel = itemView.findViewById(R.id.momentum_value_label);
mMomentumValueLabel.setVisibility(View.VISIBLE);
mLowerApi = itemView.findViewById(R.id.lowApi);
mLowerApi.setVisibility(View.GONE);
}
//mSignalStrength = itemView.findViewById(R.id.signal_strength);
}
}
}
The lines where the error is shown:
for (int i = 0; i < histoData.getData().size(); i++) {
//create a new base bar
Bar bar = new BaseBar(
endTime.plusDays(i),
histoData.getData().get(i).getOpen(),
histoData.getData().get(i).getHigh(),
histoData.getData().get(i).getLow(),
histoData.getData().get(i).getClose(),
histoData.getData().get(i).getVolumeTo()
);
series.addBar(bar);
}
Class 2:
public class TechnicalAnalysis {
//variables and their values, these dictate how likely the signal is to move one way or another.
//Eventually, these will be tweaked and changed to be more accurate.
private static double rsiOversold = 25;
private static double rsiOverbought = 75;
private static double rsiWeight = 0.35;
private static double momentumWeight = 0.3;
private static double emaWeight = 0.35;
public static Signal getSignal(TimeSeries series) {
int numBars = series.getBarCount(); //this is the number of days in the series
//create indicators from series
//in all of these, the LAST member is the latest
ClosePriceIndicator closePrices = new ClosePriceIndicator(series);
RSIIndicator rsi = new RSIIndicator(closePrices, numBars);
EMAIndicator shortEma = new EMAIndicator(closePrices, numBars / 4);
EMAIndicator longEma = new EMAIndicator(closePrices, numBars);
//init strength vars
int rsiStrength = 0;
int momentumStrength = 0;
int emaStrength = 0;
//RSI 35%
for (int i = 0; i < numBars; i++) {
if (rsi.getValue(i).isGreaterThanOrEqual(rsiOverbought)) {
rsiStrength += i;
} else if (rsi.getValue(i).isLessThanOrEqual(rsiOversold)) {
rsiStrength -= i;
}
}
//EMA 45%
for (int i = 0; i < numBars; i++) {
if (shortEma.getValue(i).isGreaterThan(longEma.getValue(i).multipliedBy(1.04))) {
emaStrength += i;
} else {
emaStrength -= i;
}
}
//MOMENTUM 20%
for (int i = 0; i < numBars; i++) {
if (series.getBar(i).getClosePrice().isGreaterThan(series.getBar(i).getOpenPrice())) {
momentumStrength += i;
} else {
momentumStrength -= i;
}
}
//finally, return the completed
double rsiValue = rsiStrength * rsiWeight;
double emaValue = emaStrength * emaWeight;
double momentumValue = momentumStrength * momentumWeight;
return new Signal(rsiValue, emaValue, momentumValue);
}
}
Class 2 error:
isGreaterThanOrEqual
(org.ta4j.core.num.Num)
in Num cannot be applied to (double)
Class 2 error line:
for (int i = 0; i < numBars; i++) {
if (rsi.getValue(i).isGreaterThanOrEqual(rsiOverbought)) {
rsiStrength += i;
} else if (rsi.getValue(i).isLessThanOrEqual(rsiOversold)) {
rsiStrength -= i;
}
}
Can someone help, please?

Android ChangeOverTime method freezing at runtime (but not consistently)

So I am running into a problem with a function I made to slowly change the value of a monitored variable over time that is causing all the java logic to lock up. It doesn't seem to be producing an error or make the application crash so it must be getting stuck in the while loop or something but the logging isn't firing while it is locked so I am just very confused. If anyone can help me figure out how to diagnose what is causing the freezing that would be very much appreciated
EDIT: Turns out the problem was updating the UI from another thread, I manged to get it to crash and got the error and used a CountDownTimer instead of the background thread and now it is working fine. For those curious checkout my GitHub for this project.
Function in question:
public static void changeOverTime(final MonitoredVariable<Integer> tVar, final int tTo, final long tTime, final long tUpdateFreq) {
if (tTime < tUpdateFreq) { Log.e(TAG, "Time must be greater then update freq."); }
if (tVar == null) { Log.e(TAG, "Container cannot be null."); }
else {
final Thread tBackgroundThread = new Thread(new Runnable() {
#Override
public void run() {
float tSteps = tTime / tUpdateFreq; // 2000/100 = 20
float tInterval = (tTo - tVar.get()) / tSteps; // 67-175 = -108/20 = -5.4
float tVal = tVar.get(); //175
while (Math.round(tVal) != tTo) { //67(After 20 Times) != 67 -> FALSE
Debug.Log(TAG, "EQ: " + Math.round(tVal) + "?=" + tTo);
tVal += tInterval; // -5.4 * 20(Times) = -108+175 = 67
tryToSleep(tUpdateFreq); // 100ms * 20(Times) = 2000ms total
tVar.set(Math.round(tVal));
}
}
});
tBackgroundThread.start();
}
}
Supporting Function:
private static void tryToSleep(long tTime) {
try { sleep(tTime); }
catch (InterruptedException e) { e.printStackTrace(); }
}
Monitored Variable Class:
public class MonitoredVariable<Prototype> {
protected Prototype mData;
protected ChangeListener mListener;
public MonitoredVariable(Prototype tData) {
this(tData, null);
}
public MonitoredVariable(Prototype tData, ChangeListener tListener) {
if (tListener != null) setListener(tListener);
mData = tData;
}
public Prototype get() {
return mData;
}
public void set(Prototype tData) {
if (mData != tData) {
mData = tData;
notifyChange();
}
}
public void setListener(ChangeListener tListener) {
mListener = tListener;
}
public ChangeListener getListener() {
return mListener;
}
public void notifyChange() {
if (mListener != null) mListener.onChange();
}
public interface ChangeListener {
void onChange();
}
}
Usage:
public static void init() {
MonitoredVariable.ChangeListener tUpdateBackground = new MonitoredVariable.ChangeListener() {
#Override
public void onChange() { updateBackgroud();
}
};
mTop = new MonitoredVariable[]{
new MonitoredVariable<>(0, tUpdateBackground),
new MonitoredVariable<>(0, tUpdateBackground),
new MonitoredVariable<>(0, tUpdateBackground)
};
mBottom = new MonitoredVariable[]{
new MonitoredVariable<>(0, tUpdateBackground),
new MonitoredVariable<>(0, tUpdateBackground),
new MonitoredVariable<>(0, tUpdateBackground)
};
mAnimationLoop = new Handler();
mAnimation = new Runnable() {
#Override
public void run() {
Debug.Log(TAG, "RUNNING ANIMATION");
final Random RNG = new Random();
for (MonitoredVariable<Integer>[] tBackground: new MonitoredVariable[][] {mTop, mBottom}) {
for (MonitoredVariable<Integer> tColor : tBackground) {
int tRandomColor = RNG.nextInt(255);
//tColor.set(tRandomColor);
Shift.changeOverTime(tColor, tRandomColor, 2000, 100);
}
}
if(mAnimate.get()) {
mAnimationLoop.postDelayed(mAnimation, 10000);
}
}
};
mAnimate = new MonitoredVariable<>(false, new MonitoredVariable.ChangeListener() {
#Override
public void onChange() {
if (mAnimate.get()) mAnimationLoop.postDelayed(mAnimation, 0);
else mAnimationLoop.removeCallbacks(mAnimation);
}
});
}
public static void setBackground(final Activity tActivity){
final View tActivityBackground = tActivity.findViewById(R.id.background);
mListener = new ChangeListener() {
#Override
public void onChange() { tActivityBackground.setBackground(mBackground); }
};
notifyChange();
}
private static void updateBackgroud() {
int tTop = Color.argb(255, mTop[0].get(), mTop[1].get(), mTop[2].get());
int tBottom = Color.argb(255, mBottom[0].get(), mBottom[1].get(), mBottom[2].get());
int[] colors = {tTop, tBottom};
mBackground = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
mBackground.setCornerRadius(0f);
notifyChange();
}
public static void animateBackground(boolean tAnimate) {
mAnimate.set(tAnimate);
}
public static void notifyChange() {
if (mListener != null) mListener.onChange();
}
public interface ChangeListener {
void onChange();
}

Problems with Out of memory error

I get out of memory error if the function doesWifiExist is false if it is true every thing works normally.Can someone tell me what m i doing wrong
The idea is to get a list of wifi networks nearby and check if the inserted network exists in the list.
Here is the wifi network scanning code and the the function that checks if the wifi network exists.
MainActivity:
private WiFiConnection _wifiConnection = null;
static final int MY_PERMISSIONS_REQUEST = 1042;
private static final String PERMISSIONS_TAG = "PERMISSION";
...
#Override
protected void onStart() {
super.onStart();
_wifiConnection = new WiFiConnection(this);
startScan();
}
#Override
protected void onStop() {
super.onStop();
_wifiConnection.stopScan();
unregisterReceiver(_wifiScanReceiver);
}
void startScan() {
checkPermission(this);
registerReceiver(_wifiScanReceiver,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Thread t = new Thread(_wifiConnection.getWifiScanner());
t.start();
}
private final BroadcastReceiver _wifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
if (_wifiConnection != null && _wifiConnection.isWifiEnabled()) {
_wifiConnection.updateScanData();
}
}
}
};
public static boolean checkPermission(Activity activity) {
boolean permission = true;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<String> requiringList = new ArrayList<>();
permission = activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
Log.d(PERMISSIONS_TAG, "ACCESS_COARSE_LOCATION: " + permission);
if (!permission) {
requiringList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (requiringList.size() > 0) {
String[] stringArray = requiringList.toArray(new String[0]);
activity.requestPermissions(stringArray, MY_PERMISSIONS_REQUEST);
}
}
return permission;
}
private boolean doesWifiExist(String s){
String[] array = s.split(" ");
String ssid = array[0];
boolean flag = false;
//Check if wifi exists in the area
for(int i = 0 ; i < _wifiConnection.getListSSIDs().size(); i++){
if(_wifiConnection.getListSSIDs().get(i).equals(ssid)){
flag = true;
break;
}
}
return flag;
}
WiFiConnection class:
public class WiFiConnection
{
private static final int SCAN_INTERVAL = 5000;
final private List<String> _listSSIDs = new ArrayList<>();
private WifiManager _wifiManager;
private final WiFiScanner _startScan = new WiFiScanner();
private List<ScanResult> scanResults;
WiFiConnection(Activity activity) {
_wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}
//Puts wifi networks in a list
public List<String> getListSSIDs() {
for(int i = 0; i < scanResults.size(); i++)
{
_listSSIDs.add(scanResults.get(i).SSID);
}
return _listSSIDs;
}
WiFiScanner getWifiScanner() { return _startScan; }
void stopScan() { _startScan.stop(); }
boolean isWifiEnabled() { return _wifiManager.isWifiEnabled(); }
//Gets the wifi networks
void updateScanData() {
if ((_wifiManager != null && _wifiManager.isWifiEnabled())) {
scanResults = _wifiManager.getScanResults();
}
}
//Scans at an interval
private class WiFiScanner implements Runnable
{
private boolean _stop = false;
public void stop() {_stop = true;}
#Override
public void run() {
while (!_stop) {
_listSSIDs.clear();
_wifiManager.startScan();
try {
Thread.sleep(SCAN_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
The code where doesWifiExist is used.
//Check if wifi exists in the area
if(doesWifiExist(barcode.displayValue)){
//Connects to wifi
WifiConnect(barcode.displayValue);
//Saves item in db
insertItem();
if(networkSecurity.equals("None")){
networkPass = empty;
}
//Adds item to recyclerview
historyItems.add(0, new HistoryItem(wifiName + " " + networkSSID, wifiPass + " " + networkPass));
adapter.notifyItemInserted(0);
} else
Snackbar.make(findViewById(R.id.main_activity), R.string.snackInvalidQrCode, Snackbar.LENGTH_SHORT).show();
This method is called many times, and it everytime adds all scanResults at the end of field _listSSIDS.
public List<String> getListSSIDs() {
for(int i = 0; i < scanResults.size(); i++)
{
_listSSIDs.add(scanResults.get(i).SSID);
}
return _listSSIDs;
}
Use a local variable with a new List or better Set there.
Instead replace
for(int i = 0 ; i < _wifiConnection.getListSSIDs().size(); i++){
if(_wifiConnection.getListSSIDs().get(i).equals(ssid)){
flag = true;
break;
}
}
with
flag = _wifiConnection.hasSSID(String ssid);
public boolean hasSSID(String ssid) {
for (int i = 0; i < scanResults.size(); i++) {
if (ssid.equals(scanResults.get(i).SSID)) {
return true;
}
}
return false;
}

Excessive Internal memory consumed while using two different asyncTask on same RealmObject Android

1.. If i run two methods create2YearsDatabse(); at one anpplication run session
then kill the program completely and then in the next run run the method :
updateAutoGeneratedCalendar();
then the result is as expected it takes about
2-3 MB of memory
2. But if i run create2YearsDatabse() and onSuccess() callback of async Task it is using then the memory it takes in internal memory suddenly goes to more than 400 MB.
// The methods are managed in this way:
public void create2YearsDatabase() {
new BGAsyncTasks(context, new ThreadCallBack() {
#Override
public void onSuccess() {
final SettingAndStatusDTO settingDto = realm.where(SettingAndStatusDTO.class).findFirst();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
//because two years has more or equal to 730 days
if (realm.where(CalendarDto.class).findAll().size() >= 730) {
settingDto.setIs2YearsFullDBCreated(true);
context.getSharedPreferences(context.getString(R.string.shared_pref_name),Context.MODE_PRIVATE).edit().putBoolean(SplashActivity.FIRST_TIME_RUN,false).apply();
}
}
});
SplashActivity.freshRun = false;
startDashBoard();
}
#Override
public void onFailure() {
}
}, BGAsyncTasks.CREATE_INITIALIZE_2_YEARS_CALENDAR).execute();
}
public void updateAutoGeneratedCalendar() {
new BGAsyncTasks(context, new ThreadCallBack() {
#Override
public void onSuccess() {
Log.i("datatest", "full data size" + realm.where(CalendarDto.class).findAll().size());
final SettingAndStatusDTO settingDto = realm.where(SettingAndStatusDTO.class).findFirst();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
if (realm.where(CalendarDto.class).findAll().size() >= 32000)
settingDto.setIs90YearsDBCreated(true);
}
});
}
#Override
public void onFailure() {
}
}, BGAsyncTasks.CREATE_AUTO_GENERATE_CALENDAR).execute();
}
And My Async Task Looks like this :
public class BGAsyncTasks extends AsyncTask<Void, Void, Void> {
// Intention variables
public static final int CREATE_INITIALIZE_2_YEARS_CALENDAR = 0;
public static final int CREATE_AUTO_GENERATE_CALENDAR = 1;
// Message from the Activity/Fragment.
ThreadCallBack callBack;
Context context;
int intention;
IParseData parser ;
//Constructor for bg processes.
public BGAsyncTasks(Context c, ThreadCallBack callBack, int DATA_TYPE_FROM_RES) {
this.callBack = callBack;
this.context = c;
this.intention = DATA_TYPE_FROM_RES;
this.parser = new ParseData(context);
}
#Override
protected Void doInBackground(Void... params) {
switch (intention) {
case CREATE_AUTO_GENERATE_CALENDAR: {
final Realm asyncRealm = Realm.getDefaultInstance();
for (int i = 2000; i <= 2090; i++) {
if (i < 2072 || i > 2073) {
for (int j = 0; j < 12; j++) {
parser.setOnemonthData(i, j);
}
}
Log.i("datatest", "year:" + i);
}
}
case CREATE_INITIALIZE_2_YEARS_CALENDAR: {
String thisMonthString;
for (int i = 2072; i <=2073; i++) {
for (int j = 0; j < 12; j++) {
thisMonthString = getStringByMonth(i, j);// returns the json string
parser.parseOneMonthData(fixFormatting(thisMonthString));
}
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
callBack.onSuccess();
}
}
And my Parse and saving to Database methods look like this:
public class ParseData implements IParseData {
Context context;
Realm realm;
CalendarDto mCalendarDto;
public ParseData(Context c) {
context = c;
mCalendarDto = new CalendarDto();
}
public void parseOneMonthData(String monthData) {
//parse json data of one month and return as DTO of size equal
//to no of days in that month
try {
JSONArray oneMonthJsonData = new JSONArray(monthData);
int length = oneMonthJsonData.length();
for (int i = 0; i < length; i++) {
saveOneDayData(oneMonthJsonData.optJSONObject(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void saveOneDayData(final JSONObject singleTouple) {
realm = Realm.getDefaultInstance();
// parsing the data of one day so that it can be used everywhere.
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
mCalendarDto.setDayInfo(singleTouple.optString(DataItems.DAY_INFO));
mCalendarDto.setMahina(singleTouple.optString(DataItems.MAHINA));
realm.copyToRealmOrUpdate(mCalendarDto);
}
});
}
// saving data by month and year
public void setOnemonthData(final int yr, final int mnt) {
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
mCalendarDto.setMonthEnId(currentEngMonth);
mCalendarDto.setMonthNpId(month);
realm.copyToRealmOrUpdate(mCalendarDto);
}
}
});
}
}
Here is my Calendar Realm Object :
public class CalendarDto extends RealmObject {
public CalendarDto() {
}
#PrimaryKey
private int primaryDayId
private String sakey;
private String raja;
private String mantri;
private String nepalSambat;
// more variables and ...........
//// autogenerated getters and settetrs
////////
}
#Override
protected Void doInBackground(Void... params) {
switch (intention) {
case CREATE_AUTO_GENERATE_CALENDAR: {
final Realm asyncRealm = Realm.getDefaultInstance(); // <--- this line
and
public void saveOneDayData(final JSONObject singleTouple) {
realm = Realm.getDefaultInstance(); // <--- this line
and
public void setOnemonthData(final int yr, final int mnt) {
realm = Realm.getDefaultInstance(); // <--- this line
On background threads, you should close the Realm instance after using them in a finally block.
In this case, you are opening a new Realm instance for every single day twice, and you're not closing any of them.
On a background thread, best practice is to open only one Realm instance, and then close it after the execution is complete.
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
//do things
} finally {
if(realm != null) {
realm.close();
}
}

Setting one element in array changes others

I checked other similar tags with almost same title. Those answers were not relevant
When setting element at one position of array, both the elements have the same value.
public class LogActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
startStopButton = (Button) findViewById(R.id.btnStart);
loggingStatusText = (TextView) findViewById(R.id.logStatusText);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
sensorValues=new ArrayList<float[]>(sensorList.size());
sensorValsArray=new float[sensorList.size()][];
sensorNameList = new ArrayList<String>();
selectedSensorNames = new ArrayList<String>();
for (Sensor itemSensor : sensorList)
{
if (itemSensor != null)
{
sensorNameList.add(itemSensor.getName());
}
}
showSensorList();
}
private void showSensorList()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setMultiChoiceItems((CharSequence[]) sensorNameList
.toArray(new CharSequence[sensorNameList.size()]),
new boolean[sensorNameList.size()],
new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked)
{
if (isChecked)
{
if (!selectedSensorNames.contains(sensorNameList
.get(whichButton)))
selectedSensorNames.add(sensorNameList
.get(whichButton));
} else
{
if (selectedSensorNames.contains(sensorNameList
.get(whichButton)))
{
selectedSensorNames.remove(sensorNameList
.get(whichButton));
}
}
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
listeners=new SensorEventListener[selectedSensorNames.size()];
float[] tempVals = new float[] { 0, 0, 0 };
for (int i = 0; i < selectedSensorNames.size(); i++)
{
sensorValsArray[i]=tempVals;
}
showRateList();
}
});
builder.setCancelable(false);
builder.create().show();
}
void registerSensors()
{
for (Sensor sensor : sensorList)
{
if (selectedSensorNames.contains(sensor.getName()))
{
mSensorManager.registerListener(listeners[selectedSensorNames.indexOf(sensor.getName())], sensor, selectedDelay);
}
}
}
class SchedulerTask extends TimerTask
{
/*
* The task to run should be specified in the implementation of the
* run() method
*/
public void run()
{
logSensorData();
}
}
private void createLog(String fileName)
{
File root = getExternalFilesDir(null);// Get the Android external
// storage directory
Date cDate = new Date();
String bstLogFileName = fileName;
bstLogFile = new File(root, bstLogFileName);// Construct a new file for
// using the specified
// directory and name
FileWriter bstLogWriter;
logScheduler = new Timer();// Create a new timer for updating values
// from content provider
logScheduler.schedule(new SchedulerTask(),
LOG_TASK_DELAY_IN_MILLISECONDS,
getLogPeriodInMilliSeconds(selectedDelay));
}
public void logSensorData()
{
Date stampDate = new Date();
String LogPack ="\r\n";
for (int count=0;count<selectedSensorNames.size();count++)
{
LogPack += sensorValsArray[count][0] + "," + sensorValsArray[count][1] + "," + sensorValsArray[count][2] + ",";
}
LogPack += "\r\n";
try
{
F_StreamWriter.write(LogPack);
F_StreamWriter.flush();
}
catch (IOException e)
{
}
catch (NullPointerException e)
{
}
}
public void startStopLog(View v)
{
if (startStopButton.getText().equals("Start"))
{
createSensorListeners();
registerSensors();
showFilenameDialog();
} else if (startStopButton.getText().equals("Stop"))
{
stopLog();
}
}
public void startLog(String fileName)
{
createLog(fileName);
}
public void stopLog()
{
logScheduler.cancel();
logScheduler.purge();
for(int i=0;i<listeners.length;i++)
mSensorManager.unregisterListener(listeners[i]);
}
private void showFilenameDialog()
{
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_text_input_dialog);
dialog.setCancelable(true);
final EditText fileNameInput = (EditText) dialog
.findViewById(R.id.fileNameText);
Button button = (Button) dialog.findViewById(R.id.okButton);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startLog(nameInput);
dialog.dismiss();
}
});
dialog.show();
}
private void createSensorListeners()
{
listeners=new SensorEventListener[selectedSensorNames.size()];
for (int i = 0; i < selectedSensorNames.size(); i++)
{
listeners[i]=new SensorEventListener()
{
#Override
public void onSensorChanged(SensorEvent event)
{
sensorValsArray[selectedSensorNames.indexOf(event.sensor.getName())]=event.values;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
};
}
}
}
When index is 0, when set command is executed, it also changes the the value at index position '1'.
Can anyone help me with this?
Thanks in Advance,
Dheepak
When index is 0, when set command is executed, it also changes the the value at index position '1'. Can anyone help me with this?
You are definitely mistaken as to what it is causing this. Setting the value at one position of an ArrayList WILL NOT mysteriously cause the value at another position to change. It simply does not work like that.
The effect you are observing will be due to something else:
maybe the value of index is not what you expect
maybe the value of event.values is not what you expect. (Maybe you've made a mistake in the way that you create the Event objects, and they are all sharing one float[] object.)
maybe the value at position 1 was already that value
maybe you've got multiple threads updating the sensorValues list.

Categories

Resources