Undeclared identifie trying to make a reflection token - reflection

I'm gettin "undeclared identifier" in this line:
// set the rest of the contract variables
wannaSwapRouterV2 = _wannaSwapRouterV2;
Not sure exactly what I need to change. Full code:
contract TOKEN is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000 * 10**6 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "TOKEN";
string private _symbol = "TOKEN";
uint8 private _decimals = 9;
uint256 public _taxFee = 5;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 5;
uint256 private _previousLiquidityFee = _liquidityFee;
IWannaSwapRouterV2 public immutable wannaswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 5000000 * 10**6 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 500000 * 10**6 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () public {
_rOwned[_msgSender()] = _rTotal;
IWannaSwapRouterV2 _wannaSwapRouterV2 = IWannaSwapRouterV2(0xa3a1eF5Ae6561572023363862e238aFA84C72ef5);
// Create a uniswap pair for this new token
IWannaSwapPair = IWannaSwapFactory(_wannaSwapRouterV2.factory())
.createPair(address(this), _wannaSwapRouterV2.WETH());
// set the rest of the contract variables
wannaSwapRouterV2 = _wannaSwapRouterV2;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = wannaswapV2Router.WETH();
_approve(address(this), address(wannaswapV2Router), tokenAmount);
// make the swap
wannaswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(wannaswapV2Router), tokenAmount);
// add the liquidity
wannaswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}

You have a typo in that line.
You declared IWannaSwapRouterV2 public immutable wannaswapV2Router;
Then you want to assign _wannaSwapRouterV2 to wannaSwapRouterV2

Related

Filter based on user input - LiveData, Recycler, RoomView

