Yesterday a colleague of mine started experiencing a weird issue with their android studio. Whenever they’d build the code, a change would be written to codeStyleSettings.xml file automatically.

The change at the first glance was clearly unrelated to something they had been working and hence they weren’t able to figure out what could be the cause of this issue.

What did the change look like?

<Objective-C-extensions>
  <option name="GENERATE_INSTANCE_VARIABLES_FOR_PROPERTIES" value="ASK" />
  <option name="RELEASE_STYLE" value="IVAR" />
  <option name="TYPE_QUALIFIERS_PLACEMENT" value="BEFORE" />
  <file>
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" />
  </file>
  <class>
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" />
    <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" />
  </class>
  <extensions>
    <pair source="cpp" header="h" />
    <pair source="c" header="h" />
  </extensions>
</Objective-C-extensions>

Clearly it wasn’t something related to our code since we aren’t doing anything with Objective-C in our android project. This made me want to check the android studio config on that machine, to see if some preferences were changed by mistake, or through an update or any other means.

Quickly searching for objective-c, I found that there were changes being written to the Inspections in the IDE. However, the dev denied making any such changes.

What do you think was the next obvious step for me?

Turns out, this was an old issue that someone asked about, on StackOverflow 3 years ago, and this, was the top rated and accepted answer that led us to the solution.

The <Objective-C-extensions> Section is added by the Android NDK Support Plugin. Which was added in 1.3 and is activated by default. 
If you have activated this plugin it adds the Section to your codeStyleSettings.xml. Otherwise it will be removed.

Answer by devtribe

Even though the dev had not activated this plugin on their own, maybe an update introduced this change and started causing this weird behaviour.

Here are the steps to fix the problem:

Step 1: Open Preferences in your Android Studio. Shortcut on Mac OS is Command + , (comma) and on Windows is Control + Alt + S
Step 2: Goto Plugins and find the Android NDK Support plugin
Step 3: Uncheck the box to deactivate this plugin, As soon as you do that, a warning dialog will appear asking you to disable Android APK Plugin, Click OK
Step 4: Once deactivated, click on Apply and restart your Android Studio!

Now you can remove the file from your git change log if it appears there, restart Android Studio and the problem would be fixed.

Warning: The solution requires you to disable two plugins which you might want to use at a later stage, so keep that in mind before you do that.

Advertisements

While testing our android app on tablets a while ago, a developer reported that the app had a glitch on the Search Results in landscape mode. After making a search, when we scroll on the search results page, the screen becomes unresponsive.

We immediately started investigation and were easily able to reproduce this behavior on multiple real devices as well as on emulators. So it was not device specific and the amount of memory on the device was for sure not a concern.

The first logical step that came to our mind was to profile and see if we can spot a bottleneck in the CPU Usage or Memory Usage monitors.

While memory profiler showed us a lot of things that we were tempted to look into, one of the devs said we must first look at the CPU usage because it seems some heavy computation is happening on the main thread that is rendering the app completely unusable. We moved to the CPU usage flame chart in unison. 

Here we found out that the RecyclerView was generating more Views than needed. It was then that we figured, for the initial load of the screen, we need 5 different types of views which the RecyclerView might want to already create and cache. What we saw didn’t look very nice. Here is the picture of the Call chart.

The first blue colored call that you see when viewing from top to bottom is the call to onCreateViewHolder method. Something kept on triggering the call to this method infinitely. 

We started playing with RecyclerView API to control view cache size but to no avail.

We also tried to look into our ViewHolder to find out if “maybe” we were doing something nasty there but couldn’t find anything that contributed to this problem.

While reading the code in the fragment, we stumbled upon an issue reported on Google, titled RecyclerView notifyItemChanged Prevent Scroll.

Here is the code snippet which led us to that link:

recyclerView.setHasFixedSize(true);
// In tablet landscape mode the RecyclerView inflated all views because of the bug :
// This was also cause by the upgrade to support library 23.3 and 23.4
// If this bug is fixed by Google we might use the default for setAutoMeasureEnabled to true again if that is better.
srLayoutManager.setAutoMeasureEnabled(false);

Apparently, due to some changes in the past releases of RecyclerView something changed again and even, this fix stopped working.

