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

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?

Related

How to if conditions between two intents in Android Studio?

Р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).

Holder cardview change textview color error

i want to change color of my textview inside of cardview when its value is "kritis" or "kurang" but somehow everytime when my textview in position 0 and its value is either kritis or kurang it always change color textiew in position 0 and also position 7, and also when its in position 1 it will set color text view in position 8 too and so... and then i try to use logd to see howmany times my setcolor initiate and its only 1x (when changing color only position 1 and 7) or 2x (when changing color text position 0,1,7,8)(my cardview is inside recyclerview)
this is my adapter code
public class ListAdapter extends RecyclerView.Adapter<form_mhs_04_fragment2.ListAdapter.ViewHolder>
{
private ArrayList<DataNote> dataList;
public ListAdapter(ArrayList<DataNote> data)
{
this.dataList = data;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView textViewIPKcap;
TextView textViewIPKkat;
TextView textViewSKScap;
TextView textViewSKSkat;
TextView textViewCatatan;
TextView textViewSemester;
public ViewHolder(View itemView)
{
super(itemView);
this.textViewSemester = (TextView) itemView.findViewById(R.id.TV04_cardview_semester);
this.textViewIPKcap = (TextView) itemView.findViewById(R.id.TV04_cardview_ipkcap);
this.textViewIPKkat = (TextView) itemView.findViewById(R.id.TV04_cardview_ipkkat);
this.textViewSKScap = (TextView) itemView.findViewById(R.id.TV04_cardview_skscap);
this.textViewSKSkat = (TextView) itemView.findViewById(R.id.TV04_cardview_skskat);
this.textViewCatatan = (TextView) itemView.findViewById(R.id.TV04_cardview_catatan);
}
}
#Override
public form_mhs_04_fragment2.ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.form_mhs_04_cardview, parent, false);
form_mhs_04_fragment2.ListAdapter.ViewHolder viewHolder = new form_mhs_04_fragment2.ListAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(form_mhs_04_fragment2.ListAdapter.ViewHolder holder, final int position)
{
holder.textViewIPKkat.setText(dataList.get(position).getIpkkat());
holder.textViewIPKcap.setText("IPK : "+dataList.get(position).getIpkcap());
holder.textViewSKSkat.setText(dataList.get(position).getSkskat());
holder.textViewSKScap.setText("SKS : "+dataList.get(position).getSkscap()+" SKS");
holder.textViewCatatan.setText(dataList.get(position).getCatatan());
holder.textViewSemester.setText(dataList.get(position).getSemester());
if(holder.textViewSKSkat.getText().equals("kritis") || holder.textViewSKSkat.getText().equals("kurang")){
holder.textViewSKSkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
}
if(holder.textViewIPKkat.getText().equals("kritis") || holder.textViewIPKkat.getText().equals("kurang")){
holder.textViewIPKkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
}
holder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
}
});
}
#Override
public int getItemCount()
{
return dataList.size();
}
}
this is how i send data to adapter
public void initListView(String UserId){
Call<ListForm4Response> getListForm4 = mApiService.getListForm4(
UserId
);
getListForm4.enqueue(new Callback<ListForm4Response>() {
#Override
public void onResponse(Call<ListForm4Response> call, Response<ListForm4Response> response) {
boolean iserror_ = response.body().getError();
if (iserror_ == false) {
List<List_Form4> list = new ArrayList<>();
list = response.body().getEvalMhsf4();
ipk_cap = new String[list.size()];
ipk_kat = new String[list.size()];
sks_cap = new String[list.size()];
sks_kat = new String[list.size()];
catatan = new String[list.size()];
semester = new String[list.size()];
for (int i =0;i<list.size();i++) {
ipk_cap[i] = list.get(i).getIpkMhs();
ipk_kat[i] = list.get(i).getKategoriIpk();
sks_cap[i] = String.valueOf(list.get(i).getSksMhs());
sks_kat[i] = list.get(i).getKategoriSks();
catatan[i] = list.get(i).getCatatan();
semester[i] = list.get(i).getSemester();
}
ArrayList data = new ArrayList<DataNote>();
for (int i = 0; i < list.size(); i++)
{
data.add(
new DataNote
(
ipk_cap[i],
ipk_kat[i],
sks_cap[i],
sks_kat[i],
catatan[i],
semester[i]
));
}
mListadapter = new form_mhs_04_fragment2.ListAdapter(data);
listview.setAdapter(mListadapter);
}
}
#Override
public void onFailure(Call<ListForm4Response> call, Throwable t) {
Toast.makeText(getActivity().getBaseContext(), "Koneksi Jaringan Bermasalah", Toast.LENGTH_SHORT).show();
Log.e("debug", "onFailure: ERROR > " + t.toString());
Intent intent = new Intent(getActivity().getBaseContext(), Form_Mhs_Menu.class);
getActivity().startActivity(intent);
}
});
}
and this is my Datanote
package com.example.bimbinganpasi.Form_04.adapter;
public class DataNote {
String ipkkat,ipkcap,skskat,skscap,catatan,semester;
public DataNote(String ipkcap, String ipkkat, String skscap, String skskat,String catatan ,String semester) {
this.ipkkat = ipkkat;
this.ipkcap = ipkcap;
this.skskat = skskat;
this.skscap = skscap;
this.catatan = catatan;
this.semester = semester;
}
public String getIpkkat() {
return ipkkat;
}
public String getIpkcap() {
return ipkcap;
}
public String getSkskat() {
return skskat;
}
public String getSkscap() {
return skscap;
}
public String getCatatan() {
return catatan;
}
public String getSemester() {
return semester;
}
}
try adding else to set default background color :
if(holder.textViewSKSkat.getText().equals("kritis") || holder.textViewSKSkat.getText().equals("kurang")){
holder.textViewSKSkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
} else {
holder.textViewSKSkat.setTextColor(Color.rgb(0,0,0)); //TODO : SET DEFAULT COLOR
}
if(holder.textViewIPKkat.getText().equals("kritis") || holder.textViewIPKkat.getText().equals("kurang")){
holder.textViewIPKkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
} else {
holder.textViewIPKkat.setTextColor(Color.rgb(0,0,0)); //TODO : SET DEFAULT COLOR
}
In My Case i tried this code..
holder.textview.setColor(ContextCompat.getColor(YourActivity.this,R.color.colorPrimary));