I have an SQLite Database for my Android App. Database has a table for properties , and another table for the repairs at each property.
Table repairs :
#Entity(tableName = "repairs",
indices = {#Index(value = "repairID", unique = true), #Index("repairPropID")})
public class MYRepairs
{
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "repid")
public int id;
#ColumnInfo(name = "repairID")
#NonNull
public String repairID;
#ColumnInfo(name = "repairPropID")
public int repairPropID;
}
...
and then RepairsDao.java
#Dao
public interface MyRepairsDao
{
#Query("SELECT * FROM repairs WHERE repid = :repid LIMIT 1")
MYRepairs findRepairById(String repid);
#Query("SELECT * FROM repairs WHERE repairPropID = :repairPropID")
MYRepairs findRepairByPropID(int repairPropID);
#Query("SELECT * FROM repairs ORDER BY repairPropID ASC")
LiveData<List<MYRepairs>> getAllRepairs();
#Query("SELECT * FROM repairs WHERE repairPropID = :repairPropID")
LiveData<List<MYRepairs>> getPropertyRepairs(int repairPropID);
}
In the ViewModel:
public class repairViewModel extends AndroidViewModel
{
private MyRepairsDao myRepairDao;
private LiveData<List<MYRepairs>> repairLiveData;
private LiveData<List<MYRepairs>> repairPropertyLiveData;
private LiveData<String> filterLiveData = new MutableLiveData<String>();
public repairViewModel(#NonNull Application application)
{
super(application);
myRepairDao = DogwoodDatabase.getDatabase(application).repairDao();
repairLiveData = myRepairDao.getAllRepairs();
repairPropertyLiveData = myRepairDao.getPropertyRepairs(propertyID);
}
public LiveData<List<MYRepairs>> getAllRepairs()
{
return repairLiveData;
}
public LiveData<List<MYRepairs>> getPropertyRepairs(int propertyID)
{
return repairPropertyLiveData;
}
And in the RecyclerView.Adapter:
public class repairListAdapter extends RecyclerView.Adapter<repairListAdapter.RepairViewHolder>
{
#NonNull
#Override
public repairListAdapter.RepairViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
final View itemView = layoutInflater.inflate(R.layout.repaircontent, parent, false);
return new repairListAdapter.RepairViewHolder(itemView);
}
In the repairFragment - we only want to view the repairs for a user selected property. Property Code propertyID is received by the repairFragement. It is known to the initData()
public class repairFragment extends Fragment
{
private repairListAdapter repairListAdapter;
private repairViewModel repairViewModel;
public void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
propertyID = getArguments().getString("ARG_PROPNUM_ID");
propNumID = Integer.parseInt(propertyID);
initData();
}
private void initData()
{
Log.e ("INIT", "ID is " + propertyID);
repairViewModel = new
ViewModelProvider(this).get(repairViewModel.class);
repairViewModel.getPropertyRepairs(propertyID).observe(this, new Observer<List<MYRepairs>>()
{
#Override
public void onChanged(#Nullable List<MYRepairs> MYRepairs)
{
repairListAdapter.setMYRepairList(MYRepairs);
}
});
}
This returns NO RECORDS.
In an ideal world, my properties would have no repairs, but I do not live in that world!
I have scoured this board for help on filtering .
Can you help me with how to filter for only the repairs for a user selected property (propertyID).
Thanks, Rachael
What you wanted to do is the following:
public LiveData<List<MYRepairs>> getPropertyRepairs() {
return repairPropertyLiveData;
}
And
private MutableLiveData<String> selectedPropertyId = new MutableLiveData<>();
private final repairPropertyLiveData = Transformations.switchMap(selectedPropertyId, (id) -> {
return myRepairDao.getPropertyRepairs(id);
});
public void updateSelectedProperty(String propertyId) {
selectedPropertyId.setValue(propertyId);
}
This way, you don't end up with new subscriptions that were not properly invalidated in case you were to select a different property id later.
Oh my! I figured it out.
In repairViewModel:
public LiveData<List<MYRepairs>> getPropertyRepairs(int propertyID)
{
repairPropertyLiveData = myRepairDao.getPropertyRepairs(propertyID);
return repairPropertyLiveData;
}

how to override the LocaleContext in Spring MVC

I'm trying to customise the LocaleContext in Spring MVC to store some additional information.
I've set up a custom localeResolver, which works okay so far. But I'm not sure how to customise the locale context itself.
I wrote this class:
/**
* Creates a store aware localisation context
*/
public class SimpleStoreAwareLocaleContext extends SimpleTimeZoneAwareLocaleContext {
private Location location;
public SimpleStoreAwareLocaleContext(Locale locale, TimeZone timeZone) {
super(locale, timeZone);
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
But how do I get this to be the default LocaleContext on the LocaleContextHolder?
So when I call this, I want to get an instance of my locale context back..
LocaleContextHolder.getLocaleContext();
Is there a filter or something I need to override?
Also, just so I make sure my understanding is correct - is the LocaleContext thread local? So it should be different for each user right?
Thanks!
Ok, no answers, but I mostly have this working so here's what I did. I basically copy & pasted large amounts of the CookieLocaleResolver because there were private methods that I needed, and a few other reasons. But I came up with my own version of the cookie resolver, and modified the formatting in the cookie value to support more parameters:
/**
* <p>The custom locale resolver will also handle setting up the customer's local store in the
* locale context.</p>
*
*
*/
public class StoreLocaleResolver extends CookieLocaleResolver {
private static Logger logger = LogManager.getLogger(StoreLocaleResolver.class.getName());
private Location defaultLocation;
private Location location;
#Autowired
private LocationService locationService;
/**
* The name of the request attribute that holds the Location Information.
* <p>Only used for overriding a cookie value if the locale has been
* changed in the course of the current request!
* <p>Use {#code RequestContext(Utils).getTimeZone()}
* to retrieve the current time zone in controllers or views.
* #see org.springframework.web.servlet.support.RequestContext#getTimeZone
* #see org.springframework.web.servlet.support.RequestContextUtils#getTimeZone
*/
public static final String LOCAL_STORE_REQUEST_ATTRIBUTE_NAME = CookieLocaleResolver.class.getName() + ".LOCAL_STORE";
#Override
public void setLocaleContext(HttpServletRequest request, HttpServletResponse response, LocaleContext localeContext) {
//super.setLocaleContext(request, response, localeContext);
Locale locale = null;
TimeZone timeZone = null;
Location location = null;
if (localeContext != null) {
removeCookie(response);
if (localeContext instanceof SimpleStoreAwareLocaleContext) {
locale = localeContext.getLocale();
location = ((SimpleStoreAwareLocaleContext) localeContext).getLocation();
timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
}
StringBuilder bud = new StringBuilder();
if (locale != null)
bud.append("locale:" + locale);
if (timeZone != null)
{
bud.append("::");
bud.append("timezone:" + timeZone.getID());
}
if (location != null)
{
bud.append("::");
bud.append("location:" + location.getExternalIdentifier());
}
String cookieValue = bud.toString();
addCookie(response, bud.toString());
}
else {
removeCookie(response);
}
request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
(locale != null ? locale: determineDefaultLocale(request)));
request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
(timeZone != null ? timeZone : determineDefaultTimeZone(request)));
request.setAttribute(LOCAL_STORE_REQUEST_ATTRIBUTE_NAME,
(location != null ? location: determineDefaultLocalStore(request)));
}
#Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
SimpleStoreAwareLocaleContext localeContext = new SimpleStoreAwareLocaleContext(locale, null);
Location loc = (Location)request.getAttribute(StoreLocaleResolver.LOCAL_STORE_REQUEST_ATTRIBUTE_NAME);
if (loc != null)
{
localeContext.setLocation(loc);
}
setLocaleContext(request, response, (locale != null ? localeContext : null));
}
#Override
public Locale resolveLocale(HttpServletRequest request) {
parseLocaleCookieIfNecessary(request);
return (Locale) request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME);
}
#Override
public LocaleContext resolveLocaleContext(final HttpServletRequest request) {
parseLocaleCookieIfNecessary(request);
return new StoreAwareLocaleContext() {
#Override
public Locale getLocale() {
return (Locale) request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME);
}
#Override
public TimeZone getTimeZone() {
return (TimeZone) request.getAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME);
}
#Override
public Location getLocation() {
return (Location) request.getAttribute(LOCAL_STORE_REQUEST_ATTRIBUTE_NAME);
}
};
}
// copied from the parent class and extended to support parsing out the store location.
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
// Retrieve and parse cookie value.
Cookie cookie = WebUtils.getCookie(request, getCookieName());
Locale locale = null;
TimeZone timeZone = null;
if (cookie != null) {
String value = cookie.getValue();
Map<String, String> params = new HashMap<String, String>();
String[] tokens1 = value.split("::");
for (String token: tokens1){
String[] tokens2 = token.split(":");
params.put(tokens2[0], tokens2[1]);
}
String localeString = params.get("locale");
String timezoneString = params.get("timezone");
String locationString = params.get("location");
if (localeString != null)
{
locale = StringUtils.parseLocaleString(localeString);
}
if (timezoneString != null)
{
timeZone = StringUtils.parseTimeZoneString(timezoneString);
}
if (locationString != null)
{
location = locationService.findForLocaleContext(locationString, false);
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
"'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
}
}
request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
(locale != null ? locale: determineDefaultLocale(request)));
request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
(timeZone != null ? timeZone : determineDefaultTimeZone(request)));
request.setAttribute(LOCAL_STORE_REQUEST_ATTRIBUTE_NAME,
(location != null ? location : determineDefaultLocalStore(request)));
}
}
/**
* Determine the default time zone for the given request,
* Called if no TimeZone cookie has been found.
* <p>The default implementation returns the specified default time zone,
* if any, or {#code null} otherwise.
* #param request the request to resolve the time zone for
* #return the default time zone (or {#code null} if none defined)
* #see #setDefaultTimeZone
*/
protected Location determineDefaultLocalStore(HttpServletRequest request) {
return getDefaultLocation();
}
#Override
protected Locale getDefaultLocale() {
logger.debug("Getting the default locale");
LocaleContextHolder.getLocaleContext();
return super.getDefaultLocale();
}
public Location getDefaultLocation() {
return defaultLocation;
}
public void setDefaultLocation(Location defaultLocation) {
this.defaultLocation = defaultLocation;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
The other main class is an extended LocaleChangeInterceptor that allows me to change the local store by adding a parameter to any controller URL.
/**
* <p>The custom locale resolver will also handle setting up the customer's local store in the
* locale context.</p>
*
*
*/
#Component
public class StoreLocaleChangeInterceptor extends LocaleChangeInterceptor {
private static Logger logger = LogManager.getLogger(StoreLocaleChangeInterceptor.class.getName());
/**
* Default name of the store locale specification parameter: "store".
*/
public static final String DEFAULT_STORE_PARAM_NAME = "store";
private String storeParamName = DEFAULT_STORE_PARAM_NAME;
#Autowired
private LocationService locationService;
public String getStoreParamName() {
return storeParamName;
}
public void setStoreParamName(String storeParamName) {
this.storeParamName = storeParamName;
}
public LocationService getLocationService() {
return locationService;
}
public void setLocationService(LocationService locationService) {
this.locationService = locationService;
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException {
String newLocale = request.getParameter(getParamName());
String newStore = request.getParameter(this.storeParamName);
if (newStore != null || newLocale != null) {
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
if (localeResolver instanceof StoreLocaleResolver)
{
Location location = locationService.findByIdentifier(newStore);
if (location != null) {
((StoreLocaleResolver) localeResolver).setLocation(location);
request.setAttribute(StoreLocaleResolver.LOCAL_STORE_REQUEST_ATTRIBUTE_NAME, location);
}
if (newLocale != null)
{
localeResolver.setLocale(request, response, StringUtils.parseLocaleString(newLocale));
}else
{
Locale currentLocale = localeResolver.resolveLocale(request);
localeResolver.setLocale(request, response, currentLocale);
}
}
}
// Proceed in any case.
return true;
}
}
Then from the LocaleContextHolder I have to downcast to the context type (which is now an interface).
#ModelAttribute("myStore")
protected Location getCurrentStore() {
LocaleContext ctx = LocaleContextHolder.getLocaleContext();
if (StoreAwareLocaleContext.class.isAssignableFrom(ctx.getClass())){
return ((StoreAwareLocaleContext) ctx).getLocation();
}else
{
return null;
}
}

Controlling more than one properties for custom component on scenebuilder

I cannot see the old values of a property of custom component on Scene Builder.
I want to get the old value of "Speed Unit Type" to change the Min/Max values accordingly.
Maybe I can use static Min / Max values and bind these to "Speed Unit Type". But just wonderwhether it is possible to use old values at design tima on SB.
public static enum SpeedUnitType {KILO_METERS_PER_HOUR,METERS_PER_SECOND,DATA_MILES_PER_HOUR}
public static final int SPEED_MAX_DEFAULT_VALUE = 1000;
public static final int SPEED_MAX_LIMIT_VALUE = 999;
public static final double SPEED_MIN_LIMIT_VALUE = -100;
private final IntegerProperty minValue = new SimpleIntegerProperty(0);
private final IntegerProperty maxValue = new SimpleIntegerProperty(Integer.MAX_VALUE);
private final IntegerProperty value = new SimpleIntegerProperty(0);
private SpeedUnitType _speedUnit = SpeedUnitType.KILO_METERS_PER_HOUR;
private ObjectProperty<SpeedUnitType> speedUnitTypeProperty ;
public final SpeedUnitType getSpeedUnitType() {
return null == speedUnitTypeProperty ? _speedUnit : speedUnitTypeProperty.get();
}
public final void setSpeedUnitType(final SpeedUnitType UNIT) {
if (null == speedUnitTypeProperty) {
_speedUnit = UNIT;
} else {
speedUnitTypeProperty.set(UNIT);
}
}
public final ObjectProperty<SpeedUnitType> speedUnitTypeProperty() {
if (null == speedUnitTypeProperty) {
speedUnitTypeProperty = new SimpleObjectProperty<>(this, "speedUnitTypeProperty", _speedUnit);
}
return speedUnitTypeProperty;
}
public Speed() {
this.construct();
}
public void setMinValue(int min){ this.minValue.set(min); }
public int getMinValue() { return this.minValue.get(); }
public IntegerProperty minValueProperty() { return this.minValue;}
public void setMaxValue(int max) { this.maxValue.set(max);}
public int getMaxValue(){ return this.maxValue.get();}
public IntegerProperty maxValueProperty() { return this.maxValue; }
public final int getValue() { return value.get(); }
public final void setValue(final int VALUE) { value.set(VALUE);}
public final IntegerProperty valueProperty() {return value;}
private void construct()
{
this.maxValueProperty().addListener((observable, oldValue, newValue) ->
{
try
{
System.out.println("maxValueProperty --> The value was changed from " + oldValue.toString() + " to " + newValue.toString());
}
catch (Exception e)
{
System.err.println("Exception: " + e.getLocalizedMessage());
setText("ERROR");
}
});
speedUnitTypeProperty().addListener((observable, oldValue, newValue) -> {
this.convertSpeedUnit(oldValue, newValue);
});
// this.maxValueProperty().bind(Bindings.add(10, this.minValueProperty())); test to bind property min to property max
}
// ******************** Utility Methods ***********************************
public void convertSpeedUnit(SpeedUnitType oldValue, SpeedUnitType newValue)
{
if (oldValue == null)
return;
if (oldValue == newValue){}
else{
switch (oldValue){
case KILO_METERS_PER_HOUR:
System.out.println("convertSpeedUnit::formerUnit - KILO_METERS_PER_HOUR");
switch (newValue){
case METERS_PER_SECOND:
System.out.println("convertSpeedUnit::currentUnit - METERS_PER_SECOND");
setMinValue(10);
setMaxValue(20);
break;
case DATA_MILES_PER_HOUR:
System.out.println("convertSpeedUnit::currentUnit - DATA_MILES_PER_HOUR");
setMinValue(11);
setMaxValue(21);
break;
}
break;
case METERS_PER_SECOND:
System.out.println("convertSpeedUnit::formerUnit - METERS_PER_SECOND");
switch (newValue){
case KILO_METERS_PER_HOUR:
System.out.println("convertSpeedUnit::currentUnit - KILO_METERS_PER_HOUR");
setMinValue(12);
setMaxValue(22);
break;
case DATA_MILES_PER_HOUR:
System.out.println("convertSpeedUnit::currentUnit - DATA_MILES_PER_HOUR");
setMinValue(13);
setMaxValue(23);
break;
}
break;
case DATA_MILES_PER_HOUR:
System.out.println("convertSpeedUnit::formerUnit - DATA_MILES_PER_HOUR");
switch (newValue){
case KILO_METERS_PER_HOUR:
System.out.println("convertSpeedUnit::currentUnit - KILO_METERS_PER_HOUR");
setMinValue(34);
setMaxValue(45);
break;
case METERS_PER_SECOND:
System.out.println("convertSpeedUnit::currentUnit - METERS_PER_SECOND");
setMinValue(56);
setMaxValue(67);
break;
}
break;
}
}
}

How to get the value of a map from a key which is a POJO

I got the following function
Map<MyClass, String> someFunction() {
Map<MyClass, String> result = new HashMap<>();
return result.put(new MyClass("someString"), "someOtherString"));
}
The implementation of MyClass looks like the following:
public class MyClass{
String string;
public MyClass(String string) {
this.string = string;
}
public void setString(String string) {
this.string = string;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((string== null) ? 0 : string.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MyClass other = (MyClass) obj;
if (string== null) {
if (other.string!= null) {
return false;
}
} else if (!string.equals(other.string)) {
return false;
}
return true;
}
}
In my test I am doing the following:
#Test
public void test() {
Map<MyClass, String> outcome = classUnderTest.someFunction();
assertThat(outcome.get(new MyClass("someString")), is("someOtherString"));
}
But this test fails, because actual is null.
If I try the following:
assertThat(outcome.keySet(), hasItem(MY_CLASS));
this also fails, telling me, that these are different intantiations. I even tried to debug my test, but it never reaches the equals method. Can you tell me what is happening here?
Are you sure, that your method doesn't modify the objecT? I think, that someFunction replaces the string in MyClass. That causes that your object of MyClass return another hashCode.
A HashMap works like that:
put:
compute hashCode of the key. Store value under that hashCode
get:
compute hashCode of the key. Search for a value with that hashCode. If there is a value, then maybe call equals.
So: never use mutable values as key! Otherwise, you may lose your data (or make it difficult to resolve)
Just try to execute this test, it should be green
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class SomeTest {
Map<MyClass, String> someFunction() {
Map<MyClass, String> result = new HashMap<>();
result.put(new MyClass("someString"), "someOtherString");
return result;
}
#Test
public void test() {
Map<MyClass, String> outcome = someFunction();
assertThat(outcome.get(new MyClass("someString")), is("someOtherString"));
}
public static class MyClass {
String string;
public MyClass(String string) {
this.string = string;
}
public void setString(String string) {
this.string = string;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((string == null) ? 0 : string.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MyClass other = (MyClass) obj;
if (string == null) {
if (other.string != null) {
return false;
}
} else if (!string.equals(other.string)) {
return false;
}
return true;
}
}
}
but if you modify MyClass object after it was added to Map, the test became red:
Map<MyClass, String> someFunction() {
Map<MyClass, String> result = new HashMap<>();
MyClass key = new MyClass("someOldString");
result.put(key, "someOtherString");
key.setString("someString");
return result;
}
In your function you are returning null
From the JavaDoc for HashMap:
public V put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Specified by:
put in interface Map<K,V>
Overrides:
put in class AbstractMap<K,V>
Parameters:
key - key with which the specified value is to be associated
value - value to be associated with the specified key
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
put() returns what used to be there, not what you just put there

RSS Feeder Android Application

I'm building android app for Show RSS feeds, in one activity ,
I write the RSS Link in EditText and click button, then appear the RSS feeds (the news).
When i enter the RSS link and click the button in the first time the appear the news normally , but my problem is when I Enter a new link & press button: the news of the new link appear under the old News (news of the first link i have been entered in the EditText).
But I want to erase the old news and appear the RSS feed of the new link when i press button.
Any idea?
Thanks in advance.
My code:
In MainActivity:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static String rss_url = "http://www.thehindu.com/news/cities/chennai/chen-health/?service=rss";
ProgressDialog progressDialog;
Handler handler = new Handler();
RSSListView list;
RSSListAdapter adapter;
ArrayList<RSSNewsItem> newsItemList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
list = new RSSListView(this);
adapter = new RSSListAdapter(this);
list.setAdapter(adapter);
list.setOnDataSelectionListener(new OnDataSelectionListener() {
public void onDataSelected(AdapterView parent, View v,
int position, long id) {
RSSNewsItem curItem = (RSSNewsItem) adapter.getItem(position);
String curTitle = curItem.getTitle();
Toast.makeText(getApplicationContext(),
"Selected : " + curTitle, 1000).show();
}
});
newsItemList = new ArrayList<RSSNewsItem>();
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
mainLayout.addView(list, params);
final EditText edit01 = (EditText) findViewById(R.id.edit01);
edit01.setText(rss_url);
Button show_btn = (Button) findViewById(R.id.show_btn);
show_btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String inputStr = edit01.getText().toString();
showRSS(inputStr);
}
});
}
private void showRSS(String urlStr) {
try {
progressDialog = ProgressDialog.show(this, "RSS Refresh",
"RSS Lodeing..", true, true);
RefreshThread thread = new RefreshThread(urlStr);
thread.start();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
class RefreshThread extends Thread {
String urlStr;
public RefreshThread(String str) {
urlStr = str;
}
public void run() {
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
URL urlForHttp = new URL(urlStr);
InputStream instream = getInputStreamUsingHTTP(urlForHttp);
// parse
Document document = builder.parse(instream);
int countItem = processDocument(document);
Log.d(TAG, countItem + " news item processed.");
// post for the display of fetched RSS info.
handler.post(updateRSSRunnable);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public InputStream getInputStreamUsingHTTP(URL url) throws Exception {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
int resCode = conn.getResponseCode();
Log.d(TAG, "Response Code : " + resCode);
InputStream instream = conn.getInputStream();
return instream;
}
private int processDocument(Document doc) {
newsItemList.clear();
Element docEle = doc.getDocumentElement();
NodeList nodelist = docEle.getElementsByTagName("item");
int count = 0;
if ((nodelist != null) && (nodelist.getLength() > 0)) {
for (int i = 0; i < nodelist.getLength(); i++) {
RSSNewsItem newsItem = dissectNode(nodelist, i);
if (newsItem != null) {
newsItemList.add(newsItem);
count++;
}
}
}
return count;
}
private RSSNewsItem dissectNode(NodeList nodelist, int index) {
RSSNewsItem newsItem = null;
try {
Element entry = (Element) nodelist.item(index);
Element title = (Element) entry.getElementsByTagName("title").item(
0);
Element link = (Element) entry.getElementsByTagName("link").item(0);
Element description = (Element) entry.getElementsByTagName(
"description").item(0);
NodeList pubDataNode = entry.getElementsByTagName("pubDate");
if (pubDataNode == null) {
pubDataNode = entry.getElementsByTagName("dc:date");
}
Element pubDate = (Element) pubDataNode.item(0);
Element author = (Element) entry.getElementsByTagName("author")
.item(0);
Element category = (Element) entry.getElementsByTagName("category")
.item(0);
String titleValue = null;
if (title != null) {
Node firstChild = title.getFirstChild();
if (firstChild != null) {
titleValue = firstChild.getNodeValue();
}
}
String linkValue = null;
if (link != null) {
Node firstChild = link.getFirstChild();
if (firstChild != null) {
linkValue = firstChild.getNodeValue();
}
}
String descriptionValue = null;
if (description != null) {
Node firstChild = description.getFirstChild();
if (firstChild != null) {
descriptionValue = firstChild.getNodeValue();
}
}
String pubDateValue = null;
if (pubDate != null) {
Node firstChild = pubDate.getFirstChild();
if (firstChild != null) {
pubDateValue = firstChild.getNodeValue();
}
}
String authorValue = null;
if (author != null) {
Node firstChild = author.getFirstChild();
if (firstChild != null) {
authorValue = firstChild.getNodeValue();
}
}
String categoryValue = null;
if (category != null) {
Node firstChild = category.getFirstChild();
if (firstChild != null) {
categoryValue = firstChild.getNodeValue();
}
}
Log.d(TAG, "item node : " + titleValue + ", " + linkValue + ", "
+ descriptionValue + ", " + pubDateValue + ", "
+ authorValue + ", " + categoryValue);
newsItem = new RSSNewsItem(titleValue, linkValue, descriptionValue,
pubDateValue, authorValue, categoryValue);
} catch (DOMException e) {
e.printStackTrace();
}
return newsItem;
}
Runnable updateRSSRunnable = new Runnable() {
public void run() {
try {
Resources res = getResources();
Drawable rssIcon = res.getDrawable(R.drawable.rss_icon);
for (int i = 0; i < newsItemList.size(); i++) {
RSSNewsItem newsItem = (RSSNewsItem) newsItemList.get(i);
newsItem.setIcon(rssIcon);
adapter.addItem(newsItem);
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and in OnDataSelectionListener class:
public interface OnDataSelectionListener {
public void onDataSelected(AdapterView parent, View v, int position, long id);
}
and in RSSListAdapter:
public class RSSListAdapter extends BaseAdapter {
private Context mContext;
private List<RSSNewsItem> mItems = new ArrayList<RSSNewsItem>();
public RSSListAdapter(Context context) {
mContext = context;
}
public void addItem(RSSNewsItem it) {
mItems.add(it);
}
public void setListItems(List<RSSNewsItem> lit) {
mItems = lit;
}
public int getCount() {
return mItems.size();
}
public Object getItem(int position) {
return mItems.get(position);
}
public boolean areAllItemsSelectable() {
return false;
}
public boolean isSelectable(int position) {
return true;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
RSSNewsItemView itemView;
if (convertView == null) {
itemView = new RSSNewsItemView(mContext, mItems.get(position));
} else {
itemView = (RSSNewsItemView) convertView;
itemView.setIcon(mItems.get(position).getIcon());
itemView.setText(0, mItems.get(position).getTitle());
itemView.setText(1, mItems.get(position).getPubDate());
itemView.setText(2, mItems.get(position).getCategory());
itemView.setText(3, mItems.get(position).getDescription());
}
return itemView;
}
}
and in RSSListView class:
public class RSSListView extends ListView {
/**
* DataAdapter for this instance
*/
private RSSListAdapter adapter;
/**
* Listener for data selection
*/
private OnDataSelectionListener selectionListener;
public RSSListView(Context context) {
super(context);
init();
}
public RSSListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* set initial properties
*/
private void init() {
// set OnItemClickListener for processing OnDataSelectionListener
setOnItemClickListener(new OnItemClickAdapter());
}
/**
* set DataAdapter
*
* #param adapter
*/
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
}
/**
* get DataAdapter
*
* #return
*/
public BaseAdapter getAdapter() {
return (BaseAdapter) super.getAdapter();
}
/**
* set OnDataSelectionListener
*
* #param listener
*/
public void setOnDataSelectionListener(OnDataSelectionListener listener) {
this.selectionListener = listener;
}
/**
* get OnDataSelectionListener
*
* #return
*/
public OnDataSelectionListener getOnDataSelectionListener() {
return selectionListener;
}
class OnItemClickAdapter implements OnItemClickListener {
public OnItemClickAdapter() {
}
public void onItemClick(AdapterView parent, View v, int position,
long id) {
if (selectionListener == null) {
return;
}
// get row and column
int rowIndex = -1;
int columnIndex = -1;
// call the OnDataSelectionListener method
selectionListener.onDataSelected(parent, v, position, id);
}
}
}
and in RSSNewsItem class:
public class RSSNewsItem {
private String title;
private String link;
private String description;
private String pubDate;
private String author;
private String category;
private Drawable mIcon;
/**
* Initialize with icon and data array
*/
public RSSNewsItem() {
}
/**
* Initialize with icon and strings
*/
public RSSNewsItem(String title, String link, String description, String pubDate, String author, String category) {
this.title = title;
this.link = link;
this.description = description;
this.pubDate = pubDate;
this.author = author;
this.category = category;
}
/**
* Set icon
*
* #param icon
*/
public void setIcon(Drawable icon) {
mIcon = icon;
}
/**
* Get icon
*
* #return
*/
public Drawable getIcon() {
return mIcon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
/**
* Compare with the input object
*
* #param other
* #return
*/
public int compareTo(RSSNewsItem other) {
if (title.equals(other.getTitle())) {
return -1;
} else if (link.equals(other.getLink())) {
return -1;
} else if (description.equals(other.getDescription())) {
return -1;
} else if (pubDate.equals(other.getPubDate())) {
return -1;
} else if (author.equals(other.getAuthor())) {
return -1;
} else if (category.equals(other.getCategory())) {
return -1;
}
return 0;
}
}
Finally, in RSSNewsItemView class:
public class RSSNewsItem {
private String title;
private String link;
private String description;
private String pubDate;
private String author;
private String category;
private Drawable mIcon;
/**
* Initialize with icon and data array
*/
public RSSNewsItem() {
}
/**
* Initialize with icon and strings
*/
public RSSNewsItem(String title, String link, String description, String pubDate, String author, String category) {
this.title = title;
this.link = link;
this.description = description;
this.pubDate = pubDate;
this.author = author;
this.category = category;
}
/**
* Set icon
*
* #param icon
*/
public void setIcon(Drawable icon) {
mIcon = icon;
}
/**
* Get icon
*
* #return
*/
public Drawable getIcon() {
return mIcon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
/**
* Compare with the input object
*
* #param other
* #return
*/
public int compareTo(RSSNewsItem other) {
if (title.equals(other.getTitle())) {
return -1;
} else if (link.equals(other.getLink())) {
return -1;
} else if (description.equals(other.getDescription())) {
return -1;
} else if (pubDate.equals(other.getPubDate())) {
return -1;
} else if (author.equals(other.getAuthor())) {
return -1;
} else if (category.equals(other.getCategory())) {
return -1;
}
return 0;
}
}
I think you would need to call adapter.clear() and invalidate your list again using adapter.notifyDataSet() when you click the button.

Resources