We then went to the XML file of the Activity in which the two fragments were being loaded on the tablet. 

<?xml version="1.0" encoding="utf-8"?&gt;
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal"&gt;

   <FrameLayout
      android:id="@+id/searchresults_list"
      android:layout_width="0px"
      android:layout_height="match_parent"
      android:layout_weight="1"/&gt;

   <View
      android:layout_width="1dp"
      android:layout_height="match_parent"
      android:background="@color/bui_color_grayscale_light"/&gt;

   <FrameLayout
      android:id="@+id/searchresults_map"
      android:layout_width="0px"
      android:layout_height="match_parent"
      android:layout_weight="1"/&gt;

</LinearLayout&gt;

A lot of you might have understood the problem by now, right? But I’ll still continue for those who haven’t.

RecyclerView’s parent was measuring it with unlimited width and height spec. So the parent was literally asking the RecyclerView to layout as many items as it can, which it did – well, at least tried to. 

The problem is that we were using weighted width on a horizontal weighted linear layout. To calculate the weight distribution, it measured both children with unlimited space, then distributed the remaining space. 
Even though our RecyclerView container was MATCH_PARENT because it was a horizontal linear layout and baseline align is set to true (by default, it is true), LinearLayout tried to measure children’s height to be able to align them, thus, measuring the child with unlimited height. 

Inferred from Official Android Documentation

This is not really a bug in the RecyclerView API. LinearLayout could be more clever not to do this when the child is match_parent but since we were setting baseline align in match_parent children, it was also inconsistent. 

We wrote another variant of the same screen using RelativeLayout which fixed the issue for us.

<?xml version="1.0" encoding="utf-8"?&gt;
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"&gt;

   <FrameLayout
      android:id="@+id/searchresults_list"
      android:layout_alignParentStart="true"
      android:layout_toStartOf="@+id/searchresults_tablet_divider"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/&gt;

   <View
      android:id="@+id/searchresults_tablet_divider"
      android:layout_width="1dp"
      android:layout_height="match_parent"
      android:layout_centerInParent="true"
      android:background="@color/bui_color_grayscale_light"/&gt;

   <FrameLayout
      android:id="@+id/searchresults_map"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentEnd="true"
      android:layout_toEndOf="@+id/searchresults_tablet_divider"/&gt;

</RelativeLayout&gt;

Here is the call chart we saw while running the app with the new variant of the Layout.

The number of calls to onCreateViewHolder reduced significantly and RecyclerView only drew what we expected it to.

This is how we solved this major bottleneck in the tablet version of the app.

In the end, I’d like to conclude that the Android Studio Monitors for Profiling CPU and Memory Usage can be very handy. Never underestimate the power of profiling your code, you’ll always find something to improve there. But be careful as it can be very tempting to fall into traps of code that doesn’t really need optimization. 

Request timed out! But you didn’t expect it, did you? Of course not because while you were writing the app and testing the code you were always on your blazing fast WiFi connection or a 4G LTE network. But in the real world, all your users don’t have access to such a network connection at all times.

Would you want them to suffer?
Would you want your app to behave in a strange manner in that case?
Would you want to create a bad user experience?
Would you want to have an unsatisfied customer?
Do you always test all your features depended on network requests for flaky connections?

If your answer to all the above questions is “No”, then I have a simple solution for you, that’ll make your life a lot easier to test your features for these scenarios and have a failure mechanism in place to be more responsive to the user.


Implementation

The solution is pretty straight forward, create an Interceptor for your network requests and delay or fail them. Let’s look at how to implement this interceptor with OkHttp and provide easy access to it through a UI to all the stakeholders that are responsible or are willing to test your application.

