My RecyclerView is duplicated every time I open activity - android-recyclerview

I have some problem with my project, and I will be very glad if anyone of you helps me. There is an activity in my app, where the only view is RecyclerView and everytime I open this activity, I need fill it, I do it like that:
RecyclerView templatesRecycler;
private MyRecyclerViewAdapter myRecyclerViewAdapter;
int numberOfColumns = 2;
//
templatesRecycler = (RecyclerView) findViewById(R.id.templatesListView);
updateRecyclerView(MyCollections.getTemplatesTitles());
public void updateRecyclerView(ArrayList<MyTemplate> myTemplates){
templatesRecycler.setHasFixedSize(true);
templatesRecycler.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
myRecyclerViewAdapter = new MyRecyclerViewAdapter(this, myTemplates, this);
templatesRecycler.setAdapter(myRecyclerViewAdapter);
}
I want to use class MyCollections, because there are a lot of RecyclerViews in my app, but I dont want to fill it myself everytime, so I create class MyCollections:
public class MyCollections {
public static ArrayList<MyTemplate> templatesTitles = new ArrayList<>();
public MyCollections(){
templatesTitles.add(new MyTemplate("Люди", R.drawable.ic_people));
templatesTitles.add(new MyTemplate("Транспорт", R.drawable.ic_car));
templatesTitles.add(new MyTemplate("Мебель", R.drawable.ic_furniture));
templatesTitles.add(new MyTemplate("Фоны", R.drawable.ic_background));
templatesTitles.add(new MyTemplate("Предметы", R.drawable.ic_tools));
templatesTitles.add(new MyTemplate("Животные", R.drawable.ic_animal));
templatesTitles.add(new MyTemplate("Природа", R.drawable.ic_nature));
templatesTitles.add(new MyTemplate("Разметка листа", R.drawable.ic_sections));
templatesTitles.add(new MyTemplate("Другое", R.drawable.ic_others));
}
public static ArrayList<MyTemplate> getTemplatesTitles() {
return templatesTitles;
}
}
By the way, here is my MyTemplate class:
public class MyTemplate {
public String titleTemplate;
public int drawableID;
public String getTitleTemplate() {
return titleTemplate;
}
public void setTitleTemplate(String titleTemplate) {
this.titleTemplate = titleTemplate;
}
public int getDrawableID() {
return drawableID;
}
public void setDrawableID(int drawableID) {
this.drawableID = drawableID;
}
public MyTemplate(String titleTemplate, int drawableID){
this.titleTemplate = titleTemplate;
this.drawableID = drawableID;
}
public MyTemplate(){}
}
But here is the problem. Every time I open activity, my RecyclerView duplicates his elements, before I filled RecyclerView myself, and there wasnt such a problem. Please, help me, I am just beginner, so I dont know how I can fix this problem. Thanks!

Related

How to write Xunit test case of factory design pattern code block which is tightly coupled?

I would like to write xunit test case of below method. Could you please suggest alternate design so i can write xunit test case with minimum change in my current project.
public ActionResult Index(int id = 0, AssetFilterType filter = AssetFilterType.All)
{
using (var tracer = new Tracer("AssetController", "Index"))
{
RemoveReturnUrl();
ViewBag.JobId = id;
var response = ContextFactory.Current.GetDomain<EmployeeDomain>().GetEmployeeFilterAsync(id,
CurrentUser.CompanyId, filter); // Not able write unit test case , please suggest alternate design.
return View("View", response);
}
}
current design is as follow
public interface IDomain
{
}
public interface IContext
{
D GetDomain<D>() where D : IDomain;
string ConnectionString { get; }
}
public class ApplicationContext : IContext
{
public D GetDomain<D>() where D : IDomain
{
return (D)Activator.CreateInstance(typeof(D));
}
public string ConnectionString
{
get
{
return "DatabaseConnection";
}
}
}
public class ContextFactory
{
private static IContext _context;
public static IContext Current
{
get
{
return _context;
}
}
public static void Register(IContext context)
{
_context = context;
}
}
//var response = ContextFactory.Current.GetDomain**< EmployeeDomain>**().GetEmployeeFilterAsync(id,
CompanyId, filter);
This line serve purpose to call specific class method i.e GetEmployeeFilterAsync from EmployeeDomain. Although it is very handy and widely used in our application but due to design issue i am not able to write unit
test case.
Could you please suggest design so with the minimum change we can write unit test case.
Don't use the Service Locator anti-pattern, use Constructor Injection instead. I can't tell what AssetDomain is from the OP, but it seems as though it's the dependency that matters. Inject it into the class:
public class ProbablySomeController
{
public ProbablySomeController(AssetDomain assetDomain)
{
AssetDomain = assetDomain;
}
public AssetDomain AssetDomain { get; }
public ActionResult Index(int id = 0, AssetFilterType filter = AssetFilterType.All)
{
using (var tracer = new Tracer("AssetController", "Index"))
{
RemoveReturnUrl();
ViewBag.JobId = id;
var response = AssetDomain.GetAssetFilterAsync(id, CurrentUser.CompanyId, filter);
return View("View", response);
}
}
}
Assuming that AssetDomain is a polymorphic type, you can now write a test and inject a Test Double:
[Fact]
public void MyTest()
{
var testDouble = new AssetDomainTestDouble();
var sut = new ProbablySomeController(testDouble);
var actual = sut.Index(42, AssetFilterType.All);
// Put assertions here
}
step1 : Required library
step 2 : When the application starts , register required domain like
protected void Application_Start()
UnityConfig.RegisterComponents();
Step 3: create one static class and register all your domain
example
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
Initialize domain which will injected in controller
container.RegisterType<IPricingDomain, PricingDomain>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
step 4 :
so you can inject respective interface in constructor
in controller file.
goal : get rid of below any pattern in your project.
and start writing unit test cases.