Setter/Getter method not working

Hi I am having a problem accessing variables/methods in my view class from my main activity. I just need to return the turns int from GameView.java and be able to access it in MainActivity and then insert it into my database. I try to use GameView mGameView = new GameView(getApplicationContext()); but this doesn't work and I can't access any methods from GameView with this.
My GameView class:
public class GameView extends View {
int mcolumns = 5;
int mrows = 5;
private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
private GestureDetector mGestureDetector;
Random rand = new Random();
int sizeSqX;
int sizeSqY;
int sizeSq;
int turns = 0;
Paint bgPaint;
public GameView(Context context) {
super(context);
init();
}
private void init() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setColor(0xff0000ff);
mGame.gridCopy();
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
int num = rand.nextInt(3) + 1;
for (int turns = 1; turns < num; turns++) {
mGame.rotateRight(col, row);
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
sizeSqX = getWidth() / mcolumns;
sizeSqY = getHeight() / mrows;
if (sizeSqX < sizeSqY) {
sizeSq = sizeSqX;
}
else {
sizeSq = sizeSqY;
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
int cellContent;
int square = 140;
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
cellContent = mGame.getGridElem(col,row);
if (cellContent == 1) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
if (cellContent == 65 && mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
}
}
else if (cellContent == 2) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
}
}
else if (cellContent == 3) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
}
}
else {
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
}
canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(70);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int column = getColTouched(event.getX());
int row = getRowTouched(event.getY());
try {
mGame.rotateRight(column, row);
System.out.println(mcolumns);
mGame.checkWin();
if (mGame.checkWin()) {
System.out.println("check win works");
invalidate();
}
invalidate();
}
catch (ArrayIndexOutOfBoundsException err) {
System.out.println("User has pressed outside game grid - exception caught");
}
turns++;
return super.onTouchEvent(event);
}
public int getColTouched(float x) {
return (int) (x / sizeSq);
}
public int getRowTouched(float y) {
return (int) (y / sizeSq);
}
public int getTurns() {
return turns;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private int mcolumns;
private int mrows;
DatabaseHelper myDb;
String test = "test data";
int turns;
static Context appcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appcon = this;
myDb = new DatabaseHelper(this);
}
public void runGame(View view){
Intent intent = new Intent(this, GameViewActivity.class);
startActivity(intent);
}
public void runInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void setTurns() {
GameView mGameView = new GameView(getApplicationContext());
this.turns = mGameView.turns;
System.out.println("Turns: " + Integer.toString(turns));
}
public void AddData() {
boolean isInserted = myDb.insertData(Integer.toString(turns));
if(isInserted == true) {
System.out.println("Data inserted");
}
else {
System.out.println("Data NOT inserted");
}
}
}
In MainAcivity, inside setTurns()
Replace this
this.turns = mGameView.turns; //you can't access this variable directly
with
this.turns = mGameView.getTurns(); // Calling the public method getTurns()
please see this answer for explanation about Access modifiers in Java
There are two ways to fix this.
1. Preferred way:
Add a new Method in GameView class
public int getTurns() {
return turns;
}
And use this method where you want to access turns like:
this.turns = mGameView.getTurns();
2. Bad way:
Make turns variable public.

