MODIFY /etc/hosts on Genymotion device

Need to be a root user:

 sudo su

Once you are a root user, need to execute:

./adb shell

When you are in, open the file and edit it.

 vi /etc/hosts

Espresso Google – Let’s see some examples

Doubt about Android testing? I show you what I did…
After long time using Robotium, I decide to try Google Espresso and I have to say I’m happy of this change.

Why I’m happy about it?

Pro Espresso:

    Byebye solo.sleep()! Yes you read well, Espresso understand when the UI is still running before let you fail the test
    Fast. Fast. Faaaaast.

Pro Robotium:

    Much easy to write code. The learning curve is faster than Espresso
    Easy to read test. They look more readable even from a non technical person

….But I did not find good example of Espresso, so I decide to create a public repository on Github with many simple (and not only) examples about using Espresso. Clone it or just start watching it: https://github.com/onivas/EspressoPlayGround

Here a fast Espresso sheet: https://code.google.com/p/android-test-kit/wiki/EspressoV2CheatSheet

How to get a View while testing [with Android Espresso]

I was trying Google Espresso for testing Android apps (it is pretty nice and fast), but I got stuck while I was trying to tap a custom (in my case was a checkbox and a linked text) view and the onView(withId(R.id.checkbox_id)).perform(click()); fails every times. Text link was clicked but checkbox wasn’t checked.

Question? Can I get the view and use coords to perform click?
Answer: Yes!
Note: The custom view is not on Activity test rule

Let’s see how to do:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class EspressoTest {

  @Rule
  public ActivityTestRule mHomeRule = new ActivityTestRule<>(Home.class);
/**
 * Need to add HONEYCOMB because the clickXY() action needs
 * YOUR_ACTIVITY_NAME = the Activity that contains the view
 */
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  @Test
  public void letsClickWithCoords(){
// Click the button that open the activity that contains our custom view
  onView(withId(R.id.open_activity)).perform(click());
Instrumentation.ActivityMonitor monitor =  getInstrumentation().addMonitor(YOUR_ACTIVITY_NAME.class.getName(), null, false);
  Activity currentActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 5);
 [..do something until the view is visible…]
 View v = currentActivity.findViewById(R.id.checkbox_id);
 onView(withId(R.id.paid_options_tos)).perform(clickXY(v.getX(), v.getY()));
 }

 [...]
 public static ViewAction clickXY(final float x, final float y){
   return new GeneralClickAction(
   Tap.SINGLE,
   new CoordinatesProvider() {
    @Override
    public float[] calculateCoordinates(View view) {
     final int[] screenPos = new int[2];
     view.getLocationOnScreen(screenPos);
     final float screenX = screenPos[0] + x;
     final float screenY = screenPos[1] + y;
     float[] coordinates = {screenX, screenY};
     return coordinates;
     }
   },
   Press.FINGER);
 }

Menu Animation for Android

Published code for a cool menu animation.

Grab the code: https://github.com/onivas/MenuAnimation

AdMob + Google Play Services + Android Studio

I have to admit it, I spent few hours before clearly understand how to include adMob banner inside an Android app using Android Studio, here it is how to do!

  1. Update build.gradle
  2. Add permission in AndroidManifest
  3. Modify layout
  4. Load the request in onCreate()
1. We have to first add a new dependencies in build.gradle (5.0.77 modify this number using the last play services available version)
dependencies {
 ...
    compile 'com.google.android.gms:play-services:5.0.77'
}
2. Let’s add some mew permissions and somethings more:
...
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application...
        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
3. Now I’m going to modify the layout to add the banner – Remember to put your adUnitId (Get it from adMob website)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
 xmlns:ads="http://schemas.android.com/apk/res-auto"
    ... >

    <com.google.android.gms.ads.AdView android:id="@+id/adView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 ads:adUnitId="ADD_HERE_YOUR_UNIT_IT"
 ads:adSize="BANNER"/>

</LinearLayout>

4. In our last step we have to load the banner. I do it during onCreate.

...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Look up the AdView as a resource and load a request.
 AdView adView = (AdView) this.findViewById(R.id.adView);
 AdRequest adRequest = new AdRequest.Builder().build();
 adView.loadAd(adRequest);
    }
...

 

And now you are ready to get money :)

Android Communication

In this example I’m going to show how to communicate between fragment-activity, activity-activity and how to set a fragment variable from the activity.

In short: fragment_1 –> activity_1 –> activity_2 –> fragment_2

In this first example we will see how a fragment (fragment_1) passes a value (list item position in our case) to the activity (activity_1) by using an interface.

Fragment_1

public class ItemListFragment extends Fragment implements AbsListView.OnItemClickListener {
public static final String POSITION_MAIN_LIST = "ItemListFragment.list.position";
...
   @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        ((OnFragmentInteractionListener) getActivity()).onFragmentInteraction(position);
    }

    /* interface */
    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(int position);
    }
}

 

Activity_1

..and here how to get the position and start another activity (activity_2) passing the position value.