How to see arguments when creating a new class?

When creating a new class or method I used to be able to see the parameters needed. But, now they don't come up anymore. How do I view parameters when creating a class?
Running the latest windows version.
public class Main {
public static void main(String args[]) {
Case theCase = new Case("Default", "Corsair", "500W");
}
}
public class Case {
private String model;
private String manufacturer;
private String powerSupply;
public Case(String model, String manufacturer, String powerSupply,) {
this.model = model;
this.manufacturer = manufacturer;
this.powerSupply = powerSupply;
}
public void pressPowerButton() {
System.out.println("Power button pressed");
}
public String getModel() {
return model;
}
public String getManufacturer() {
return manufacturer;
}
public String getPowerSupply() {
return powerSupply;
}
}
When making theCase I can't see what my parameters are and have to move to the "Case" class back and forth
You can explicitly call Parameter Info action which is usually mapped to Ctrl/(Cmd) - p.
Nevermind in order to see the parameters as you type you must type them while in the editor without moving your cursor.

Jackson - Deserialize with JsonView

I am trying to restrict which properties from a JSON object are deserialised using Jackson JSONViews. The aim is to use this to prevent consumers of my API from submitting data that they shouldn't.
The problem is, I have either misunderstood JSONViews or I am doing something wrong. See below.
I started trying to do this in Spring but have noticed that even the simple test below doesn't work.
Account Class
public class Account {
#Id
private String id;
private String name;
private List<String> items;
private List<User> users;
#JsonView(AccountViews.Private.class)
public void setId(String id) {
this.id = id;
}
#JsonView(AccountViews.Public.class)
public void setName(String name) {
this.name = name;
}
#JsonView(AccountViews.Public.class)
public void setItems(List<String> items) {
this.items = items;
}
#JsonView(AccountViews.Private.class)
public void setUsers(List<User> users) {
this.users = users;
}
}
Views
public class AccountViews {
public interface Public {}
public interface Private extends Public {}
}
Test
#Test
public void testDeserialization(){
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
Account account = mapper.readerWithView(AccountViews.Public.class).forType(Account.class).readValue("{ \"name\": \"account1\", \"items\": [\"item1\"], \"users\": [ { \"firstname\": \"user1_firstname\", \"lastname\": \"user1_lastname\" }] }");
assertEquals(account.getName(), "account1");
assertNull(account.getUsers());
}
Unforunately, the 2nd assertion fails because Users has a user object inside.
Basically, even though "users" is a property of Account, I don't want the value to be deserialized because I have used the JSONView (AccountViews.Public.class). However, whatever I try it always seems to be deserialized and is present on the account object.
Any help much appreciated.
Error
`java.lang.AssertionError: expected null, but was:<[User#609db43b]>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotNull(Assert.java:755)
at org.junit.Assert.assertNull(Assert.java:737)
at org.junit.Assert.assertNull(Assert.java:747)
at`

MockingKernel and Received throws an NotASubstituteException