public class NetworkThrottlingInterceptor implements Interceptor {

private static boolean failRequests;

private static final AtomicLong failRequestCount = new AtomicLong(Long.MAX_VALUE);

private static boolean delayAllRequests;

private static long minRequestDelay;

private static long maxRequestDelay;

private final Random random = new Random(4);

@Override
public Response intercept(Chain chain) throws IOException {
if(failRequests) {
long failC = failRequestCount.get();
if (failC > 0) {
failRequestCount.compareAndSet(failC, failC-1);
throw new IOException("FAIL ALL REQUESTS");
}
}
if(delayAllRequests) {
long delay = minRequestDelay;

if(minRequestDelay != maxRequestDelay) {
delay = (long) ((random.nextDouble() * (maxRequestDelay - minRequestDelay)) + minRequestDelay);
}
long end = System.currentTimeMillis() + delay;
long now = System.currentTimeMillis();
while(now < end) {
try {
Thread.sleep(end - now);
} catch (InterruptedException e) {
// Nothing to do here, timing controlled by outer loop.
}
now = System.currentTimeMillis();
}
}
try {
return chain.proceed(chain.request());
} catch (Exception ex) {
if (BuildConfig.DEBUG) {
Request request = chain.request();
Log.e("NETWORK", "Exception during request", ex);
Log.e("NETWORK", "Request was to: " + request.url().toString());
}
throw ex;
}
}

public static void delayAllRequests(long minRequestDelay, long maxRequestDelay) {
if(minRequestDelay == 0 && maxRequestDelay == 0) {
delayAllRequests = false;
} else {
NetworkThrottlingInterceptor.minRequestDelay = minRequestDelay;
NetworkThrottlingInterceptor.maxRequestDelay = maxRequestDelay;
delayAllRequests = true;
}
}

public static void failNextRequests(long failCount) {
if(failCount == 0) {
failRequests = false;
}
else {
failRequestCount.set(failCount);
failRequests = true;
}
}
}

The logic in the interceptor is quite simple, but for verbosity, I’ll still explain it here:

We have two scenarios that we deal with, through this interceptor:

  1. Delay a response for a given network request.
  2. Fail next n network requests.

Scenario 1: Delay a response for a given network request

For this scenario, we set a minimum and maximum value and for a given request we find a random value between this range and ask the thread to sleep for that time.

You can create a different combination of settings that you give access to, through your UI, for example:

  1. Good Network (min = 0, max = 0)
  2. Slow Network (min = 1 second, max =5 seconds)
  3. Very Slow Network (min = 5 seconds, max = 10 seconds)

By default, your app can always be set to work on the Good Network. And then the users can switch to other networks as and when needed.

Scenario 2: Cause next n network requests to fail

For this scenario, we maintain a fail counter that keeps decreasing on each request until it becomes zero. And while this happens we just throw an IO Exception to cause the network request to fail, you can even cause a failure by other means like creating a fake failure response with some status code 5xx.


Interceptor Integration

Injection of this interceptor is quite simple you can add it at the time of configuration of your OkHttp client instance like so.

OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new NetworkThrottlingInterceptor())
.build();

Interceptor Exposure

In our app, we do it through a debug screen that contains a simple Spinner widget that holds all these values that we can select and modify the interceptor configuration at runtime, the code for which looks like this

private void setupNetworkThrottler() {
spNetworkInterceptor = findViewById(R.id.sp_network_throttle);
ArrayAdapter<String> networkSpeedTypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,
new String[]{"Good network", "Moderate network 1-5s delay", "Poor network 5-10s delay"});
spNetworkInterceptor.setAdapter(networkSpeedTypeAdapter);
spNetworkInterceptor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: NetworkThrottlingInterceptor.delayAllRequests(0,0);
break;
case 1: NetworkThrottlingInterceptor.delayAllRequests(1000, 5000);
break;
case 2: NetworkThrottlingInterceptor.delayAllRequests(5000, 10000);
break;
}
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
NetworkThrottlingInterceptor.delayAllRequests(0,0);
}
});
}

If you have other interesting solutions that you can leverage this interceptor for, please share them with me on Twitter where you can find me as @droidchef.

I’d like to give credits to Jonathan Farris, who originally came up with this solution.

This is a trick I learnt very recently from a Senior Android Developer at my company and now I feel miserable about all the time I had spent waiting for Gradle builds to test my changes while writing Android Apps.

Here is a typical scenario every android developer would have come across at least once during their development lifetime. You have a List of items that you want to show in a ListView or RecyclerView.

