<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Łukasz Izmajłowicz on Medium]]></title>
        <description><![CDATA[Stories by Łukasz Izmajłowicz on Medium]]></description>
        <link>https://medium.com/@MAFI8919?source=rss-55f62c577b02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NnbyfIQzFiUdfxNQ.jpeg</url>
            <title>Stories by Łukasz Izmajłowicz on Medium</title>
            <link>https://medium.com/@MAFI8919?source=rss-55f62c577b02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:31:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@MAFI8919/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[So, will AI replace developers?]]></title>
            <link>https://medium.com/@MAFI8919/so-will-ai-replace-developers-fbc6bb698429?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbc6bb698429</guid>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 20:49:11 GMT</pubDate>
            <atom:updated>2026-04-07T20:49:11.936Z</atom:updated>
            <content:encoded><![CDATA[<p>“In six months, most developers will be replaced by AI.”</p><p>I’ve heard this prediction on a loop lately. Usually, it’s coming from “vibe-coding” managers who, after two weeks with Claude Code, suddenly feel qualified to claim the title of Senior Developer. It’s a familiar cycle: people making sweeping predictions about a field they don’t fully understand. Yet, as a developer, I can’t deny the utility of these tools. We aren’t going to ditch them, nor should we. But every time I look at pure AI-generated code, I’m left with a bitter taste.</p><p>A new wave of business owners has emerged, bragging about their weekly LLM subscription spend and the staggering volume of code they’re “shipping.” They are building “revolutionary” to-do apps filled with meaningless slop — verbose logic designed more to boost token spend than efficiency.</p><p>This “vibe-coded” software often suffers from an incoherent style, looking like a patchwork of patterns that don’t actually fit together. All of it with tests that pass without covering anything important and questionable architectural decisions that look correct on the surface but crumble under real-world pressure.</p><p>This might sound like the defensive cry of a developer afraid of being replaced (maybe it is?) In reality, the more “vibe-coded” projects I’m interacting with, the safer I feel in my career.</p><p>I use these tools daily, and the benefits are undeniable, but you can only judge the quality of the output if you are an expert in the field. The narrative that the developer role is dead — and that we should all just become “one-person enterprises” — ignores a fundamental truth: you must be able to evaluate the slop. Trusting an auto-complete engine blindly isn’t “shipping” — it’s asking for a production meltdown.</p><p>There is, however, a legitimate place for vibe coding. It is a fantastic way for managers to convey ideas. We all know that stakeholders often struggle to articulate exactly what they want (and developers are often not the best at listening). A few iterations with an LLM can create a “living mockup” that makes the product vision clear. But that’s where it should end.</p><p>If it’s been “vibed,” it’s better not to deploy it to a production server. Let the managers use LLMs to build reference projects and rough prototypes as a way to hand over requirements. Once the vision is clear, the development team needs to step in to redo, refine, or build something that is actually deployable and maintainable.</p><p>So in the short term, it will suck for developers. Managers will be managers, the job market is not the best, but if all follows as it is, the bubble may burst, and projects will have to be reviewed and redesigned. The question there… are we really up for cleaning it up?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbc6bb698429" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About comments…]]></title>
            <link>https://medium.com/@MAFI8919/documenting-api-controllers-dba058a7ee4b?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/dba058a7ee4b</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 14:13:30 GMT</pubDate>
            <atom:updated>2022-12-06T14:14:30.216Z</atom:updated>
            <content:encoded><![CDATA[<p>96% of comments are useless. My guesswork proves this and no one should question it!</p><p>Ok, I don’t have any data to back it up, but it feels like that…</p><p>Common knowledge says that naming methods is one of the most difficult tasks, we poor developers, have to struggle with. Yet, quite often I see well-named methods with, how to call it… stupid comments.</p><p>Why is it a big deal for me? Reading code is what we mostly do, so it should be as effortless and fast as possible. Adding an extra layer of information (which does not bring anything new to the conversation) is just clutter.</p><p>Another well-known fact is, that documentation quite often diverges from implementation. Yes, we are lazy, and the documentation we write at the beginning of work gets easily forgotten in the process.</p><p>There are cases when extra comments make sense:</p><ul><li>A complicated piece of the algorithm,</li><li>Extra side effects that caller has to be aware of,</li><li>… well… Links to the tickets where we applied hotfixes?</li></ul><p>I cannot really think about much more...</p><p>Solution.. just burn them all (unless your manager is forcing you to keep them. In this case there are more appropriate steps to take).</p><p>Let’s see some random code from the current codebase (There is a lot like that.. about 96% :))</p><pre>/// &lt;summary&gt;<br>/// Sign up a new User<br>/// &lt;/summary&gt;<br>public class UserController : BaseApiController<br>{<br>    // ...<br><br>    /// &lt;summary&gt;<br>    /// Gets the Information about the User<br>    /// &lt;/summary&gt;<br>    public async Task&lt;UserDto&gt; Get(UserId id)<br>    {<br>      // ...<br>    }</pre><p>Explanation:</p><p>What would we expect from Get(..) method in UserController?</p><p>I don’t know you, but I expect user information. As developers working with web technologies, we all know it, we live with it daily…</p><p>Another point, did you notice the comment on the controller class? “Sing up the User”… wait, I just make a query for the User, not sign-up.. (and trust me, there are a little bit more actions there)</p><p>At some point, I will write how I see this improved. Stay tuned!</p><p>And now time for the winner (or loser, depending on how you look at it). I think we’ve all seen code like this</p><pre>/// &lt;summary&gt;<br>/// Container for the Sign UP API<br>/// &lt;/summary&gt;<br>public class SignUpData<br>{<br>    /// &lt;summary&gt;<br>    /// Used for the Serialization<br>    /// &lt;/summary&gt;<br>    public SignUpData()<br>    {<br><br>    }<br><br>    /// &lt;summary&gt;<br>    /// The Email Address to register<br>    /// &lt;/summary&gt;<br>    public string Email { get; set; }<br><br>    /// &lt;summary&gt;<br>    /// The Password to register<br>    /// &lt;/summary&gt;<br>    public string Password { get; set; }<br>}</pre><p>Do I even... ehh see you next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dba058a7ee4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegated Properties in Kotlin]]></title>
            <link>https://medium.com/@MAFI8919/delegated-properties-in-kotlin-574747a4129f?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/574747a4129f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Fri, 28 Apr 2017 12:53:13 GMT</pubDate>
            <atom:updated>2017-04-28T12:53:13.643Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build-In delegates to solve common problems</h4><p>Today I will share some knowledge about Delegated Properties in Kotlin. To be specific, I will be talking only about three of them — <em>Lazy</em>, <em>Observable</em> and <em>Vetoable</em> which can help many in common problems.</p><p>Simply speaking, Delegated Property is a property which corresponding <em>getValue()</em> or<em> setValue()</em> method will be called when accessed.</p><p>Kotlin provides few delegated properties build in into the language — <em>Lazy properties</em>, <em>Observable properties </em>and <em>Properties storing in the map</em>.</p><p>I don’t have real and good use case for <em>Properties storing in the map (as docs explain — </em>“storing properties in a map, instead of a separate field for each property”), but <em>Lazy</em> and <em>Observable</em> are delegates heavily used in day to day work.</p><h4>Lazy property</h4><p>There are many times when delaying object creation until it is first used is beneficial. Think of heavy objects, which may affect application startup time or can be actually never called (for example in case of handling click events).</p><p>Kotlin gives <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-lazy/">Lazy</a> delegate which cares about waiting with creation of the actual object until first touched. When used, <em>getValue()</em> method gets evaluated and result is remembered.</p><pre>private val model by <em>lazy </em><strong>{ </strong>Injector.app().transactionsModel() <strong>}</strong></pre><pre><em>// Somewhere inside the function body<br>view</em>.setOnClickListener <strong>{ </strong>model.showWallets() <strong>}</strong></pre><p>As shown above, the <em>model</em> is a delegated property. Its initialization body will be called only in case onClickListener will be called. What is important, it will be initialized only once.</p><p>Kotlin provides 3 different modes for specifying threading policy (<em>SYNCHRONIZED, PUBLICATION, NONE)</em>.</p><ul><li><em>LazyThreadSafetyMode.SYNCHRONIZED</em> mode is used to ensure that only a single thread can initialize the instance.</li><li><em>LazyThreadSafetyMode.PUBLICATION allows multiple callers to call initialization body but only the first returned will be used as the value.</em></li><li><em>LazyThreadSafetyMode.NONE does not care about threading and for multiple callers, result is unexpected. Android works with many frameworks which are used on UI thread only. In that cases by using LazyThreadSafetyMode.NONE we could take advantage of Thread Confinement and save precious milliseconds for </em>acquiring<em> locks.</em></li></ul><p>To specify thread policy, pass value of <em>LazyThreadSafetyMode </em>to lazy parameter like following:</p><pre>private val model by <em>lazy</em>(mode = LazyThreadSafetyMode.NONE) <strong>{ <br>    </strong>Injector.app().transactionsModel() <br><strong>}</strong></pre><h4>Observable and Vetoable property</h4><p><em>Observable</em> is a property with attached body which gets called after each modification. It allows to have logically connected business logic, while exposing only property to the outside.</p><p><em>Vetoable</em> is similar concept, but it gives also a way to block modification depending on return value. Both delegates are created using factory function from Delegates.kt like below:</p><pre>// Adapter<br>var data: List&lt;Any&gt; by Delegates.vetoable(<em>listOf</em>()) <strong>{ </strong>p, old, new <strong>-&gt;<br>    </strong>notifyDataSetChanged()<br>    old != new<br><strong>}</strong></pre><pre>// Somewhere in the code...<br>adapter.data = model.fetchWallets()</pre><p>When creating <em>observable</em> or <em>vetoable</em>, you need to specify default value as a parameter. When onChange callback gets invoked, developer can check the current value <em>old</em> (which is the default value on first invocation), <em>new</em> value which is being assigned as well as <em>p</em> which is reference to modified property.</p><p>Each time <em>adapter.data</em> sets new value <em>onChange </em>lambda gets called. As mentioned before, <em>Vetoable</em> can block the modification by returning false from the lambda body (in above example if previous value was not actually changed).</p><p>The example shows simple usage for RecyclerView.Adapter implementation. To avoid re-assigning the same value (which would costs rewriting the view) <em>Vetoable</em> check if previous and new value are not the same.</p><p>When <em>Vetoable’s </em>onChange callback gets called it first checks the return value. When TRUE, then the value is set to the new value. Returning FALSE won’t modify the property.</p><p>There you have it! If you want to read more, check the links below for more informations.</p><ul><li><a href="https://kotlinlang.org/docs/reference/delegated-properties.html">Official documentation about Delegated Properties</a></li><li><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-lazy/">Lazy Delegate</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=574747a4129f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Querying table details in SQLite?]]></title>
            <link>https://medium.com/@MAFI8919/querying-table-details-in-sqlite-d5436fd7e9b2?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5436fd7e9b2</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Thu, 27 Apr 2017 11:10:44 GMT</pubDate>
            <atom:updated>2017-04-27T11:10:44.274Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sqlite_master table explained</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wN-Q552zj3ZvinY3MC3H1g.jpeg" /></figure><p>Let’s be honest… fetching informations about tables is not the task you will come across every day. Even though it is not so usual, there are still cases when knowing if table exists is crucial. One of the cases could be testing your database schema. Testing database migrations? Sounds helpful to me as well.</p><p>But how do you do this? There is a simple answer — Query <em>SQLITE_MASTER </em>table with <em>SELECT</em> statement, like:</p><pre>SELECT name FROM sqlite_master WHERE type=&#39;table&#39;;</pre><p>Hold on! Where did the <em>sqlite_master</em> table came from?</p><p><em>Sqlite_master</em> table is created for each database automatically. It describes the schema of each table with some additional informations. Additionally, database can contain <em>SQLITE_TEMP_MASTER</em> which holds information about views, their indices and triggers.</p><p><strong>Type</strong> column can be either a <em>table</em> or <em>index.</em> Depending of the type, <em>name</em> and <em>tbl_name</em> can take different values.</p><p><strong><em>Name</em></strong> and <strong><em>tbl_name</em></strong> are the most interesting columns. Name is simply the name of table or index, where <em>tbl_name</em>, when type is <em>index, </em>is the table to which the index belongs. For type table <em>tbl_name </em>is NULL.</p><p><strong><em>Rootpage</em></strong><em> </em>is the page number of the root b-tree page. For rows that define views, triggers, and virtual tables, the <em>rootpage</em> column is zero or NULL.</p><p><strong><em>Sql</em></strong> is just a CREATE statement for table or index. For automatically created indices (to implement PRIMARY KEY or UNIQUE constraints) sql is set to NULL.</p><p>Now, when we know what informations we can get, let’s see how easily can we find out whether the table exists in database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1cd2ebbb5aca6e12398a64a465614b4/href">https://medium.com/media/e1cd2ebbb5aca6e12398a64a465614b4/href</a></iframe><p>As described above, <em>name</em> column keeps the name of the table. The Above example assumes that what we are interested in are only tables and not tables which belong to indices (which would be kept in <em>tbl_name</em> column<em>).</em></p><p>One point to consider is whether to query temporary tables as well. In this case, the following version would be more appropriate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf0c39af8db3e758827792359353ecd5/href">https://medium.com/media/bf0c39af8db3e758827792359353ecd5/href</a></iframe><p>Let’s take a look at the real live scenario. The task is to create tables for each supported language. Test cases like below show how to use presented method to check whether all expected tables are created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34657943543150d8b54585a22f8d0dd7/href">https://medium.com/media/34657943543150d8b54585a22f8d0dd7/href</a></iframe><p>If you are into topics like that one, check my other posts about automated Android and SQLite. The short, but still growing, list of articles on that topic looks like the following:</p><ul><li><a href="https://medium.com/@MAFI8919/simple-trick-to-make-your-sqlite-database-tests-faster-on-android-d0f5c7b7b572#.ek3c90qmm">Simple trick to make your SQLite Database tests faster on Android</a> shows how to prepare database object for fast testing.</li><li><a href="https://medium.com/@MAFI8919/android-database-schema-testing-66f6ff08ebd8#.36mwnr4cd">Android Database Schema Testing</a> shows how to use PRAGMA Statements to assert database state.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5436fd7e9b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing SQLite on Android]]></title>
            <link>https://medium.com/@MAFI8919/testing-sqlite-on-android-bfa0733e11e7?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa0733e11e7</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[sqlite]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Fri, 06 Jan 2017 08:34:27 GMT</pubDate>
            <atom:updated>2017-04-27T11:15:44.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLFyyYkwihAu_G81mY6Ztg.jpeg" /></figure><h4>Solving Chicken and Egg problem</h4><p>Times, when testing Android code was a taboo are far behind us. With growth of the community, multiple members tried to educate others about importance of automated testing.</p><p>In past, Google Team have not put much attention into making Android code testable. Gladly though, they have took some steps to improve the live of professional developers, by providing better tooling, and publishing <a href="https://developer.android.com/training/testing/index.html">Best Practices for Testing</a>.</p><p>While internet is full of general Tricks&amp;Tips for testing, there is still not much knowledge, of how to solve some common problems. This is why, I decided to share my knowledge about testing storage related topics. The motivation was quite simple — show fellow developers that with some tweaks and tricks, testing can be achieved really easy.</p><p>The short, but still growing, list of articles on that topic looks like the following:</p><ul><li><a href="https://medium.com/@MAFI8919/simple-trick-to-make-your-sqlite-database-tests-faster-on-android-d0f5c7b7b572#.ek3c90qmm">Simple trick to make your SQLite Database tests faster on Android</a> shows how to prepare database object for fast testing.</li><li><a href="https://medium.com/@MAFI8919/android-database-schema-testing-66f6ff08ebd8#.36mwnr4cd">Android Database Schema Testing</a> shows how to use PRAGMA Statements to assert database state.</li><li><a href="https://medium.com/@MAFI8919/querying-table-details-in-sqlite-d5436fd7e9b2">SQLITE_MASTER table explained</a>. How to list tables in the database.</li></ul><p>This article offers a simple way of how to test fetching and storing objects using SQLite based storage.</p><p>Storage layer is a fundamental piece of core logic in many Android applications. Providing offline access to data is a must have feature, to survive in crowded market, as well as opportunity to shine with outstanding user experience.</p><p>This is why, storage layer should be a stable piece of code, and testing increases the developer’s confidence about on that matter.</p><p>The following interface of the storage class points out the contract, which each implementation of <em>WalletStorage</em> should follow. It helps with finding out test cases, as well as guards implementation details from the outside world. In the most basic form, it contains two methods.</p><ul><li>First, allows upper layers in architecture, to fetch all stored <em>Wallet</em> objects, with strong note, that returned collection will never be empty.</li><li>To store <em>Wallet</em> objects, client code, uses <em>insert(wallet)</em> method which persists the object, or throws exception when it is already persisted.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adbd8ae2520be87a17379a668e8b46cf/href">https://medium.com/media/adbd8ae2520be87a17379a668e8b46cf/href</a></iframe><p>Finding the first case to cover is sometimes a tricky part. Even though there are only two methods to be tested, there is a problem with circular dependency between them.</p><p>In order to test fetching items, they need to be stored first, and vice versa, to store items, they need to be fetched later for assertion.</p><p>The solution presented below, leads to either duplicated tests, or single test, which covers both scenarios. It is not a comfortable scenario either, the problem is that when designing first test, implementation of all methods is needed (which breaks the purpose of Test First approach).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2052f64a4b6ede657c3124e5dad63f98/href">https://medium.com/media/2052f64a4b6ede657c3124e5dad63f98/href</a></iframe><p>The solution would be finding trusted piece of code (hopefully tested as well), which gives the needed functionalities. One option could be using SQLite database, embedded into framework, to persist or fetch objects from database.</p><p>As much as we would like to trust 3rd party code, there is not much choice in this case. With few, simple SQL statements all needed cases would be covered. <em>SQLiteDatabase</em> class provides methods to <a href="https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String,%20java.lang.String%5B%5D)">query state of tables</a>, as well as <a href="https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#execSQL(java.lang.String)">executing raw SQL statements</a>.</p><p>Isolating test for storing <em>Wallets</em>, is possible by asserting table state with simple sql SELECT statement (<em>SELECT name FROM tbl_wallet;</em>). The only overhead for this solution is using the <em>Cursor</em> class to map results into <em>Wallet</em> object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb00e5264a6078cc379d77b61f58cd7f/href">https://medium.com/media/eb00e5264a6078cc379d77b61f58cd7f/href</a></iframe><p>When testing storing Wallets, things get even simpler. There is no need to map Cursors into object. Insert statement on database is all what is needed (<em>INSERT INTO tbl_wallet VALUES (‘uuid’, ‘name’);</em>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ed6a0a696e2278bcde31dfe00e05f68/href">https://medium.com/media/2ed6a0a696e2278bcde31dfe00e05f68/href</a></iframe><p>By covering those two fundamental cases, testing deleting or updating objects can follow the first approach. Now, there is a trusted (tested) prove that they both work as expected.</p><p>I would still advise you to use the same approach though. It makes all functionalities independent and easier to maintain in future.</p><p>The presented solution uses simple SQL statements to test CRUD operations using SQLite database. Even though, for some, it can sound like a controversial solution, I find it easy and clean to isolate test cases. As always, there is some extra work needed, but having confidence, that features work as expected is worth it!</p><blockquote><em>Android is a tricky beast. Keep calm, find your way around!</em></blockquote><p>Recommended readings:</p><ul><li><a href="https://www.sqlite.org/lang_insert.html">https://www.sqlite.org/lang_insert.html</a></li><li><a href="https://www.sqlite.org/lang_select.html">https://www.sqlite.org/lang_select.html</a></li><li><a href="https://developer.android.com/reference/android/database/Cursor.html">https://developer.android.com/reference/android/database/Cursor.html</a></li><li><a href="https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html">https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa0733e11e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Database Schema Testing]]></title>
            <link>https://medium.com/@MAFI8919/android-database-schema-testing-66f6ff08ebd8?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f6ff08ebd8</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Tue, 03 Jan 2017 21:43:32 GMT</pubDate>
            <atom:updated>2017-01-04T12:04:57.377Z</atom:updated>
            <content:encoded><![CDATA[<h4>Should I really do this?</h4><p>Just before all the hype about MVP, RxJava and Firebase, testing was a hot topic in the Android community. While separating framework from application logic is mostly the solution to go, sometimes there are cases when only framework can provide the data we need.</p><p>To continue <a href="https://medium.com/@MAFI8919/simple-trick-to-make-your-sqlite-database-tests-faster-on-android-d0f5c7b7b572#.a21fffksd">last topic</a> about preparing database for tests, today I want to concentrate on a not so usual problem:</p><blockquote>How would I test database structure?</blockquote><p>I need to be honest with you, I am not really sure if there is a big value in doing that, but as a curious creature, I always want to check what is possible to achieve.</p><p>Android does not provide much information about table structures. SQLite, on the other hand, gives us <a href="https://www.sqlite.org/pragma.html">PRAGMA Statements</a>:</p><blockquote>The PRAGMA statement is an SQL extension specific to SQLite and used to modify the operation of the SQLite library or to query the SQLite library for internal (non-table) data.</blockquote><p>There is a long list of PRAGMA Statements for SQLite (not all of them are available on each Android versions).</p><p><a href="https://www.sqlite.org/pragma.html#pragma_table_info">Table Info PRAGMA</a> (PRAGMA table_info) statement lets us query data related to table structure. Following piece of documentation, describes what is possible to get out of the table_info pragma:</p><blockquote>This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The “pk” column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.</blockquote><p>PRAGMA Statement, like any other sql statement, can be executed as a query on database. Example of output, for tbl_wallet table, looks like following:</p><p>sqlite&gt; pragma table_info(“tbl_wallet”);<br><em>0|uuid|TEXT|0||1<br>1|name|TEXT|1||0</em></p><p>Table_info PRAGMA Statement returns data in format: <strong><em>position| name | type | Nullable | Default value | Primary Key.</em></strong></p><p>As we can see, that first column, UUID, is a Primary Key without default value which allows storing TEXT values.</p><p>Similarly, name column, which allows TEXT values, is not a Primary Key and cannot have null values, neither has a default value.</p><p>To create this structure, following sql command was used. Notice, that uuid column, was not marked as a NOT NULL, which is easily accepted by SQLite databases (how to deal with it, will be described with following articles).</p><pre>CREATE TABLE tbl_wallet(uuid TEXT PRIMARY KEY, name TEXT NOT NULL);</pre><p>As said before, PRAGMA Statements can be executed as a query on database. By using SQLiteDatabase::rawQuery(pragmaStatement) method we get access to data listed above.</p><p>Following code retrieves only column names. Except name, possible options are:</p><ul><li><strong>type</strong>, gives type of column (one of INTEGER, REAL, TEXT, BLOB, NULL)</li><li><strong>pk</strong>, whether or not column is Primary Key</li><li><strong>notnull</strong>, whether field can contain null values</li></ul><p>Testing is trivial again. Following test checks if table <em>tbl_wallet</em> contains all necessary columns.</p><pre>@Test<br>public void walletsTableHasAllColumns() {<br>    assertThat(listColumnNames(db, &quot;tbl_wallet&quot;))<br>            .containsExactly(&quot;uuid&quot;, &quot;name&quot;);<br>}</pre><pre>// Implementation of PRAGMA table_info for column names<br>List&lt;String&gt; listColumnNames(SQLiteDatabase db, String table) {<br>    Cursor c = null;<br>    try {<br>        <strong>c = db.rawQuery(&quot;pragma table_info(&quot; + table + &quot;);&quot;, null);</strong><br><br>        List&lt;String&gt; columns = new ArrayList&lt;&gt;();<br>        while (c != null &amp;&amp; c.moveToNext()) {<br>            columns.add(c.getString(c.getColumnIndex(&quot;name&quot;)));<br>        }<br><br>        c.close();<br>        return columns;<br>    } catch (Exception ignored) {<br>        return Collections.<em>emptyList</em>();<br>    }<br>}</pre><p>Similarly, we can follow with other properties. TableDescription is wrapper around those informations. For more details, check <a href="https://gist.github.com/izmajlowiczl/61ce2edc4d881b78ca06b45d91b91b17">following gist</a>.</p><pre>@Test<br>public void walletTableHasCorrectUuidColumn() {<br>    TableDescription uuidColumn = getColumnDetails(db, &quot;tbl_wallet&quot;, &quot;uuid&quot;);<br><br>    assertThat(uuidColumn.name).isEqualTo(&quot;uuid&quot;);<br>    assertThat(uuidColumn.type).isEqualTo(&quot;TEXT&quot;);<br>    assertThat(uuidColumn.isNotNull).isTrue();<br>    assertThat(uuidColumn.isPk).isTrue();<br>}<br><br>@Test<br>public void walletTableHasCorrectNameColumn() {<br>    TableDescription nameColumn = getColumnDetailsOrNull(db, &quot;tbl_wallet&quot;, &quot;name&quot;);</pre><pre>    assertThat(nameColumn.name).isEqualTo(&quot;name&quot;);<br>    assertThat(nameColumn.type).isEqualTo(&quot;TEXT&quot;);<br>    assertThat(nameColumn.isNotNull).isTrue();<br>    assertThat(nameColumn.isPk).isFalse();<br>}</pre><p>Check out <a href="https://www.sqlite.org/pragma.html">documentation</a> about PRAGMA Statements, to find out more use cases to cover with tests. Some useful examples could be:</p><ul><li><strong>user_version</strong></li></ul><blockquote>The user_version pragma will to get or set the value of the user-version integer at offset 60 in the <a href="https://www.sqlite.org/fileformat2.html#database_header">database header</a>.</blockquote><pre>@Test<br>public void currentDatabaseVersion() {<br>    assertThat(getCurrentDatabaseVersion(db))<br>            .isEqualTo(42);<br>}</pre><pre>// Implementation of PRAGMA user_version<br>int getCurrentDatabaseVersion(SQLiteDatabase db) {<br>    Cursor c = db.rawQuery(&quot;pragma user_version;&quot;, null);<br>    return c.moveToNext() ? c.getInt(0) : -1;<br>}</pre><ul><li><strong>foreign_key_list</strong></li></ul><blockquote>This pragma returns one row for each <a href="https://www.sqlite.org/foreignkeys.html">foreign key constraint</a> created by a REFERENCES clause in the CREATE TABLE statement of table “<em>table-name</em>”.</blockquote><pre>@Test<br>public void currentDatabaseVersion() {<br>    assertThat(getFks(db, &quot;tbl_transaction&quot;))<br>            .isEqualTo(Pair.create(&quot;wallet&quot;, &quot;uuid&quot;);<br>}</pre><pre>// Implementation of PRAGMA foreign_key_list<br>Pair&lt;String, String&gt; getCurrentDatabaseVersion(SQLiteDatabase db, String table) {<br>    Cursor c = db.rawQuery(&quot;pragma foreign_key_list(&quot; + table + &quot;);&quot;, null);<br><br>    if (!c.moveToNext()) {<br>        return null;<br>    }<br><br>    // c[2] -&gt; Referenced table<br>    // c[3] -&gt; key<br>    // c[4] -&gt; Referenced key<br>    return Pair.<em>create</em>(c.getString(2), c.getString(4));<br>}</pre><p>Note that some of PRAGMA Statements can be not available. Different versions of Android bounds different versions of SQLite database (check <a href="https://developer.android.com/reference/android/database/sqlite/package-summary.html">Android docs</a>).</p><blockquote>Android is a tricky beast. Keep calm, find your way around!</blockquote><p>Recommended readings</p><ul><li><a href="https://www.sqlite.org/pragma.html">https://www.sqlite.org/pragma.html</a></li><li><a href="https://developer.android.com/reference/android/database/sqlite/package-summary.html">https://developer.android.com/reference/android/database/sqlite/package-summary.html</a></li><li><a href="http://www.grokkingandroid.com/sqlite-in-android/">http://www.grokkingandroid.com/sqlite-in-android</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f6ff08ebd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple trick to make your SQLite Database tests faster on Android]]></title>
            <link>https://medium.com/@MAFI8919/simple-trick-to-make-your-sqlite-database-tests-faster-on-android-d0f5c7b7b572?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0f5c7b7b572</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Fri, 16 Dec 2016 17:39:30 GMT</pubDate>
            <atom:updated>2016-12-17T11:50:33.681Z</atom:updated>
            <content:encoded><![CDATA[<h4>One parameter can make a difference</h4><p>It is a known fact, that developers complain about duration of test execution. Many times, this is the main argument against writing tests at all. Sometimes, we cannot do much about this, but in most cases, there is a way to make it work fast.</p><p>Another known fact, is that testing Android applications is especially tricky, or at least most of us try to make a noise like that around other fellow developers. When in few cases it could be true, with some small tricks, and browsing documentation, it is not always the case.</p><p>Let’s start with some theory about SQLite on Android.</p><p><a href="https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html">SQLiteOpenHelper</a> is an abstract class, providing an interface for managing database creation and version management. It provides two mandatory methods, which have to be implemented.</p><ul><li><a href="https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onCreate(android.database.sqlite.SQLiteDatabase)">onCreate(SQLiteDatabase db)</a> is the place, where initial schema goes in. Here, we see sql commands to be feed into SQLiteDatabase::execSQL(String sql) methods.</li><li><a href="https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onUpgrade(android.database.sqlite.SQLiteDatabase,%20int,%20int)">onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)</a> handles all updates to our schema. Depending on <em>oldVersion</em>, and <em>newVersion</em>, developers should run sql to alter schema and migrate data.</li></ul><p>SQLite database is a file backed, persistent storage. The file is located in application folder. To be more specific, inside databases folder, like <em>/data/data/your.app.package/databases/database_name</em></p><p>Going back to our topic, each time test is executed, database has to be opened, requested operation has to be invoked and finally database get closed. This means touching file storage.</p><blockquote>Disk operations are slow, and makes developers unhappy.</blockquote><blockquote>— Me, developer, mostly happy!</blockquote><p>The good news is, that there is a way to skip disk operations at all. If you take a look at the <a href="https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#SQLiteOpenHelper(android.content.Context,%20java.lang.String,%20android.database.sqlite.SQLiteDatabase.CursorFactory,%20int)">documentation</a>, by passing <strong>null</strong> as a database name, we get in memory database.</p><p>Sounds cool, let’s see some code.</p><p>Below is the bare bone implementation of SQLiteOpenHelper class. Mind the VisibleForTesting annotated constructor, which will be used to create in memory database for tests. For readability, implementations of onCreate and onUpgrade are left blank.</p><pre>public class Database extends SQLiteOpenHelper {<br>    public Database(Context context) {<br>        super(context, <em>DATABASE_NAME</em>, null, <em>DATABASE_VERSION</em>);<br>    }<br><br>    @VisibleForTesting<br>    Database(Context context, String name, int version) {<br>        super(context, name, null, version);<br>    }<br><br>    @Override public void onCreate(SQLiteDatabase db)<br>    @Override public void onUpgrade(SQLiteDatabase db, int a, int b)<br>}</pre><p>The only overhead here is the need to have extra constructor. This could be avoided, by having single constructor, and providing name and version from outside of this class (consider Dependency injection). Encapsulating those values inside SQLiteOpenHelper implementation is common practice though, so developer should decide what fits him better.</p><p>Going to the test class, now we need to inject our database object (with null-name parameter) in any possible way (still Dependency Injection…), and concentrate on testing the logic.</p><p>A simple test could look like that..</p><pre>@RunWith(AndroidJUnit4.class)<br>public class WalletModelTest {<br>    Database db = DI.<em>storage</em>().testDatabase();<br><br>    @Test<br>    public void storeWallet() {<br>        db.insertWallets(Wallet.create(&quot;Test-Wallet&quot;));<br>        <br>        assertThat(db.listWallets())<br>                .containsExactly(wallet);<br>    }<br><br>    @Test(expected = DatabaseConstraintException.class)<br>    public void blockStoringDuplicates() {<br>        String walletName = &quot;Test-Wallet&quot;;<br><br>        db.insertWallets(Wallet.create(walletName),<br>                         Wallet.create(walletName));<br>    }<br>}</pre><p>But why do we even want to test Storage layer?</p><p>These days, most of local caches are implemented using SQLite provided by framework. This core component of most of the applications has to be stable and understandable by each team member.</p><p>Additionally, there is much business logic around SQLite database, schema creation and migration, just to mention few. It is a fully valuable piece of code to be covered with tests.</p><p>Other point is, that mostly developers write abstraction on top of SQLite database, with custom storage logic. This definitely sounds like a good candidate for test coverage. By having in memory database, there is no need to mock it.</p><p>Like it or not, there are no more excuses to test your storage. When done correctly, there is no need to blame time spent waiting for Jenkins reports.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0f5c7b7b572" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Argument Passing With @AutoValue]]></title>
            <link>https://medium.com/android-news/better-argument-passing-with-autovalue-5dfa32b74882?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dfa32b74882</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[autovalue]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Thu, 15 Dec 2016 23:19:26 GMT</pubDate>
            <atom:updated>2017-01-16T18:05:35.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HM4TNmMdnrbyS1aP8Ugd4A.jpeg" /><figcaption><a href="https://stocksnap.io/photo/56A1C1BE07">https://stocksnap.io/photo/56A1C1BE07</a></figcaption></figure><h4>AutoValue extensions for simplifying passing custom object between Activities</h4><p>On Android, transferring objects between Activities is not a pleasant experience. Passing primitive values like, long, int or boolean is pretty straightforward, where custom object is a little bit more tricky.</p><p>Framework creates Activity objects, so developers have to implement Parcelable interface on their own to pass custom objects around. It forces developers to create quite some number of lines of code (see below example), as well as remembering about correct order of calls.</p><p>Google, together with open source community came with help. I will not explain benefits of AutoValue better than Joshua Bloch:</p><blockquote>AutoValue is a great tool for eliminating the drudgery of writing mundane value classes in Java. It encapsulates much of the advice in Effective Java Chapter 2, and frees you to concentrate on the more interesting aspects of your program. The resulting program is likely to be shorter, clearer, and freer of bugs. Two thumbs up.</blockquote><blockquote>— Joshua Bloch, author, Effective Java</blockquote><p>Sounds cool, right? On top of that, it is really easy to extend. Ryan Harter created an <a href="https://github.com/rharter/auto-value-parcel">extension</a>, which generates all boilerplate code for Parcelable. Using it is as simple as adding line to gradle build file and implementing Parcelable interface. That is it, Magic!</p><p>When combining these two libraries, the solution for our problem sounds trivial. The whole idea is to wrap params into one class or reuse custom class, make it implement Parcelable and of course let AutoValue do the rest.</p><p>To present this solution, let’s take a look at case when 2 Strings are passed between Activities. In receiving Activity, class with city and station was declared, plus some helper method which creates Bundle object with all values. First, our new way.</p><pre>@AutoValue<br>public static abstract class InputParams implements Parcelable {<br><br>    public abstract String city();<br>    public abstract String station();<br><br>    public Bundle toExtras(String withKey) {<br>        Bundle extras = new Bundle();<br>        extras.putParcelable(withKey, this);<br>        return extras;<br>    }<br>}</pre><p>Even though this example is still pretty simple, it has only 2 fields, adding each next field increases it by exactly one line. What is more important, extension is as stupid easy as possible, just declare new abstract field and AutoValue, together with extension will generate the rest for you.</p><p>The same example, written in the standard fashion will looks like following:</p><pre>public static class UglyInputParams implements Parcelable {<br>    public static final String <em>KEY_CITY </em>= _City&quot;;<br>    public static final String <em>KEY_STATION </em>= _Station&quot;;<br>    <br>    public String city;<br>    public String station;<br><br>    public UglyInputParams(Parcel in) {<br>        city = in.readString();<br>        station = in.readString();<br>    }<br><br>    @Override<br>    public void writeToParcel(Parcel dest, int flags) {<br>        dest.writeString(city);<br>        dest.writeString(station);<br>    }<br><br>    @Override<br>    public int describeContents() {<br>        return 0;<br>    }<br><br>    public static final Creator&lt;UglyInputParams&gt; <em>CREATOR </em>= new Creator&lt;UglyInputParams&gt;() {<br>        @Override<br>        public UglyInputParams createFromParcel(Parcel in) {<br>            return new UglyInputParams(in);<br>        }<br><br>        @Override<br>        public UglyInputParams[] newArray(int size) {<br>            return new UglyInputParams[size];<br>        }<br>    };<br><br>    public Bundle toExtras(String withKey) {<br>        Bundle extras = new Bundle();<br>        extras.putParcelable(withKey, this);<br>        return extras;<br>    }<br>}</pre><p>You see the difference, right?.</p><p>Just adding single field causes increase in 3 lines on top of already packed class. The biggest pain though, comes with fact that order of fields is important, while writing to and from Parcel.</p><p>Lazy developers don’t want to think about details like that. Trust me, I am an engineer!</p><p>To wrap up. As a lazy developers, we want…</p><ul><li>Less code to write. Let’s make the machines code!</li><li>Brainless implementation</li><li>Forget about declaring constants for keys</li><li>Easier creation of object</li><li>Test friendly</li><li>Clear definition of input parameters</li></ul><p>There are some small problems, like…</p><ul><li>Optional arguments. There is no easy way to indicate that primitive like int or boolean can be optional. One possibility to overcome this problem is to use special values (like -1 for integers, false for booleans, etc.). For the rest Nullable annotation could be a good solution</li><li>Adding extra libraries to project</li><li>Increase of number of classes. AutoValue generates classes with AutoValue_ prefix, but is it really a problem?</li></ul><p>AutoValue is a great tool, made by Google, with lots of useful extensions. Parcelable is one of those, which saves our frustrations in day to day tasks, and keeps our code cleaner, and simpler to read or maintain.</p><p>To check out more about AutoValue, take a look at the official page <a href="https://github.com/google/auto/blob/master/value/userguide/index.md">here</a>. For Parcelable extension, used by me, check <a href="https://github.com/rharter/auto-value-parcel">this link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dfa32b74882" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/better-argument-passing-with-autovalue-5dfa32b74882">Better Argument Passing With @AutoValue</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application is not the place for utility methods. Period.]]></title>
            <link>https://medium.com/@MAFI8919/application-is-not-the-place-for-utility-methods-period-8d7da2affee4?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7da2affee4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Wed, 13 Jan 2016 21:58:58 GMT</pubDate>
            <atom:updated>2016-01-14T20:49:59.425Z</atom:updated>
            <content:encoded><![CDATA[<p>Each time I take a look on new android codebase, I start to read <em>AndroidManifest </em>file followed by (if any) custom implementation of <em>android.app.Application</em> class.</p><p>I want to check what kind of initialization application needs. Often, I find there crash reporting tool setup, storage initialization, sometimes some logging tool setup or even StrictMode configuration. All this is just fine, but..</p><p>What about all of those other methods out there?</p><p>Putting utility methods inside Application subclass; This is an interesting phenomena, which I have noticed in few recent projects. For many of you this may sound like a silly problem, and for others like a correct solution (I count to get some feedback from you guys!).</p><p>I believe that <em>Application</em> subclass is intended to keep only necessary initialization code which should be done once per application lifecycle. I don’t see any value in storing utility methods out there.</p><p>Each method should have a class that explains meaning for it. What I mean by that is that methods like <em>reportException, sessionId, saveStringParameterToPrefs </em>and much more just don’t fit there (yes, these are examples from real projects).</p><p>There is a better place to keep all those methods, so why not to extract common classes, which will precisely indicate the intention those methods. Some good candidates could be <em>Logger::reportException, Session::getSessionId, KeyValueStorage::saveString…</em></p><p><em>You get the idea, right?</em></p><p>There is another benefit of having separate classes instead big blob of code in one place.</p><p>Take into consideration guys who are new to your project. The first thing they see is project structure filled with bunch of meaningful packages and classes, instead of an <em>App</em> class which “hides” your functionality.</p><p>It will be just easier to find helpful methods in well organized project structure. Trust me, I was there!</p><p>This touches different topic — how to name classes, and how to organize project structure. There should be a following text about it in the future.</p><p>To wrap it all up, no kittens will die if you will put your utility methods in one place but remember that <em>Application</em> subclass is not a suitable place for them.</p><p>Better way would be to keep granulated classes, which indicates purpose of functionality and better document your project. At the same time, your project structure is more clear and other developers will easily find what they are looking for!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7da2affee4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static fields in Application class]]></title>
            <link>https://medium.com/@MAFI8919/static-fields-in-application-class-def29d227331?source=rss-55f62c577b02------2</link>
            <guid isPermaLink="false">https://medium.com/p/def29d227331</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Łukasz Izmajłowicz]]></dc:creator>
            <pubDate>Sat, 09 Jan 2016 09:33:09 GMT</pubDate>
            <atom:updated>2016-01-19T23:00:34.491Z</atom:updated>
            <content:encoded><![CDATA[<p>How not to store shared values throughout your app.</p><p>I just feel… tired. Seeing people doing the same mistakes over and over again. What I am talking about? As you can deduct from the title, I want to say once for good…</p><blockquote><strong>DON’T STORE STATIC OBJECTS INSIDE THE APPLICATION CLASS</strong>.</blockquote><h3>Why is it so wrong?</h3><p>Let me explain you in just few seconds, but first let’s understand that android is able to kill your application at any point of its lifecycle. It is nothing special and it can happen quite often. Each time your system gets low in memory, framework can decide to kill your app.</p><p>The important thing to keep in mind is that framework will try to recreate state of the application from the point of time when it got killed.</p><p>To illustrate the problem, let’s first take a look at very simple implementation of App class.</p><pre>public class App extends Application {</pre><pre>    public static String someValue = “unknown”;</pre><pre>}</pre><p>As you can see, we keep one static field holding simple string value. The intention of programer would be to share this value easily between different components throughout the whole app.</p><p>Now, changing this global value may look correct, and in fact it is. Here, our starting activity just reassigns value to <em>test. While being on this screen not much can happen indeed. User can rotate the screen, even kill the app and value will be re-assigned correctly.</em></p><pre><em>// MainActivity</em></pre><pre>protected void onCreate(Bundle savedInstanceState) {</pre><pre>    App.someValue = “test”;<br>    vText.setText(App.someValue);</pre><pre>}</pre><p>Our application flow let us start another activity(<em>DetailsActivity</em>) where App.someValue will be just displayed as well but not re-assigned.</p><pre>// DetailsActivity</pre><pre>protected void onCreate(Bundle savedInstanceState) {</pre><pre>    vText.setText(App.someValue);</pre><pre>}</pre><p>Now things get a complicated. Here is where all the problems (or maybe confusions) start.</p><p>Imagine situation, while being on details screen, application gets killed. Next time you try to open it system will restore state and show details screen (It is done for the user to not notice that application was killed).</p><p>Sadly, instead of seeing our test value we see default <em>unknown</em> text displayed. That’s unfortunate…</p><p>It all because <em>someValue</em> was not persisted. Because App class was recreated, static values were recreated to it’s default values as well. Noting magically, just the way mobile systems work.</p><p>There is no single and easy answer how to solve this issue. The best idea is to store values in persistent storage like SharedPreferences. It gets more complicated when trying to store more complex objects using for example SQLite database.</p><p>Unless you expect to have <em>fresh</em> values each time your app is re-created, please put close attention to how you deal with <em>shared</em> objects across whole application. What looks correct at the first look can get tricky later.</p><p>Storing data in described way can just produce hard to find bugs and make your life miserable. Good practice, which I use personally, is to test how your app behaves with screen orientation changes and application re-creation.</p><p>Do not follow blindly examples written on random blogs. I would suggest to use stackoverflow and read comments to check for others opinions. Then, use your brain, and always think twice before adding extra lines of code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def29d227331" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>