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!

Uninstall Applications using ADB

If you need to uninstall an App on your phone, you can do it using adb (Android Debug Bridge).

The path to execute adb is <sdk>/platform-tools

adb uninstall <package name>

 

Tip. To get in the sdk folder, try to execute “cd $ANDROID_HOME

Windows 7.. or maybe not

I use Windows 7 on my PC and today I see a really funny thing… typical of Windows.

As I said, I use Windows 7, but seems “they” forget to change a text on Disk Cleanup window :) …Now I’m confuse, maybe I have Windows Vista and I never knew it!

 

How to ignore “KEY is not translated in LANGUAGE” in Eclipse

If you are using Eclipse, go in Window -> Preferences -> Android -> -Lint Error Checking and find Missing Translation. Change the value to Warning and apply it.

 

 

Otherwise, you can create a lint.xml file in your project like this:

<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <issue id="ExtraTranslation" severity="warning" />
    <issue id="MissingTranslation" severity="warning" />
</lint>

It’s very..

It’s very easy to be different,

but very difficult to be better.

-

Jonathan Ive