Below is our beloved onBindViewHolder method that binds your model to your views of the RecyclerView.

    @Overridepublic void onBindViewHolder(ViewHolder holder, final int position) {final String name = values.get(position);        holder.txtHeader.setText(name);        holder.txtFooter.setText("Footer: " + name);    }

Now lets say you wanted to change the text color for every 3rd element in the list. So the code would look something like this

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {

final String name = values.get(position);
holder.txtHeader.setText(name);
if (position % 3 == 0) {
holder.txtHeader.
setTextColor(Color.GREEN);
}
holder.txtFooter.setText("Footer: " + name);
}

Then you’d click on Run and wait for build to finish and see your changes, right?

Copied Image from Anand Shekhar Roy’s post on Speeding up your gradle builds.

Now you’d be thinking what other way could we achieve this?

Welcome Android Studio Debugger, yes we need no external plugin or tool to achieve the above task and more over, we won’t even have to build the project, you heard me, we will by pass Gradle 🙂 Here’s how !

Step 1 — We need to define a Run Config

This run config would allow us to launch our app and attach the debugger from android studio to it, alternatively you can also attach it to an already running process by your hand.

Click on Run -> Edit Configurations

On the Top-Left Corner of the Dialog, Click on the + icon and choose Android App

Now give it a name, I like to call it Run-Only, but you can call it anything.

Choose the module which has your app code, in the below screenshot it is called app.

Important step : 
In Installation Options, Choose Nothing for Deploy.
In Launch Options, Choose Default Activity
In Before Launch, Remove the Gradle-aware Make task.

So the config should look like this screenshot below

Now you can apply and save this config. It should be selected automatically by Android Studio now, if not just select it from the list.

Now apply a Breakpoint some close before the line you’d like to test a change, in our case we’ll put it where we set the text.

Right Click on the Break Point and Uncheck Suspend. Please write back to me on Twitter, if you have never seen this before, I’d very happy to know I showed you something new 🙂

As soon as you uncheck this dialog, you would see this dialog expand with a lot of options.

What we are interested right now is in Evaluate and log. We will write a statement there to test a change in our RecyclerView’s Item. Click on the small blue colored icon next to the dropdown arrow of the Evaluate and log text input box to expand it to a bigger editor and add your testing statement, like this and click Ok and then click on Done.

Now Click on Debug icon with Run-Only Config Selected and see the Magic.

The App Should start from your default activity and you should see the changes applied there, also if you pay close attention to the IDE, on the very bottom you’ll just see one task running that says Launching Activity.

Would love to hear your experiences when you try this trick !! My Twitter Handle is @droidchef

If you are an Android or a Java Developer you’d know about the pain of navigating amongst the classes of a project on Github. You either need to look it up in the tree like this


or use the file finder using the keyboard shortcut “ t ” like this


But while you are looking at the code, and want to jump to another class you have to use one of the above methods unlike what you do in the IDE. You just Cmd + Click and reach the other class, like this

In order to bring the similar kind of navigation to Github, I wrote a chrome extension which will automatically hyperlink all the classes of your project so you can just click to open them in a new tab.

Here it is in action

Installation is simple, just click on this link and once installed just open any of your projects on Github and navigate through the classes like a boss 😎

Wait…there’s more to it! It also links all the classes from the Android SDK to the official documentation, which means now you have almost everything you need to understand the code on Github at your disposal with just a click.


I would love to your hear feedback on this effort. If you like it, just hit the ️💚 icon below and let your friends know about this extension.

The extension is open sourced already, feel free to star and/or watch it, report issues, improvements and features. I’d be more than happy to accept pull requests there.

Github Repo : https://github.com/droidchef/hops

Follow me on twitter : https://twitter.com/droidchef

Cheers!

So its that time of the year again when students will start hustling for their Google Summer of Code proposals, especially since the organizations will begin accepting them from today.

Before you go any further, mark your calendars, April 3, 2017, is the last day to submit your proposal.


1. Structure of the proposal

Portrays you as an organized person

The most important thing that you must keep in mind always while writing your proposal is that your proposal is your best advertisement.

The flow of this advertisement (story) of selling the product (yourself) to the customer (org/mentor) is in your hands. So why not structure it in such a way that the person going through it, gets so engrossed as if you were going to tell them about the death of the next character in Game of Thrones.

