Рow to use if statements between two intent activities? I have two different activities collecting data from external sensors. I would like to control some GPIO pins of Activity1 based on the sensor values of Activity2.
Activity 1
public class RealTimeData extends AppCompatActivity {
private static final String TAG = "sensor_data";
private static final String FRAGMENT_DIALOG = "dialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_real_time_data);
Resources res = getResources();
GetAllResources();
OpenSerialPort();
}
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
private void GetAllResources() {
pressure1 = (TextView) findViewById(R.id.pressure);
temp1 = (TextView) findViewById(R.id.temperature);
co2ppm1 = (TextView) findViewById(R.id.co2);
humidity1 = (TextView) findViewById(R.id.humidity);
pressure1data = (TextView) findViewById(R.id.pressureData);
temp1data = (TextView) findViewById(R.id.temperatureData);
co2ppm1data = (TextView) findViewById(R.id.co2Data);
humidity1data = (TextView) findViewById(R.id.humidityData);
}
private sensorDataApplication sensordata = new sensorDataApplication();
private UartApplication[] mSerialport = {null, null};
private void SetValues()
{
TextView tv =(TextView) findViewById(R.id.pressureData);
tv.setText(String.valueOf(sensordata.get_pressure_value(0)));
tv =(TextView) findViewById(R.id.temperatureData);
tv.setText(String.valueOf(sensordata.get_temperature_value(0)));
tv =(TextView) findViewById(R.id.co2Data);
tv.setText(String.valueOf(sensordata.get_co2_value(0)));
tv =(TextView) findViewById(R.id.humidityData);
tv.setText(String.valueOf(sensordata.get_humidity_value(0)));
}
private void OpenSerialPort() {
new sensorDataApplication();
try {
int i =0;
for(String devicePath : Configs.uartdevicePath) {
mSerialport[i] = new UartApplication(new File(devicePath), mReaderCallback);
i++;
}
} catch (SecurityException e) {
ErrorMessage.newInstance(getString(R.string.error_serial))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (IOException e) {
ErrorMessage.newInstance(getString(R.string.error_unknown))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (InvalidParameterException e) {
ErrorMessage.newInstance(getString(R.string.error_uart_config))
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
}
private final UartApplication.ReaderCallback mReaderCallback=
new UartApplication.ReaderCallback() {
#Override
public void onDataReceived(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
public void run() {
if (pressure1 != null) {
String received_str = new String(buffer, 0, size);
//uartRx.append(received_str);
sensordata.parse_and_update_sensordata(received_str);
SetValues();
Log.e(TAG,"received packet "+received_str);
}
}
});
}
};
TextWatcher mUartTxCallback = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(max(start,before) < s.length()) {
String changedStr = s.toString().substring(max(start, before), s.length());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable var1) {
}
};
private void CloseSerialPort(int idx)
{
mSerialport[idx].closeSerialPort();
}
private void WriteSerialPort(String writeString, int idx)
{
mSerialport[idx].writeData(writeString);
}
private static byte[] hexStringToByteArray(String s) {
int len = s.length();
s.toUpperCase();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
private static String toHexString(byte[] ba) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < ba.length; i++)
str.append(String.format("%02x", ba[i]));
return str.toString().toUpperCase();
}
private TextView pressure1;
private TextView temp1;
private TextView co2ppm1;
private TextView humidity1;
private TextView pressure1data;
private TextView temp1data;
private TextView co2ppm1data;
private TextView humidity1data;
}
Activity 2
public class ManualControl extends AppCompatActivity {
static {
System.loadLibrary("native-lib");
}
List<gpioApplication> mGPIO = new ArrayList<>();
private static final String FRAGMENT_DIALOG = "dialog";
private int[] mGPIOList = null;
private CheckBox[] cbGPIO;
private final gpioApplication.InterruptCallback mGPIOCallback =
new gpioApplication.InterruptCallback() {
#Override
public void onDataReceived(final int GPIOnum, final int value) {
runOnUiThread(new Runnable() {
public void run() {
//Do Nothing
CheckBox cbnGPIO = GetCheckBoxGpio(GPIOnum);
cbnGPIO.setOnCheckedChangeListener(null);
if (cbnGPIO != null)
cbnGPIO.setChecked(value > 0 ? true : false);
cbnGPIO.setOnCheckedChangeListener(mGPIOCheckBoxCallback);
}
});
}
};
private final CompoundButton.OnCheckedChangeListener mGPIOCheckBoxCallback =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
int gpioID = Integer.parseInt(buttonView.getHint().toString());
int GPIOValue = buttonView.isChecked() == true ? 1 : 0;
if (gpioID < mGPIOList.length) {
gpioApplication gpio = mGPIO.get(gpioID);
gpio.GPIOWrite(GPIOValue);
}
}
};
private CheckBox GetCheckBoxGpio(int GPIOnum) {
if (GPIOnum < mGPIOList.length)
return cbGPIO[GPIOnum];
return null;
}
private void GetAllResources() {
cbGPIO = new CheckBox[20];
cbGPIO[9] = (CheckBox) findViewById(R.id.checkBox_GPIO92);
cbGPIO[0] = (CheckBox) findViewById(R.id.checkBox_GPIO16);
cbGPIO[1] = (CheckBox) findViewById(R.id.checkBox_GPIO17);
cbGPIO[6] = (CheckBox) findViewById(R.id.checkBox_GPIO69);
cbGPIO[2] = (CheckBox) findViewById(R.id.checkBox_GPIO23);
for (int i = 0; i < mGPIOList.length; i++) {
if (i == 9 || i == 0 || i == 1 || i == 6 || i == 2) {
GetCheckBoxGpio(i).setText(Integer.toString(mGPIOList[i]));
GetCheckBoxGpio(i).setEnabled(true);
}
}
}
private final CompoundButton.OnCheckedChangeListener mIntCheckBoxCallback =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
int gpioID = Integer.parseInt(buttonView.getHint().toString());
boolean IntValue = buttonView.isChecked();
if (gpioID < mGPIOList.length) {
/*Use IntValue Re-configure GPIO Interrupt Here*/
mGPIO.get(gpioID).ConfigureInterrupt(IntValue);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_control);
try {
mGPIOList = gpio_list;
GetAllResources();
for (int i = 0; i < mGPIOList.length; i++) {
GPIOOpen(i);
}
ConfigureCallbacks();
GetAllResources();
} catch (Exception e) {
ErrorMessage.newInstance(e.getLocalizedMessage())
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
}
private void ConfigureCallbacks() {
ConfigureGPIOCheckboxCallback();
}
private void ConfigureGPIOCheckboxCallback() {
for (int i = 0; i < mGPIOList.length; i++) {
if (i == 9 || i == 0 || i == 1 || i == 6 || i == 2) {
cbGPIO[i].setOnCheckedChangeListener(mGPIOCheckBoxCallback);
}
}
}
private void GPIOOpen(int GPIOnum) {
if (GPIOnum == 9 || GPIOnum == 0 || GPIOnum == 1 || GPIOnum == 6 || GPIOnum == 2) {
mGPIO.add(new gpioApplication());
try {
mGPIO.get(GPIOnum).GPIOOpen(GPIOnum, mGPIOList[GPIOnum], mGPIOCallback);
} catch (SecurityException e) {
ErrorMessage.newInstance(getString(R.string.error_gpio))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (IOException e) {
ErrorMessage.newInstance(getString(R.string.error_unknown))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (InvalidParameterException e) {
ErrorMessage.newInstance(getString(R.string.error_gpio_config))
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
} else {
mGPIO.add(null);
}
}
}
In the above codes the GPIO pins must be controlled by the co2ppm1 sensor values (If the co2ppm1 sensor value is above 2000, it must turn ON GPIO 9 pin).
Related
I make whole video player app but stuck at mediacontroller. I want to show my own mediacontroller with different button, not the default one. It's 4rth day, i'm just trying to make my own mediacontroller but didn't succeed.
I succeed by doing it with surfaceview but i want to use it with videoview.
I try the following code.
public class MyMediaController extends MediaController {
private static final String TAG = "VideoControllerView";
MediaController.MediaPlayerControl mPlayer;
private Context mContext;
private View mAnchor;
private View mRoot;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mSubtitleButton;
private ImageButton mResizeButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private final AccessibilityManager mAccessibilityManager;
public MyMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = null;
mContext = context;
mUseFastForward = true;
mFromXml = true;
mAccessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
public MyMediaController(Context context, boolean useFastForward) {
super(context, useFastForward);
mUseFastForward = useFastForward;
mAccessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
public MyMediaController(Context context) {
this(context, true);
mContext = context;
}
#Override
public void setMediaPlayer(MediaController.MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
}
#Override
public void setAnchorView(View view) {
mAnchor = view;
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
removeAllViews();
View v = makeControllerView();
addView(v, frameParams);
}
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.media_controller_layout, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View mRoot) {
mPauseButton = mRoot.findViewById(R.id.pause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mResizeButton = mRoot.findViewById(R.id.resize);
if (mResizeButton != null) {
mResizeButton.requestFocus();
mResizeButton.setOnClickListener(mResizeListener);
}
mSubtitleButton = mRoot.findViewById(R.id.subtitle);
if (mSubtitleButton != null)
{
mSubtitleButton.requestFocus();
mSubtitleButton.setOnClickListener(mSubtitleListener);
}
mNextButton = mRoot.findViewById(R.id.next);
if (mNextButton != null ) {
mNextButton.requestFocus();
mNextButton.setOnClickListener(mNextListener);
}
mPrevButton = mRoot.findViewById(R.id.prev);
if (mPrevButton != null ) {
mPrevButton.requestFocus();
mPrevButton.setOnClickListener(mPrevListener);
}
mProgress = mRoot.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = mRoot.findViewById(R.id.time);
mCurrentTime = mRoot.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
}
public final View.OnClickListener mPauseListener = new OnClickListener() {
#Override
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private void doPauseResume() {
if (mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private void updatePausePlay() {
if (mRoot == null || mPauseButton == null)
return;
if (mPlayer.isPlaying())
mPauseButton.setImageResource(R.drawable.ic_pause);
else
mPauseButton.setImageResource(R.drawable.ic_play);
}
public final View.OnClickListener mResizeListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"Resize is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mNextListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"NextBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mPrevListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"PreviousBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mSubtitleListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"subtitleBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
private final SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
mDragging = true;
// By removing these pending progress messages we make sure
// that a) we won't update the progress while the user adjusts
// the seekbar and b) once the user is done dragging the thumb
// we will post one of these messages to the queue again and
// this ensures that there will be exactly one message queued up.
removeCallbacks(mShowProgress);
}
#Override
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (!fromuser) {
// We're not interested in programmatically generated changes to
// the progress bar's position.
return;
}
long duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo( (int) newposition);
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime( (int) newposition));
}
#Override
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
// Ensure that progress is properly updated in the future,
// the call to show() does not guarantee this because it is a
// no-op if we are already showing.
post(mShowProgress);
}
};
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress( (int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private final Runnable mShowProgress = new Runnable() {
#Override
public void run() {
int pos = setProgress();
if (!mDragging && mShowing && mPlayer.isPlaying()) {
postDelayed(mShowProgress, 1000 - (pos % 1000));
}
}
};
#Override
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
setProgress();
if (mPauseButton != null) {
mPauseButton.requestFocus();
}
FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
addView(this, tlp);
mShowing = true;
}
updatePausePlay();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
post(mShowProgress);
if (timeout != 0 && !mAccessibilityManager.isTouchExplorationEnabled()) {
removeCallbacks(mFadeOut);
postDelayed(mFadeOut, timeout);
}
}
#Override
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
#Override
public void hide() {
if (mAnchor == null)
return;
if (mShowing) {
try {
removeCallbacks(mShowProgress);
removeView(this);
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
mShowing = false;
}
}
private final Runnable mFadeOut = new Runnable() {
#Override
public void run() {
hide();
}
};
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
show(0);
break;
case MotionEvent.ACTION_UP:
show(sDefaultTimeout);
break;
case MotionEvent.ACTION_CANCEL:
hide();
break;
default:
break;
}
return true;
}
}
Plz someone suggest my the right way to do it. I realy need help.
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?
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;
}
public class PerformanceDashboard extends MotherActivity {
String dashboardData;
int SELECTED_PAGE, SEARCH_TYPE, TRAY_TYPE;
List<String[]> cachedCounterUpdates = new ArrayList<String[]>();
List<DasDetails> docList = new ArrayList<DasDetails>();
ListView listViewDashboard;
DataAdapter dataAdap = new DataAdapter();
TextView noOfItems, userCount, totalLoginTime;
int itemsTotal = 0, userTotal = 0, totalTime = 0;
String KEYWORD = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (App.isTestVersion) {
Log.e("actName", "StoreOut");
}
if (bgVariableIsNull()) {
this.finish();
return;
}
setContentView(R.layout.dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setProgressBarIndeterminateVisibility(false);
lytBlocker = (LinearLayout) findViewById(R.id.lyt_blocker);
listViewDashboard = (ListView) findViewById(R.id.dashboard_listview);
noOfItems = ((TextView) findViewById(R.id.noOfItems));
userCount = ((TextView) findViewById(R.id.userCount));
totalLoginTime = ((TextView) findViewById(R.id.totalLoginTime));
new DataLoader().start();
listViewDashboard.setAdapter(dataAdap);
System.out.println("PerformanceDashboard. onCreate processOutData() -- item total " + itemsTotal); //0 i am not getting that adapter value i.e. 6
System.out.println("PerformanceDashboard. onCreate processOutData() -- user total " + userTotal); //0 i am not getting that adapter value i.e. 4
System.out.println("PerformanceDashboard. onCreate processOutData() -- total total " + totalTime); //0 i am not getting that adapter value i.e. 310
}
private class DataAdapter extends BaseAdapter {
#Override
public int getCount() {
return docList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.dashboard_item, null);
final DasDetails item = docList.get(position);
((TextView) convertView.findViewById(R.id.cMode))
.setText(item.cMode);
((TextView) convertView.findViewById(R.id.noOfItems))
.setText(item.totPickItemCount);
((TextView) convertView.findViewById(R.id.userCount))
.setText(item.userCount);
((TextView) convertView.findViewById(R.id.totalLoginTime))
.setText(item.totLoginTime);
TextView textView = ((TextView) convertView
.findViewById(R.id.avgSpeed));
Double s = Double.parseDouble(item.avgPickingSpeed);
textView.setText(String.format("%.2f", s));
if (position == 0 || position == 2 || position == 4) {
convertView.setBackgroundColor(getResources().getColor(
R.color.hot_pink));
} else if (position == 1 || position == 3 || position == 5) {
convertView.setBackgroundColor(getResources().getColor(
R.color.lightblue));
}
return convertView;
}
}
class ErrorItem {
String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public ErrorItem(HashMap<String, String> row) {
cMode = row.get(XT.MODE);
dDate = row.get(XT.DATE);
userCount = row.get(XT.USER_COUNT);
totLoginTime = row.get(XT.TOT_LOGIN_TIME);
totPickItemCount = row.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = row.get(XT.AVG_PICKING_SPEED);
}
}
private class DataLoader extends Thread {
#Override
public void run() {
super.run();
System.out.println("DataLoader dashboard");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair(C.PRM_IDX, C.GET_SUMMARY));
param.add(new BasicNameValuePair(C.PRM_HDR_DATA, "2016-07-04")); // yyyy-mm-dd
toggleProgressNoUINoBlock(true);
final String result = callService(C.WS_ST_PERFORMANCE_DASHBOARD,
param);
if (!App.validateXmlResult(actContext, null, result, true))
return;
runOnUiThread(new Runnable() {
#Override
public void run() {
Runnable r = new Runnable() {
#Override
public void run() {
dataAdap.notifyDataSetChanged();
toggleProgressNoUINoBlock(false);
}
};
dashboardData = result;
processOutData(r);
}
});
}
}
private String callService(String serviceName, List<NameValuePair> params) {
String result = ws.callService(serviceName, params);
return result;
}
private void processOutData(final Runnable rAfterProcessing) {
if (dashboardData == null || dashboardData.length() == 0)
return;
new Thread() {
#Override
public void run() {
super.run();
final List<HashMap<String, String>> dataList = XMLfunctions
.getDataList(dashboardData, new String[] { XT.MODE,
XT.DATE, XT.USER_COUNT, XT.TOT_LOGIN_TIME,
XT.TOT_PICK_ITEM_COUNT, XT.AVG_PICKING_SPEED });
final List<DasDetails> tempList = new ArrayList<DasDetails>();
for (int i = 0; i < dataList.size(); i++) {
int pos = docExists(tempList, dataList.get(i).get(XT.MODE));
if (pos == -1) {
if (SEARCH_TYPE == 0
|| KEYWORD.equals("")
|| (SEARCH_TYPE == 1 && dataList.get(i)
.get(XT.CUST_NAME).contains(KEYWORD))
|| (SEARCH_TYPE == 2 && dataList.get(i)
.get(XT.DOC_NO).contains(KEYWORD))) {
DasDetails doc = new DasDetails(dataList.get(i));
int cachePos = getPosInCachedCounterUpdates(doc.cMode);
if (cachePos != -1) {
if (cachedCounterUpdates.get(cachePos)[1]
.equals(doc.dDate))
cachedCounterUpdates.remove(cachePos);
else
doc.dDate = cachedCounterUpdates
.get(cachePos)[1];
}
tempList.add(doc);
pos = tempList.size() - 1;
}
}
if (pos == -1)
continue;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
docList = tempList;
rAfterProcessing.run();
logit("processOutData", "Processing OVER");
}
});
for (int i = 0; i < docList.size(); i++) {
itemsTotal = itemsTotal+ Integer.parseInt(docList.get(i).totPickItemCount);
userTotal = userTotal + Integer.parseInt(docList.get(i).userCount);
totalTime = totalTime + Integer.parseInt(docList.get(i).totLoginTime);
}
System.out.println("PerformanceDashboard.processOutData() -- fINAL item TOTAL " + itemsTotal); // 6 i have data here but i need this data in my oncreate but not getting why?????
System.out.println("PerformanceDashboard.processOutData() -- userTotal TOTAL " + userTotal); //4
System.out.println("PerformanceDashboard.processOutData() -- totalTime TOTAL " + totalTime); //310
noOfItems.setText(itemsTotal); // crashing with null pointer exception
// userCount.setText(userTotal);
// totalLoginTime.setText(totalTime);
};
}.start();
}
private class DasDetails {
public String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public DasDetails(HashMap<String, String> data) {
cMode = data.get(XT.MODE);
dDate = data.get(XT.DATE);
userCount = data.get(XT.USER_COUNT);
totLoginTime = data.get(XT.TOT_LOGIN_TIME);
totPickItemCount = data.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = data.get(XT.AVG_PICKING_SPEED);
}
}
public Integer docExists(List<DasDetails> list, String docNo) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).cMode.equals(docNo))
return i;
}
return -1;
}
private int getPosInCachedCounterUpdates(String docNo) {
for (int i = 0; i < cachedCounterUpdates.size(); i++) {
if (cachedCounterUpdates.get(i)[0].equals(docNo))
return i;
}
return -1;
}
}
This is the above code please go through it and let me know if any clarifications are required. I cannot able to set "itemsTotal" value to "noOfIttems" textview. I have added the comments. Please help me in solving this issue.
Thanks in advance.
Please check your noOfItems textView's id. TextView is null.
I am developing a chat application in which I want to add smiley support to it. But I am not being able to use it.
I have gone through many codes but the symbols are not changing to smileys.
Here is my code...
private static final Factory spannableFactory = Spannable.Factory
.getInstance();
private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>();
static {
addPattern(emoticons, ":)", R.drawable.emo_im_happy);
addPattern(emoticons, ":-)", R.drawable.emo_im_happy);
// ...
}
private static void addPattern(Map<Pattern, Integer> map, String smile,
int resource) {
map.put(Pattern.compile(Pattern.quote(smile)), resource);
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging_screen); // messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
}
public void appendToMessageHistory(String paramString1, String paramString2) {
if ((paramString1 != null) && (paramString2 != null)) {
if (paramString1.toString().equals(this.friend.userName.toString())) {
appendColoredText(this.messageHistoryText,paramString1 + ":\n", Layout.Alignment.ALIGN_NORMAL,-16711936);
appendColoredText(this.messageHistoryText, getSmiledText(this, paramString2) + "\n", Layout.Alignment.ALIGN_NORMAL, -16711936);
} else {
appendColoredText(this.messageHistoryText, "you:\n",Layout.Alignment.ALIGN_OPPOSITE, -65536);
appendColoredText(this.messageHistoryText, getSmiledText(this, paramString2) + "\n",Layout.Alignment.ALIGN_OPPOSITE, -65536);
}
}
}
public static boolean addSmiles(Context context, Spannable spannable) {
boolean hasChanges = false;
for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
Matcher matcher = entry.getKey().matcher(spannable);
while (matcher.find()) {
boolean set = true;
for (ImageSpan span : spannable.getSpans(matcher.start(),
matcher.end(), ImageSpan.class))
if (spannable.getSpanStart(span) >= matcher.start()
&& spannable.getSpanEnd(span) <= matcher.end())
spannable.removeSpan(span);
else {
set = false;
break;
}
if (set) {
hasChanges = true;
spannable.setSpan(new ImageSpan(context, entry.getValue()), matcher.start(), matcher.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
return hasChanges;
}
public static Spannable getSmiledText(Context context, CharSequence text) {
Spannable spannable = spannableFactory.newSpannable(text);
addSmiles(context, spannable);
return spannable;
}
public static void appendColoredText(EditText paramEditText,String paramString, Layout.Alignment paramAlignment, int paramInt) {
int i = paramEditText.getText().length();
paramEditText.append(paramString);
int j = paramEditText.getText().length();
Editable localEditable = paramEditText.getText();
localEditable.setSpan(new ForegroundColorSpan(paramInt), i, j, 0);
localEditable.setSpan(new AlignmentSpan.Standard(paramAlignment), i, j, 0);
//localEditable.setSpan(new BackgroundColorSpan(back), i, j, 0);
}
I am using this code with Static block so that the emoticons should be displayed but they are not being displayed. So what should I do to get it done?
Thank You