public class MainActivity extends ActionBarActivity implements ItemListFragment.OnFragmentInteractionListener {

...
    @Override
    public void onFragmentInteraction(int position) {

        Intent i = new Intent(this, SecondActivity.class);
        i.putExtra(ItemListFragment.POSITION_MAIN_LIST, position);
        startActivity(i);
    }
...
}

 

Activity_2

In this activity we get the position value by reading the Intent and pass it to the fragment_2 by calling a fragment method (updatePosition()) directly from the activity.

public class SecondActivity extends ActionBarActivity {

    int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        Intent i = getIntent();
        position = i.getIntExtra(ItemListFragment.POSITION_MAIN_LIST, 0);
        onItemListSelected(position);

    }

    public void onItemListSelected(int pos) {

        ItemGridFragment gridFragment = (ItemGridFragment) getSupportFragmentManager()
                .findFragmentByTag("second_list");

        if (gridFragment != null) {
            gridFragment.updatePosition(pos);
        }
    }

Fragment_2

..and this is the method called by the activity.

public class ItemGridFragment extends Fragment implements AbsListView.OnItemClickListener {
    int positionMain;
...
    public void updatePosition(int pos) {
        this.positionMain = pos;
    }
...
}

Autoplay video after ajax call

Here I’m going to show how to play a video automatically after an ajax call.

// this is a snapcode of the js that let the audio play

document.getElementById(“srcVideo”).src=xmlhttp.responseText; document.getElementById(“srcVideo”).play();

And here the HTML code used for the player (video source)

<div id=”player-overlay”>

<video id=”video”>
<sourcesrc=”video_file.mp4″ type=”video/mp4″ id=”srcVideo” />
</video>
</div>

 

Otto an event bus in Android

If you have an app where parts of it need to communicate by exchanging messages (events), you can easily use Otto. What is Otto?

Otto is an event bus used to allowing communication among different parts of the application.

See http://square.github.io/otto/ for more details.

Here I’m going to show a dummy project to see how Otto works. What we want to do is:

  • Fragment 1 sends an event by pressing a button
  • The Activity reads the event and modify a textView of Fragment 2

First of all, we are going to create the Bus Provider class:

package com.savinoordine.otto.test;
import com.squareup.otto.Bus;

public final class BusProvider {
  private static final Bus BUS = new Bus();

public static Bus getInstance() {
  return BUS;
}

private BusProvider() {}
}

 

The application consisting in 2 fragments and an activity. Let’s see first the fragments code:

package com.savinoordine.otto.test;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class Frag1Fragment extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
  Bundle savedInstanceState) {

  View view = inflater.inflate(R.layout.fragment_frag1, container, false);
  Button getButton = (Button) view.findViewById(R.id.button_get);
  getButton.setOnClickListener(new View.OnClickListener() {
  @Override
    public void onClick(View v) {
      BusProvider.getInstance().post(new fragm1Event("fragment1OttoEvent") );
  }
});

return view;
}

public class fragm1Event {
 String message;
  public fragm1Event(String message) {
    this.message = message;
  }
 }
}

 

And this is the second fragment:

package com.savinoordine.otto.test;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Frag2Fragment extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
  return inflater.inflate(R.layout.fragment_frag2, container, false);
}
}

 

Let’s see how activity read the event and modify the Fragment 2.

package com.savinoordine.otto.test;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.widget.TextView;
import com.squareup.otto.Subscribe;

public class MainActivity extends Activity {
 FragmentManager fm;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  fm = getFragmentManager();
}

@Override
public void onPause() {
  super.onPause();
  BusProvider.getInstance().unregister(this);
}

// you need to register the activity
@Override
public void onResume() {
  super.onResume();
  BusProvider.getInstance().register(this);
}

// Here you get the event and modify the fragment2 (fragment1Event)
@Subscribe
public void onFragm1Event(Frag1Fragment.fragm1Event event) {

  Fragment f2 = fm.findFragmentByTag("f2");
  TextView tv = (TextView) f2.getView().findViewById(R.id.f2_text);
  tv.setText(event.message);
  }
}

 

Here the activity layout with the two fragments (I omitted the fragments layout for clarity)

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" >

<fragment
android:tag="f1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.savino.tryit.app.Frag1Fragment">
</fragment>

<fragment
android:tag="f2"
android:id="@+id/f2_id"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.savino.tryit.app.Frag2Fragment">
</fragment>

</LinearLayout>

 

 

 

Arduino first steps

Check it here…. Arduino first steps

Android Studio + gradle + Windows 7

Android Studio + Windows 7 + gradle = Gradle project sync failed error

I always got the error below in my log file

 Error occurred during initialization of VM
 Could not reserve enough space for object heap
 Error: Could not create the Java Virtual Machine.
 Error: A fatal exception has occurred. Program will exit.

 

I tried many solutions, as clean project, remove .idea file/folder, restart Android Studio, but no one of those worked for me.

After many trials, I got the final solution, and it perfectly works for me! You need to modify the Xmx value, follow the steps:

  1. Control Panel
  2. System
  3. Advanced(tab)
  4. Environment Variables
  5. System Variables
  6. New
 Variable name: _JAVA_OPTIONS
 Variable value: -Xmx512M

 

…and your nightmare disappears!