I made a calendar like it is shown on the screenshot.. but I need to do that week start with monday instead of sunday... i tied to do Calendar cal = Calendar.getInstanty(); cal.setFirstDayOfWeek(Calendar.MONDAY);
but this didn't help.. any ideas?
Thanks you
import java.util.Calendar;
import java.util.Locale;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
public class CalendarView extends LinearLayout {
public CalendarView(Context context) {
super(context);
init(context);
}
public CalendarView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public interface OnMonthChangedListener {
public void onMonthChanged(CalendarView view);
}
public void setOnMonthChangedListener(OnMonthChangedListener l) {
_onMonthChangedListener = l;
}
public interface OnSelectedDayChangedListener {
public void onSelectedDayChanged(CalendarView view);
}
public void setOnSelectedDayChangedListener(OnSelectedDayChangedListener l) {
_onSelectedDayChangedListener = l;
}
public Calendar getVisibleStartDate() {
return _calendar.getVisibleStartDate();
}
public Calendar getVisibleEndDate() {
return _calendar.getVisibleEndDate();
}
public Calendar getSelectedDay() {
return _calendar.getSelectedDay();
}
private void init(Context context) {
View v = LayoutInflater.from(context).inflate(R.layout.calendar, this, true);
_calendar = new CalendarWrapper();
_days = (TableLayout) v.findViewById(R.id.days);
_up = (TextView) v.findViewById(R.id.up);
_prev = (Button) v.findViewById(R.id.previous);
_next = (Button) v.findViewById(R.id.next);
refreshCurrentDate();
// Days Table
String[] shortWeekDayNames = _calendar.getShortDayNames();
for (int i = 0; i < 7; i++) { // Rows
TableRow tr = (TableRow) _days.getChildAt(i);
for (int j = 0; j < 7; j++) { // Columns
Boolean header = i == 0; // First row is weekday headers
TextView tv = (TextView) tr.getChildAt(j);
if (header)
tv.setText(shortWeekDayNames[j]);
else
tv.setOnClickListener(_dayClicked);
}
}
refreshDayCells();
// Listeners
_calendar.setOnDateChangedListener(_dateChanged);
_prev.setOnClickListener(_incrementClicked);
_next.setOnClickListener(_incrementClicked);
setView(MONTH_VIEW);
}
private OnClickListener _incrementClicked = new OnClickListener() {
public void onClick(View v) {
int inc = (v == _next ? 1 : -1);
if (_currentView == MONTH_VIEW)
_calendar.addMonth(inc);
else if (_currentView == DAY_VIEW) {
_calendar.addDay(inc);
invokeSelectedDayChangedListener();
}
else if (_currentView == YEAR_VIEW) {
_currentYear += inc;
refreshUpText();
}
}
};
private OnDateChangedListener _dateChanged = new OnDateChangedListener() {
public void onDateChanged(CalendarWrapper sc) {
Boolean monthChanged = _currentYear != sc.getYear() || _currentMonth != sc.getMonth();
if (monthChanged) {
refreshDayCells();
invokeMonthChangedListener();
}
refreshCurrentDate();
refreshUpText();
}
};
private OnClickListener _dayClicked = new OnClickListener() {
public void onClick(View v) {
}
};
private void refreshDayCells() {
int[] dayGrid = _calendar.get7x6DayArray();
int monthAdd = -1;
int row = 1; // Skip weekday header row
int col = 0;
for (int i = 0; i < dayGrid.length; i++) {
int day = dayGrid[i];
if (day == 1)
monthAdd++;
TableRow tr = (TableRow) _days.getChildAt(row);
TextView tv = (TextView) tr.getChildAt(col);
//Clear current markers, if any.
tv.setBackgroundDrawable(null);
tv.setWidth(0);
tv.setTextSize(12);
tv.setText(dayGrid[i] + " 100€");
tv.setBackgroundColor(Color.WHITE);
if (monthAdd == 0)
tv.setTextColor(Color.BLACK);
else
tv.setTextColor(Color.LTGRAY);
tv.setTag(new int[] { monthAdd, dayGrid[i] });
col++;
if (col == 7) {
col = 0;
row++;
}
}
}
private void setView(int view) {
if (_currentView != view) {
_currentView = view;
_days.setVisibility(_currentView == MONTH_VIEW ? View.VISIBLE : View.GONE);
refreshUpText();
}
}
private void refreshUpText() {
switch (_currentView) {
case MONTH_VIEW:
_up.setText(_calendar.toString("MMMM yyyy"));
break;
case YEAR_VIEW:
_up.setText(_currentYear + "");
break;
case CENTURY_VIEW:
_up.setText("CENTURY_VIEW");
break;
case DECADE_VIEW:
_up.setText("DECADE_VIEW");
break;
case DAY_VIEW:
_up.setText(_calendar.toString("EEEE, MMMM dd, yyyy"));
break;
case ITEM_VIEW:
_up.setText("ITEM_VIEW");
break;
default:
break;
}
}
private void refreshCurrentDate() {
_currentYear = _calendar.getYear();
_currentMonth = _calendar.getMonth();
_calendar.getDay();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if(month == _calendar.getMonth() && year== _calendar.getYear()){_prev.setVisibility(INVISIBLE);}
else {_prev.setVisibility(VISIBLE);}
}
private void invokeMonthChangedListener() {
if (_onMonthChangedListener != null)
_onMonthChangedListener.onMonthChanged(this);
}
private void invokeSelectedDayChangedListener() {
if (_onSelectedDayChangedListener != null)
_onSelectedDayChangedListener.onSelectedDayChanged(this);
}
private final int CENTURY_VIEW = 5;
private final int DECADE_VIEW = 4;
private final int YEAR_VIEW = 3;
private final int MONTH_VIEW = 2;
private final int DAY_VIEW = 1;
private final int ITEM_VIEW = 0;
private CalendarWrapper _calendar;
private TableLayout _days;
private TextView _up;
private Button _prev;
private Button _next;
// private Spinner sailFromSpinner;
private OnMonthChangedListener _onMonthChangedListener;
private OnSelectedDayChangedListener _onSelectedDayChangedListener;
private int _currentView;
private int _currentYear;
private int _currentMonth;
public Calendar cal = Calendar.getInstance();
}
class CalendarWrapper {
public interface OnDateChangedListener {
public void onDateChanged(CalendarWrapper sc);
}
public CalendarWrapper() {
_calendar = Calendar.getInstance();
_shortDayNames = new String[_calendar.getActualMaximum(Calendar.DAY_OF_WEEK)];
_shortMonthNames = new String[_calendar.getActualMaximum(Calendar.MONTH) + 1]; // Months are 0-based so size is Max + 1
for (int i = 0; i < _shortDayNames.length; i++) {
_shortDayNames[i] = DateUtils.getDayOfWeekString(i +1 , DateUtils.LENGTH_SHORT);
}
for (int i = 0; i < _shortMonthNames.length; i++) {
_shortMonthNames[i] = DateUtils.getMonthString(i, DateUtils.LENGTH_SHORT);
}
}
public int getYear() {
return _calendar.get(Calendar.YEAR);
}
public int getMonth() {
return _calendar.get(Calendar.MONTH);
}
public int getDayOfWeek() {
return _calendar.get(Calendar.DAY_OF_WEEK);
}
public int getDay() {
return _calendar.get(Calendar.DAY_OF_MONTH);
}
public void setYear(int value) {
_calendar.set(Calendar.YEAR, value);
invokeDateChangedListener();
}
public void setYearAndMonth(int year, int month) {
_calendar.set(Calendar.YEAR, year);
_calendar.set(Calendar.MONTH, month);
invokeDateChangedListener();
}
public void setMonth(int value) {
_calendar.set(Calendar.MONTH, value);
invokeDateChangedListener();
}
public void setDay(int value) {
_calendar.set(Calendar.DAY_OF_MONTH, value);
invokeDateChangedListener();
}
public void addYear(int value) {
if(value != 0) {
_calendar.add(Calendar.YEAR, value);
invokeDateChangedListener();
}
}
public void addMonth(int value) {
if(value != 0) {
_calendar.add(Calendar.MONTH, value);
invokeDateChangedListener();
}
}
public void addMonthSetDay(int monthAdd, int day) {
_calendar.add(Calendar.MONTH, monthAdd);
_calendar.set(Calendar.DAY_OF_MONTH, day);
invokeDateChangedListener();
}
public void addDay(int value) {
if(value != 0) {
_calendar.add(Calendar.DAY_OF_MONTH, value);
invokeDateChangedListener();
}
}
public String[] getShortDayNames() {
return _shortDayNames;
}
public String[] getShortMonthNames() {
return _shortMonthNames;
}
public int[] get7x6DayArray() {
_visibleStartDate = null;
_visibleEndDate = null;
int[] days = new int[42];
Calendar tempCal = (Calendar) _calendar.clone();
tempCal.setFirstDayOfWeek(2);
tempCal.set(Calendar.DAY_OF_MONTH, 1);
int dayOfWeekOn1st = tempCal.get(Calendar.DAY_OF_WEEK);
int maxDay = tempCal.getActualMaximum(Calendar.DAY_OF_MONTH);
int previousMonthCount = dayOfWeekOn1st - 1;
int index = 0;
if (previousMonthCount > 0) {
tempCal.set(Calendar.DAY_OF_MONTH, -1);
int previousMonthMax = tempCal.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = previousMonthCount; i > 0; i--) {
int day = previousMonthMax - i + 1;
if(i == previousMonthCount) {
_visibleStartDate = (Calendar)tempCal.clone();
// _visibleStartDate.setFirstDayOfWeek(2);
_visibleStartDate.set(Calendar.DAY_OF_MONTH, day);
}
days[index] = day;
index++;
}
}
for (int i = 0; i < maxDay; i++) {
if(i == 0 && _visibleStartDate == null)
_visibleStartDate = (Calendar)tempCal.clone();
days[index] = (i + 1);
index++;
}
int nextMonthDay = 1;
for (int i = index; i < days.length; i++) {
if(i == index)
days[index] = nextMonthDay;
nextMonthDay++;
index++;
}
_visibleEndDate = (Calendar) _calendar.clone();
_visibleEndDate.add(Calendar.MONTH, 1);
_visibleEndDate.set(Calendar.DAY_OF_MONTH, days[41]);
return days;
}
public Calendar getSelectedDay() {
return (Calendar)_calendar.clone();
}
public Calendar getVisibleStartDate() {
return (Calendar) _visibleStartDate.clone();
}
public Calendar getVisibleEndDate() {
return (Calendar) _visibleEndDate.clone();
}
public void setOnDateChangedListener(OnDateChangedListener l) {
_onDateChangedListener = l;
}
public String toString(CharSequence format) {
return DateFormat.format(format, _calendar).toString();
}
private void invokeDateChangedListener() {
if (_onDateChangedListener != null)
_onDateChangedListener.onDateChanged(this);
}
private Calendar _calendar;
private String[] _shortDayNames;
private String[] _shortMonthNames;
private OnDateChangedListener _onDateChangedListener;
private Calendar _visibleStartDate;
private Calendar _visibleEndDate;
}
Don't know if I'm right, don't have android / java to test right now.
By seems that you do some math on _calendar, then clone it inside the get7x6DayArray, set to begin on Monday in that clone, them return the days[] to be show. But you never set the _calendar to begin on Monday, so you get the "shortWeekDayNames" begining with the Sunday (that's problably what your locale is set).
EDIT: taking a closer look to your question: in your CalendarWrapper you create an Array to hold the name of the days of the week: _shortDayNames.
Then you do a loop to fill the array with the short names: you loop from 0-6, getting the 1-7 days' names.
If you look closer at this and this, you'll see that Sunday is always the value 1: calendar.SUNDAY = 1, so _shortDayNames[0] will always get the String that corresponds to the "1" value, which is always Sunday. So your calendar will always be shown to begin with "Sunday" when you display it.
Isn't that the problem ?
Related
I am using this TextWatcher for .addtextOnChangeListener, the output of the string is ex: "123,456,77" i want it to be "123.456,77" if i use the replace method on "et" in the "afterTextChanged" method, the number isn't even formatting. With the code below the listener works and everything, i just don't know how to replace the "," with "." until the decimals.
If you think to just change the pattern ("###,##0,00") it doesn't work
This is the TextWatcher I have for the EditText
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Locale;
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private EditText et;
public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("###,##0,00");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("###,##0,00");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int index = s.toString().indexOf(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()));
int trailingZeroCount = 0;
if (index > -1)
{
for (index++; index < s.length(); index++) {
if (s.charAt(index) == '0')
trailingZeroCount++;
else {
trailingZeroCount = 0;
}
}
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
{
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
Use this:
DecimalFormat decimalFormat=new DecimalFormat();
DecimalFormatSymbols decimalFormatSymbols=DecimalFormatSymbols.getInstance();
decimalFormatSymbols.setDecimalSeparator(',');
decimalFormatSymbols.setGroupingSeparator('.');
decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
String formattedNumber=decimalFormat.format(123456.78);// prints 123.456,78
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 have following issue. I have EditText and TextWatcher which format input text according to some rules. In method afterTextChanged() I format it. Then I have formatted string and I want to replace old value of EditText by formatted value.
Next we have two options:
use EditText.setText()
use Editable.replace()
If we use first option, EditText works very slowly and looses symbols.
But If we use second method, Editable doesn't replace old text, but append new text to old text.
Maybe someone had similar issue?
Upd: using Editable.clear() then Editable.append() or insert() have similar effect
Code:
public static class LoginWatcher implements TextWatcher {
private EditText target;
private LoginFilter loginFilter = new LoginFilter();
private int lastLength;
private boolean wasPhoneNumber = false;
private AsYouTypeFormatter formatter;
private boolean isFormattingStopped;
public LoginWatcher(OnLoginEnterListener onLoginInputListener, EditText target) {
listener = onLoginInputListener;
this.target = target;
lastLength = target.getText().length();
formatter = PhoneNumberUtil.getInstance().getAsYouTypeFormatter(Locale.getDefault().getCountry());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (isFormattingStopped) {
return;
}
if (count > 0 && hasSeparator(s, start, count)) {
stopFormatting();
}
}
#Override
public void afterTextChanged(Editable s) {
target.removeTextChangedListener(this);
boolean isSymbolsChecked = loginFilter.check(s.toString());
boolean isEmail = StringUtils.isEmailValid(s.toString());
boolean isPhoneNumber = isPhoneNumber(s.toString());
if (lastLength <= s.length()) {
if (isPhoneNumber && !isFormattingStopped) {
String formatted = reformat(s, Selection.getSelectionEnd(s));
if (formatted != null) {
target.setText(formatted);
target.setSelection(target.getText().length());
}
} else if (wasPhoneNumber) {
String unformatted = unFormatPhoneNumber(s.toString());
target.setText(unformatted); // or s.clear(); s.append();
target.setSelection(target.getText().length());
}
}
lastLength = s.length();
wasPhoneNumber = isPhoneNumber;
if (isFormattingStopped) {
isFormattingStopped = s.length() != 0;
}
target.addTextChangedListener(this);
}
private String unFormatPhoneNumber(String s) {
char[] chars = s.toCharArray();
if (s.isEmpty()) {
return s;
}
if (chars[0] == '+') {
boolean isPhoneNumber = true;
for (int i = 1; i < chars.length; ++i) {
if (!Character.isDigit(chars[i])) {
isPhoneNumber = false;
break;
}
}
if (isPhoneNumber) {
return s;
}
}
return s.replaceAll("[\\+\\(\\)\\s\\-]+", "");
}
private String reformat(CharSequence s, int cursor) {
int curIndex = cursor - 1;
String formatted = null;
formatter.clear();
char lastNonSeparator = 0;
boolean hasCursor = false;
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (PhoneNumberUtils.isNonSeparator(c)) {
if (lastNonSeparator != 0) {
formatted = getFormattedNumber(lastNonSeparator, hasCursor);
hasCursor = false;
}
lastNonSeparator = c;
}
if (i == curIndex) {
hasCursor = true;
}
}
if (lastNonSeparator != 0) {
formatted = getFormattedNumber(lastNonSeparator, hasCursor);
}
return formatted;
}
private String getFormattedNumber(char lastNonSeparator, boolean hasCursor) {
return hasCursor ? formatter.inputDigitAndRememberPosition(lastNonSeparator)
: formatter.inputDigit(lastNonSeparator);
}
private boolean isPhoneNumber(String s) {
return !TextUtils.isEmpty(s) && Patterns.PHONE.matcher(s).matches();
}
private boolean hasSeparator(final CharSequence s, final int start, final int count) {
for (int i = start; i < start + count; i++) {
char c = s.charAt(i);
if (!PhoneNumberUtils.isNonSeparator(c)) {
return true;
}
}
return false;
}
private void stopFormatting() {
isFormattingStopped = true;
formatter.clear();
}
}
Try to use the methods provided by Editable
#Override
public void afterTextChanged(Editable s) {
target.removeTextChangedListener(this);
boolean isSymbolsChecked = loginFilter.check(s.toString());
boolean isEmail = StringUtils.isEmailValid(s.toString());
boolean isPhoneNumber = isPhoneNumber(s.toString());
if (lastLength <= s.length()) {
if (isPhoneNumber && !isFormattingStopped) {
String formatted = reformat(s, Selection.getSelectionEnd(s));
if (formatted != null) {
s.replace(0, s.length(), formatted)
target.setSelection(formatted.length());
}
} else if (wasPhoneNumber) {
String unformatted = unFormatPhoneNumber(s.toString());
s.replace(0, s.length(), formatted)
target.setSelection(formatted.length());
}
}
lastLength = s.length();
wasPhoneNumber = isPhoneNumber;
if (isFormattingStopped) {
isFormattingStopped = s.length() != 0;
}
target.addTextChangedListener(this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
Locale.setDefault(Locale.US);
test1 = "2014-11-08";
test2 = "2014-11-07";
test3 = "2014-12-08";
test4 = "2014-12-04";
rLayout = (LinearLayout) findViewById(R.id.text);
tvView = (TextView)findViewById(R.id.tvView);
tvView1 = (TextView)findViewById(R.id.tvView1);
tvView2 = (TextView)findViewById(R.id.tvView2);
tvView3 = (TextView)findViewById(R.id.tvView3);
tvView4 = (TextView)findViewById(R.id.tvView4);
tvView5 = (TextView)findViewById(R.id.tvView5);
tvView3.setVisibility(View.GONE);
tvView4.setVisibility(View.GONE);
tvView5.setVisibility(View.GONE);
month = (GregorianCalendar) Calendar.getInstance();
itemmonth = (GregorianCalendar) month.clone();
items = new ArrayList<String>();
adapter = new CalendarAdapter(this, month);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);
handler = new Handler();
handler.post(calendarUpdater);
TextView title = (TextView) findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);
previous.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setPreviousMonth();
refreshCalendar();
tvView.setVisibility(View.GONE);
}
});
RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setNextMonth();
refreshCalendar();
tvView.setVisibility(View.GONE);
}
});
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
TextView cdate = (TextView)v.findViewById(R.id.date);
if(cdate instanceof TextView && !cdate.getText().equals(""))
{
TextView title = (TextView) findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
testMonth=title.getText().toString();
String day = cdate.getText().toString();
Toast.makeText(getApplicationContext(),day+" "+testMonth,Toast.LENGTH_SHORT).show();
}
// removing the previous view if added
if (rLayout.getChildCount() > 0) {
// rLayout.removeAllViews();
}
desc = new ArrayList<String>();
date = new ArrayList<String>();
((CalendarAdapter) parent.getAdapter()).setSelected(v);
String selectedGridDate = CalendarAdapter.dayString
.get(position);
tvView.setVisibility(View.VISIBLE);
tvView3.setVisibility(View.VISIBLE);
tvView4.setVisibility(View.VISIBLE);
tvView5.setVisibility(View.VISIBLE);
if(test1.equals(selectedGridDate))
{
tvView.setText("My Goal");
tvView.setTextColor(Color.RED);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
}
else if(test2.equals(selectedGridDate))
{
tvView.setText("Passion of a Student");
tvView.setTextColor(Color.RED);
tvView1.setText("Creating my own Goal");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("Circular Task");
tvView2.setTextColor(Color.GREEN);
}
else if(test3.equals(selectedGridDate))
{
tvView.setText("My test Passion");
tvView.setTextColor(Color.RED);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
}
else if(test3.equals(selectedGridDate))
{
tvView.setText("My test Task");
tvView.setTextColor(Color.RED);
}
else
{
tvView.setText("No task found");
tvView.setTextColor(Color.MAGENTA);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
tvView2.setTextColor(Color.GREEN);
tvView3.setVisibility(View.GONE);
tvView4.setVisibility(View.GONE);
tvView5.setVisibility(View.GONE);
}
String[] separatedTime = selectedGridDate.split("-");
String gridvalueString = separatedTime[2].replaceFirst("^0*",
"");// taking last part of date. ie; 2 from 2012-12-02.
int gridvalue = Integer.parseInt(gridvalueString);
// navigate to next or previous month on clicking offdays.
if ((gridvalue > 10) && (position < 8)) {
setPreviousMonth();
refreshCalendar();
} else if ((gridvalue < 7) && (position > 28)) {
setNextMonth();
refreshCalendar();
}
((CalendarAdapter) parent.getAdapter()).setSelected(v);
for (int i = 0; i < Utility.startDates.size(); i++) {
if (Utility.startDates.get(i).equals(selectedGridDate)) {
desc.add(Utility.nameOfEvent.get(i));
}
}
if (desc.size() > 0) {
for (int i = 0; i < desc.size(); i++) {
TextView rowTextView = new TextView(CalendarView.this);
// set some properties of rowTextView or something
rowTextView.setText("Event:" + desc.get(i));
rowTextView.setTextColor(Color.BLACK);
// add the textview to the linearlayout
rLayout.addView(rowTextView);
}
}
desc = null;
}
});
}
protected void setNextMonth() {
if (month.get(Calendar.MONTH) == month
.getActualMaximum(Calendar.MONTH)) {
month.set((month.get(Calendar.YEAR) + 1),
month.getActualMinimum(Calendar.MONTH), 1);
} else {
month.set(Calendar.MONTH,
month.get(Calendar.MONTH) + 1);
}
}
protected void setPreviousMonth() {
if (month.get(Calendar.MONTH) == month
.getActualMinimum(Calendar.MONTH)) {
month.set((month.get(Calendar.YEAR) - 1),
month.getActualMaximum(Calendar.MONTH), 1);
} else {
month.set(Calendar.MONTH,
month.get(Calendar.MONTH) - 1);
}
}
protected void showToast(String string) {
Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
}
public void refreshCalendar() {
TextView title = (TextView) findViewById(R.id.title);
adapter.refreshDays();
adapter.notifyDataSetChanged();
handler.post(calendarUpdater); // generate some calendar items
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
}
public Runnable calendarUpdater = new Runnable() {
#Override
public void run() {
items.clear();
// Print dates of the current week
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String itemvalue;
event = Utility.readCalendarEvent(CalendarView.this);
Log.d("=====Event====", event.toString());
Log.d("=====Date ARRAY====", Utility.startDates.toString());
for (int i = 0; i < Utility.startDates.size(); i++) {
itemvalue = df.format(itemmonth.getTime());
itemmonth.add(Calendar.DATE, 1);
items.add(Utility.startDates.get(i).toString());
}
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
here I able to see all events while clicking on a particular date,but my requirement is also show the dates with bold style or any other color view that containing events without clicking gridview items.My adapter class as follows:::
public class CalendarAdapter extends BaseAdapter {
private Context mContext;
private java.util.Calendar month;
public GregorianCalendar pmonth;
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int lastWeekDay;
int leftDays;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
private ArrayList<String> items;
public static List<String> dayString;
private View previousView;
public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
CalendarAdapter.dayString = new ArrayList<String>();
Locale.setDefault(Locale.US);
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public void setItems(ArrayList<String> items) {
for (int i = 0; i != items.size(); i++) {
if (items.get(i).length() == 1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}
#Override
public int getCount() {
return dayString.size();
}
#Override
public Object getItem(int position) {
return dayString.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_layout, null);
}
dayView = (TextView) v.findViewById(R.id.date);
// separates daystring into parts.
String[] separatedTime = dayString.get(position).split("-");
// taking last part of date. ie; 2 from 2012-12-02
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
// checking whether the day is in current month or not.
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
// setting offdays to white color.
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.BLUE);
}
if (dayString.get(position).equals(curentDateString)) {
setSelected(v);
previousView = v;
} else {
v.setBackgroundResource(R.drawable.list_item_background);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = dayString.get(position);
if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(Calendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}
// show icon if date is not empty and it exists in the items array
ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
if (date.length() > 0 && items != null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
} else {
iw.setVisibility(View.INVISIBLE);
}
return v;
}
public View setSelected(View view) {
if (previousView != null) {
previousView.setBackgroundResource(R.drawable.list_item_background);
}
previousView = view;
view.setBackgroundResource(R.drawable.calendar_cel_selectl);
return view;
}
public void refreshDays() {
// clear items
items.clear();
dayString.clear();
Locale.setDefault(Locale.US);
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(Calendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(Calendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
/**
* Calendar instance for getting a complete gridview including the three
* month's (previous,current,next) dates.
*/
pmonthmaxset = (GregorianCalendar) pmonth.clone();
/**
* setting the start date as previous month's required date.
*/
pmonthmaxset.set(Calendar.DAY_OF_MONTH, calMaxP + 1);
/**
* filling calendar gridview.
*/
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(Calendar.DATE, 1);
dayString.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(Calendar.MONTH) == month
.getActualMinimum(Calendar.MONTH)) {
pmonth.set((month.get(Calendar.YEAR) - 1),
month.getActualMaximum(Calendar.MONTH), 1);
} else {
pmonth.set(Calendar.MONTH,
month.get(Calendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(Calendar.DAY_OF_MONTH);
return maxP;
}
}
Atlast I had already solved my problem changing my Runnable calendar updater as follows:
public Runnable calendarUpdater = new Runnable() {
#Override
public void run()
{
items.clear();
// Print dates of the current week
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String itemvalue;
for (int i = 0; i < 7; i++)
{
itemvalue = df.format(itemmonth.getTime());
itemmonth.add(Calendar.DATE, 1);
items.add("2014-12-08");
items.add("2014-12-04");
items.add("2014-11-07");
items.add("2014-11-08");
}
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
Now I can see the events without clicking gridView items what I want.Thanx all of you guys for your kind cooperation in this regard. but now issue is how can I also show this event on android google calendar.
I've been stuck on this for a whole day, please help me. So I have 2 arrays filled with five dice rolls from two players and I want to set them to the according dice image that I put in my drawable. This is the original code that I have, displaying the arrays in TextView.
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice;
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
I can't figure out how to get it to display the ImageView instead.
private final static int[] diceImages = new int[] { R.drawable.d1,
R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
What I am missing?
Here's my full code, sorry its a mess. I just started to learn programming on my own and this is my first program. Any advice on making it better is appreciated too.
package com.kelvinblade.liardice;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice, result, whosTurn, tvLog, score;
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
Button openDice, callDice;
EditText NumDice, DiceNum;
int NumOfDice, DiceNumber, turn;
int currentDiceQuantity, currentDiceFace;
boolean isOneWildCard = true;
int callLog[] = new int[70];
int playerOneEnergy, playerTwoEnergy;
boolean playerOneStart = true;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializePlaceHolders();
startGame();
}
// Initialize the Place Holders
private void initializePlaceHolders() {
p1Dice = (TextView) findViewById(R.id.tvP1Dice);
p2Dice = (TextView) findViewById(R.id.tvP2Dice);
openDice = (Button) findViewById(R.id.bOpenDice);
callDice = (Button) findViewById(R.id.bCallDice);
whosTurn = (TextView) findViewById(R.id.tvWhosTurn);
tvLog = (TextView) findViewById(R.id.tvLog);
score = (TextView) findViewById(R.id.tvScore);
result = (TextView) findViewById(R.id.tvResult);
NumDice = (EditText) findViewById(R.id.etNumDice);
DiceNum = (EditText) findViewById(R.id.etDiceNum);
p1Dice1 = (ImageView) findViewById(R.id.ivDice1);
p1Dice2 = (ImageView) findViewById(R.id.ivDice2);
p1Dice3 = (ImageView) findViewById(R.id.ivDice3);
p1Dice4 = (ImageView) findViewById(R.id.ivDice4);
p1Dice5 = (ImageView) findViewById(R.id.ivDice5);
openDice.setOnClickListener(this);
callDice.setOnClickListener(this);
}
// Game starts here
public void startGame() {
playerOneEnergy = 4;
playerTwoEnergy = 4;
playGame();
}
// Starts level
public void playGame() {
if ((playerOneEnergy != 0) && (playerTwoEnergy != 0)) {
initialize();
player1 = rollDice();
player2 = rollDice();
displayDice();
displayTurn();
} else if (playerTwoEnergy == 0) {
result.setText("Loading Next Stage!");
startGame();
} else
result.setText("Game Over!");
}
// Initialize the Variables
private void initialize() {
turn = 0;
currentDiceQuantity = 0;
currentDiceFace = 0;
result.setText("New Game.");
tvLog.setText("Game Log:");
}
// Rolls the Dice
private int[] rollDice() {
int[] diceArray = new int[5];
Random randomDice = new Random();
for (int i = 0; i < 5; i++) {
diceArray[i] = randomDice.nextInt(6) + 1;
}
return diceArray;
}
// Displays the Dice for Player 1 & 2
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
// try to display the dice array as image <here's the problem>
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
}
// Button actions
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCallDice:
try {
getCall();
} catch (Exception e) {
Dialog d = new Dialog(this);
d.setTitle("Invalid call. Please try again.");
d.show();
}
if ((validInput()) && (validCall()))
runCall();
else
result.setText("Invalid call");
break;
case R.id.bOpenDice:
checkDice();
break;
}
}
private void runCall() {
currentDiceQuantity = NumOfDice;
currentDiceFace = DiceNumber;
result.setText("Valid call");
writeLog();
displayLog();
turn++;
displayTurn();
}
private void startAImove() {
Random randomAction = new Random();
int randomCall = randomAction.nextInt(1);
if ((randomCall == 0) && (!isFirstMove()))
checkDice();
else {
while (!validCall()) {
NumOfDice = randomAction.nextInt(5) + 1;
DiceNumber = randomAction.nextInt(5) + 1;
}
runCall();
}
}
// Gets the Call from Player 1
private void getCall() {
String s = NumDice.getText().toString();
NumOfDice = Integer.parseInt(s);
String s1 = DiceNum.getText().toString();
DiceNumber = Integer.parseInt(s1);
if (DiceNumber == 1) {
isOneWildCard = false;
}
}
// Checks to see if the call is a valid input
private boolean validInput() {
int MaxNumOfDice = 5;
int MaxDiceQuantity = 6;
if ((NumOfDice <= MaxNumOfDice * 2) && (DiceNumber <= MaxDiceQuantity)) {
return true;
} else
return false;
}
// Checks to see if Valid Call
private boolean validCall() {
if (NumOfDice > currentDiceQuantity) {
return true;
} else if (((NumOfDice == currentDiceQuantity) && (currentDiceFace != 1))
&& ((DiceNumber == 1) || (DiceNumber > currentDiceFace))) {
return true;
} else {
return false;
}
}
// Writes to Log
private void writeLog() {
callLog[turn * 2] = currentDiceQuantity;
callLog[turn * 2 + 1] = currentDiceFace;
}
// Display Log
private void displayLog() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Game Log:\n");
for (int i = 0; i < turn + 1; i++) {
sbfNumbers.append((i + 1) + ": Player" + (i % 2 + 1) + " "
+ callLog[i * 2] + "x" + callLog[i * 2 + 1] + "\n");
}
tvLog.setText(sbfNumbers.toString());
}
// Display who's turn
public void displayTurn() {
if (whichPlayersTurn() == 1)
whosTurn.setText("Player 1's Turn...");
else {
whosTurn.setText("Player 2's Turn...");
// startAImove();
}
}
// Checks who's turn
private int whichPlayersTurn() {
boolean isTurnEven = false;
if (turn % 2 == 0)
isTurnEven = true;
if (((playerOneStart) && (isTurnEven))
|| ((!playerOneStart) && (!isTurnEven))) {
return 1;
} else
return 2;
}
// Checks if it's the first move
private boolean isFirstMove() {
if (currentDiceQuantity == 0)
return true;
else
return false;
}
// Checks the Player 1 & 2 for the Dice
private void checkDice() {
if (!isFirstMove()) {
int DiceCount = 0;
for (int i = 0; i < 5; i++) {
if (player1[i] == DiceNumber)
DiceCount++;
if (player2[i] == DiceNumber)
DiceCount++;
if ((player1[i] == 1) && (isOneWildCard))
DiceCount++;
if ((player2[i] == 1) && (isOneWildCard))
DiceCount++;
}
if (((DiceCount >= NumOfDice) && (whichPlayersTurn() != 1))
|| ((DiceCount < NumOfDice) && (whichPlayersTurn() == 1))) {
result.setText("Player 1 Wins!");
playerTwoEnergy--;
playerOneStart = false;
} else {
result.setText("Player 1 Loses!");
playerOneEnergy--;
playerOneStart = true;
}
displayWinLost();
playGame();
} else
result.setText("Can not open on first move!");
}
// Display Win / Lose
private void displayWinLost() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Player One Energy : " + playerOneEnergy
+ "\nPlayer Two Energy: " + playerTwoEnergy);
score.setText(sbfNumbers.toString());
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
Thank you so much in advanced. Any help is highly appreciated. Thanks again!!
In your code imageViews are not in an array, so you cannot do p1Dice[i] .
So please change to
private ImageView[] p1Dice = new ImageView[5];
or
p1Dice1.setImageResource(diceImage[player1[0]]);
p1Dice2.setImageResource(diceImage[player1[1]]);
p1Dice3.setImageResource(diceImage[player1[2]]);
The ImageViews are not in an array, so you cannot do p1Dice[i].something()
Change the declaration to ImageViews to this
private ImageView[] p1Dice = new ImageView[5];