I'm using NSubstituteMockingKernel in order to build all my dependencies of my library classes. I've been struggling to solve a trouble for a week and I'm really exhausted. I need some help.
This is my class:
class Core : ICoreService, ICore {
private ICoreConfiguration configuration;
Core(ICoreconfiguration configuration) {
this.configuration = configuration;
}
override ICoreService.ParentMethod() { //ICoreService implementation
foreach (Item item in this.configuration.Items)
this.ChildMethod();
}
virtual ChildMethod() {
//do something
}
}
ICoreService is:
interface ICoreService {
void ParentMethod();
}
ICore is:
interface ICore {
ICoreConfiguration Configuration { get; }
}
ICoreConfiguration is:
interface ICoreConfiguration {
IEnumerable<Item> Items { get; }
}
My test is:
[TestFixture]
public class UsersManagementTests
{
private readonly NSubstituteMockingKernel IoCKernel;
public UsersManagementTests()
{
this.IoCKernel = new NSubstituteMockingKernel();
}
[SetUp]
public void SetUp()
{
this.IoCKernel.Reset();
}
[Test(Description = "Configured Users are well loaded on Kernel")]
public void InitializationWithUsersTest()
{
//Setup Data
Item item = Item.Create("item1");
IEnumerable<Item> items = new List<Item>() { item };
//Setup Mocks
this.IoCKernel
.Get<ICoreConfiguration>()
.Items
.Returns(items);
Core core = this.IoCKernel.Get<Core>();
//Act
kernel.ParentMethod();
//Assert
IEnumerable<NSubstitute.Core.ICall> calls = kernel.ReceivedCalls(); // ((((((1))))))
kernel.Received(1).ChildMethod(); // ((((((2))))))
}
}
When ((((((1)))))) or ((((((2)))))) are reached, I'm getting this NSubstitute.Exceptions.NotASubstituteException exception message now on last line:
NSubstitute extension methods like .Received() can only be called on objects created using Substitute.For() and related methods.
As you can see I'm trying to test ChildMethod method is reached once at least. ChildMethod must be called according to my Core.Kernel implementation.
I will really appreciate some help.
Thanks.

GWTP: Troubles to display a CellTable

Hi I'm new to GWT and so, to GWTP too.
I try to play with CellTables and I decided to begin by building a simple one following GWT documentation at developers.google.com/web-toolkit/doc/2.4/DevGuideUiCellWidgets#celltable
I adapted few things to match GWTP MVP design.
First, I created my Celltable on my View.ui.xml file:
xmlns:c="urn:import:com.google.gwt.user.cellview.client">
<g:HTMLPanel>
<c:CellTable pageSize='15' ui:field='cellTable' />
</g:HTMLPanel>
Then, I created a class Contact:
public class Contact {
private final String address;
private final String name;
public Contact(String name, String address) {
this.name = name;
this.address = address;
}
public String getAddress() {
return address;
}
public String getName() {
return name;
}
}
in my View.java file:
#UiField(provided=true) CellTable<Contact> cellTable = new CellTable<Contact>();
public CellTable<Contact> getCellTable() {
return cellTable;
}
Finally in my Presenter.java file:
public interface MyView extends View {
CellTable<Contact> getCellTable();
}
#Override
protected void onReset() {
super.onReset();
// Create name column.
TextColumn<Contact> nameColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact contact) {
return contact.getName();
}
};
// Create address column.
TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact contact) {
return contact.getAddress();
}
};
// Add the columns.
getView().getCellTable().addColumn(nameColumn, "Name");
getView().getCellTable().addColumn(addressColumn, "Address");
// Set the total row count.
getView().getCellTable().setRowCount(CONTACTS.size(), true);
// Push the data into the widget.
getView().getCellTable().setRowData(0, CONTACTS);
}
Everything seems good to me but there is no CellTable displayed when I try this code...And I get no errors...
Thanks in advance for your Help!
It looks like you do not use/have DataProvider registered for your CellTable. GWT CellWidgets are based on DataProvider/DIsplay pattern. So CellTable is just a Display for your DataProvider. One DataProvider could have multiple displays.
You do not need to write:
// Set the total row count.
getView().getCellTable().setRowCount(CONTACTS.size(), true);
// Push the data into the widget.
getView().getCellTable().setRowData(0, CONTACTS);
You need to register your CellTable as a Display for your DataProvider (eg ListDataProvider) and than call refresh method when you update DataProvider with new data.