2. Identify the Problem, Propose the solution

Shows you’ve understood the project

Clearly define the problem that you wish to solve through this project. Brownie points, if you can also tell why is this a problem because it’ll tell the reader that you’ve taken a step forward to understand the underlying idea of the project.

Mention the technical aspects of the project. This part of the proposal can be and should be lengthy, as it is nice to give a long detail description of how you are going to complete the project.

Try to highlight:-

  • Things that you find challenging.
  • Things that you have no idea about, at the moment.
  • Any other blockers you might have.

Then, also mention how do you plan to overcome all these hurdles.

3. Deliverables — with bullets

Show you’re result oriented

A good proposal should always contain deliverables. These are the things you want to deliver or goals you want to achieve in order to be able to successfully pass all the evaluations and graduate as a successful GSoC student.

Break them down into smallest pieces possible.

This’ll give you confidence during the program when you can start checking off things from your list.

4. Well Defined — Timeline

Depicts how you manage time

This can be a game changer at times when choosing amongst students who are competing for the same project.

A humble, realistic and detailed timeline is much better than a timeline that promises to move mountains.

  • Show weekly goals
  • Dedicate enough time for writing tests and documentation.
  • Honestly tell about any other activity that you are going to do during the summer, which will take up significant amount of time, including but not limited to: exams, classes, travel and vacation days, internships, jobs, volunteer work etc.

5. About Me — Go nuts bragging about yourself here

This has to be a section more or less acting like a CV for you. Tell about yourself here, give all the channels of communication you use.

Here are some that a lot of people in open source use (so make sure you have everything already setup) :

  • IRC
  • Jabber
  • Skype
  • Email
  • Google Hangouts

Don’t forget to mention about your Open source contributions here, if they are in the same organization/project very well! If not, you can still mention.

6. Iterate while you can

Don’t be in a hurry to submit the proposal. It is completely fine to submit it on the last day since organizations will usually not start reviewing them before the that.

Get it reviewed from as many sources as you can.

Most importantly from your:

  • Mentors
  • Previous GSoC students
  • Someone who has relevant expertise in the tech stack or the project that you are working on. (You can get the problem and solution part reviewed from them, they might even give you a better idea to approach the problem.)

7. Images worth 1000 words

Show your dedication

Try investing some time in creating and adding mockups, flow charts, diagrams or anything relevant you find can be pictorially represented.

I’d be more than happy to review your proposals. Head over to this GitHub project and send in your proposal as a PR for the review.

Since git is an integral part of my development life cycle and I spend quite sometime committing things to it, I always felt there was something missing, until I did my Android Nanodegree at Udacity where I learned about structured commits.


Why structure your commits?

  1. Keeps your git history neat & meaningful.
  2. Easy to generate change logs

Lets look at how I structure my commits.

The Commit Prefixes

  • feat — a new feature
  • fix — a bug fix
  • docs — changes to documentation
  • style — formatting, missing semi colons, etc; no logical code change
  • refactor — refactoring production code
  • test — adding tests, refactoring test; no production code change
  • chore — updating build tasks etc; no production code change

But you’ll be wondering how is it productive when you have to type those tags into each commit message.

So here’s a script you might want to see

https://github.com/ishan1604/productivity/blob/master/commit

Just put it into your PATH and access it easily like so

$ commit feat

So now when I do

git log --oneline --decorate --graph

Here is what it yields

This is just half the fun

Now when I want to generate a change log, I have a python script that picks up all the commits with the tags feat or fix to generate a change log for me.

Here is the python script

https://github.com/ishan1604/productivity/blob/master/commit

So the output of the python script looks something like this in a change-log.json file

{  
"features":[
"feature 1",
"feature 2",
"feature 3"
],
"fixes":[
"fix 1",
"fix2",
"fix 3"
],
"major":0,
"minor":9,
"patch":11
}

You can then use this to easily curate your CHANEGLOG.md or tell your boss what you did over the last X days.

You can change this variable in the python script on line number 14 to generate the change log from the date you want

afterDate = '2016-09-12'

I’ll be adding more productivity related stuff to it soon. Till then you can give some love to the repo.

https://github.com/droidchef/productivity/