Cannot set value to textview in runonuithread

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 create a RecyclerView in Fragment but while reloading data RecyclerView does not maintains state.

//I have created RecycleView in Fragment as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_shop, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
stackView = (RelativeLayout) view.findViewById(R.id.stack_view);
firstStack = (CustomImageView) view.findViewById(R.id.firstStack);
secondStack = (CustomImageView) view.findViewById(R.id.secondStack);
thirdStack = (CustomImageView) view.findViewById(R.id.thirdStack);
stackTopGap = view.findViewById(R.id.view);
new Handler().post(new Runnable() {
#Override
public void run() {
firstStack.getLayoutParams().width = stackView.getWidth() - 40;
secondStack.getLayoutParams().width = stackView.getWidth() - 80;
thirdStack.getLayoutParams().width = stackView.getWidth() - 120;
width = thirdStack.getLayoutParams().width;
recyclerView.getLayoutParams().height = recyclerView.getHeight() - (firstStack.getHeight() + stackTopGap.getHeight());
stackView.getLayoutParams().height = firstStack.getHeight();
}
});
recyclerView.setHasFixedSize(true);
linearLayoutManager=new LinearLayoutManager(getActivity()) {
#Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
// A good idea would be to create this instance in some initialization method, and just set the target position in this method.
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(getContext()) {
#Override
public PointF computeScrollVectorForPosition(int targetPosition) {
//int yDelta = calculateCurrentDistanceToPosition(targetPosition);
return new PointF(0, 200);
}
// This is the important method. This code will return the amount of time it takes to scroll 1 pixel.
// This code will request X milliseconds for every Y DP units.
#Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 7 / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 7, displayMetrics);
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(final RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
final int positionView = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (dy > 0) {
if (positionView >= 2) {
final View view = recyclerView.getChildAt(2);
if (view != null && recyclerView.getChildAdapterPosition(view) == positionView) {
TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 200, 0);
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
if (counter == 0) {
if (recyclerView.getAdapter().getItemCount() - 4 >= positionView) {
createStackImageView();
}
if (stackView.getChildAt(1) != null) {
//stackView.getChildAt(1).setScaleX(1.5f);
}
counter++;
}
recyclerView.smoothScrollToPosition(positionView);
}
#Override
public void onAnimationEnd(Animation animation) {
view.clearAnimation();
stackView.requestLayout();
stackView.removeView(stackView.getChildAt(1));
stackView.invalidate();
try {
for (int i = 1; i < 4; i++) {
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(positionView + i))
.into((ImageView) stackView.getChildAt(i));
}
} catch (IndexOutOfBoundsException | NullPointerException | IllegalArgumentException ex) {
ex.printStackTrace();
}
counter = 0;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
translateAnimation.setDuration(150);
view.setAnimation(translateAnimation);
}
}
for (int i = stackView.getChildCount() - 1; i >= 2; i--) {
ResizeAnimation resizeAnimation = new ResizeAnimation(stackView.getChildAt(i));
resizeAnimation.setHeights(stackView.getChildAt(i).getHeight(), stackView.getChildAt(i - 1).getHeight());
resizeAnimation.setWidths(stackView.getChildAt(i).getWidth(), stackView.getChildAt(i - 1).getWidth());
resizeAnimation.setDuration(200);
stackView.getChildAt(i).startAnimation(resizeAnimation);
}
} else if (dy < 0) {
final int position = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (position == imageList.size() - 1) {
stackView.removeView(firstStack);
stackView.addView(firstStack);
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(1).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 1))
.into((ImageView) stackView.getChildAt(1));
} else if (position == imageList.size() - 2) {
stackView.removeView(secondStack);
stackView.addView(secondStack);
secondStack.getLayoutParams().height = firstStack.getHeight() - 20;
secondStack.getLayoutParams().width = firstStack.getWidth() - 40;
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(2).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 2))
.into((ImageView) stackView.getChildAt(2));
} else if (position == imageList.size() - 3) {
stackView.removeView(thirdStack);
stackView.addView(thirdStack);
thirdStack.getLayoutParams().height = secondStack.getHeight() - 20;
thirdStack.getLayoutParams().width = secondStack.getWidth() - 40;
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(3).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 3))
.into((ImageView) stackView.getChildAt(3));
} else {
stackView.removeView(firstStack);
stackView.addView(firstStack);
stackView.invalidate();
stackView.requestLayout();
}
}
}
});
return view;
}
//In validateToken method data is taken from the json and set to adapter as follows.
private void validateToken() {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (new ConnectionManager(getActivity()).isConnectedToInternet()) {
final SweetAlertDialog pDialog = new AlertDIalogMessage().showProgressDialog(getActivity(), "Loading...");
if (sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, "token_invalid").equals("token_invalid")) {
Utils.setTokenInfo(getActivity(), pDialog, new AccessTokenInfoHolder() {
#Override
public void setAcessTokenInfo(String accessToken, String expires_in, String token_type) {
Log.e("Access Token", accessToken);
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//do nothing here since the case unauthorized will not arrive for the first time
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
shoppageInfoList = getShopPageContent(data);
//set the adapter after loading data from url
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
});
} else {
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//this method is invoked when unauthorized response come from server
Utils.setTokenInfo(getActivity(), pDialog, new AccessTokenInfoHolder() {
#Override
public void setAcessTokenInfo(String accessToken, String expires_in, String token_type) {
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//do nothing here since the case unauthorized will not arrive for the first time
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
List<ShoppageInfo> shoppageInfoList = getShopPageContent(data);
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
});
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
List<ShoppageInfo> shoppageInfoList = getShopPageContent(data);
//set the adapter after loading data from url
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
} else {
new SweetAlertDialog(getActivity(), SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No internet connection!")
.show();
}
}
No in onResume method i called validate token as follows:
#Override
public void onResume() {
super.onResume();
validateToken();
}
//Now when I call some activity from this fragment and come back with back pressed validate method is called and RecyclerView adapter is reloaded. Now what I want is to maintain the state of RecyclerView such that when I came back from activity RecyclerView stays in the scroll position from when activity is called. But problem for me is it always come from the start. I also see some Stack Overflow post and they suggest me to use Parceable but i don't get any benefit. Is is doing nothing.
Can try this.
You need to maintain an identifier for each row. Then save the first visible row's identifier before you go to the activity. Then when you come back you select that particular row again.

Categories

Resources