AVD Android 5 / Lollipop ‘storage space running out’ warning

Whilst testing some code differences for Lollipop (5.x) compared to older Android versions I created an Android Virtual Device (AVD) with API 22 (Google APIs) through AVD manager in Android Studio.

When running (debugging or running normally) the warning ‘Storage space running out’ came up every time.

AVDStorage

Looking at the AVD through AVD Manager in Android Studio, only 200 mb internal space was allocated.

I increased that by editing the AVD (click on the pencil icon to the right of the AVD item in AVD manager), and then click on the ‘Show Advanced Settings’ button.

Under ‘Memory and Storage’ is ‘Internal Storage’ – this was set to 200 mb in my test.  Change to a larger value – I used 600mb – and click ‘Finish’ button.

AVDChangeStorage

Once the updated AVD has been saved, you still need to clear the data (I had to in mine).  Drop down the ‘Actions’ menu for the AVD line item and select ‘Wipe Data’

AVDWipe

Restart the AVD and error is gone.

 

ADB update in Android Studio – GLIBC_2.14 / GLIBC_2.15 not found

Update through Android Studio last night, wasn’t really concentrating on the update but looked to be ADB / SDK update.  Running Android Studio 1.5 on Debian.  This morning started Android Studio to put in place some code (whilst still fresh in mind after dreaming it) I get the following error:

Unable to create Debug Bridge: Unable to start adb server: Unable to detect adb version, adb output:
/fullpath/Android/Sdk/platform-tools/adb: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.14' not found (required by /fullpath/Android/SDK/platform-tools/adb)
Same line as above repeated for `GLIBC_2.15'

Running from the command line gives same :

./adb: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.14' not found (required by ./adb)
./adb: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.15' not found (required by ./adb)

To get the version of libc can run ‘ldd –version’ (https://en.wikipedia.org/wiki/Ldd_(Unix)) :

/Sdk/platform-tools# ldd --version
ldd (Debian EGLIBC 2.13-38+deb7u8) 2.13
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Roland McGrath and Ulrich Drepper.
Did :
apt-get update
apt-get install libc6

however libc6 already the newest version for the distro (Debian Wheezy – 7.9): ls_release -a gives details of the release.

Possible to fudge libc (eglibc in Debian) to use newer version within Debian 7 (Wheezy), however Debian releases showing Wheezy as obsolete.  https://www.debian.org/releases/ .  Upgrade to Debian 8 (Jessie) likely best solution.

This link gives a post on stackexchange which gives solution against Debian 7 (Wheezy) : http://unix.stackexchange.com/questions/85505/need-to-install-glibc-2-14-on-wheezy

 

 

Pusher test using Android Studio 1.5

Testing out Pusher (pusher.com) message system / service by knocking up a simple Android client app using Android Studio 1.5.

Create a free account at https://pusher.com (link on top right) and make a note of the app_id and most importantly the key.

Pusher give a basic example of an Android client in the documentation : https://pusher.com/docs/android_quick_start , using the test account just created, a customized version (with your key in place) is available under your Pusher dashboard : https://dashboard.pusher.com/ , then click on the relevant App

A more in depth example from Pusher is in their blog : https://blog.pusher.com/build-an-android-chat-app-with-pusher/

In this post, I am going to knock up a basic client which will connect to the test channel and receive events.  I used Android Studio (1.5).

Initial Project Setup

In build.gradle – project level, add the Mavern repository http://clojars.org/repo .  Add this to buildscript repositories and allprojects repositories, like this (click image for readable screenshot):

PusherGradle1

When attempting to sync, if you have not added to allprojects,  gradle will give the following error:

Error:Failed to resolve: org.java-websocket:java-websocket:1.3.1<a href=”openFile:/path/PusherTest/app/build.gradle”>Open File</a><br><a href=”open.dependency.in.project.structure”>Show in Project Structure dialog</a>

Solution is to add to allprojects.

You can add to allprojects through the Android Studio UI if preferred.  In Android Studio, goto File -> Project Structure.  In the resulting popup window goto ‘Project’, then add ‘http://clojars.org/repo’ after under ‘Default Library Repository’ after jcenter:

PusherGradle2

In the Module build.gradle, add pusher-java-client and android-async-http.  The pusher-java-client info is given in Pusher’s android quick start.  async-http is taken from the fuller example in Pusher’s blog.

If copying from Pusher’s blog (https://blog.pusher.com/build-an-android-chat-app-with-pusher/) you need to remove the extraneous commas from the gradle dependences section, so:

compile 'com.loopj.android:android-async-http:1.4.9', // for our HTTP requests later

becomes

compile 'com.loopj.android:android-async-http:1.4.9' // for our HTTP requests later

The module gradle should have the following added (first taken from pushers quick start, the second taken from pushers fuller example in the blog – chat app):

PusherGradle3

This gets a basic project to the stage where pusher API objects can be utilised.

Simple code to connect and display incoming messages

For this test I wanted a very simple client which connected to a test channel and simply display any incoming messages.

For debugging / logging I added implements of com.pusher.client.connection.ConnectionEventListener (very useful for seeing why the connect does not work!), and also com.pusher.client.channel.SubscriptionEventListener (to receive the events).

For simplicity and ease of reading, I implemented into the main activity, and created functions in the main activity class:

public class MainActivity extends AppCompatActivity implements SubscriptionEventListener, ConnectionEventListener{

Make sure ConnectionEventListener is the com.pusher type and not javax.sql.

The 3 methods related to the 2 interfaces are:

@Override
public void onEvent(String strChannel, String strEventName, String strData) {
    // pusher Channel SubscriptionEventListener
    showMessage("Pusher Event : " + strChannel + ":" + strEventName + ":" + strData);
}

@Override
public void onConnectionStateChange(ConnectionStateChange connectionStateChange) {
    // pusher Connection listener
    showMessage("Connection State Change: "+connectionStateChange.getCurrentState().toString());
}

@Override
public void onError(String s, String s1, Exception e) {
    // pusher Connection listener - on Error
    showMessage("Connection Error: "+e.getMessage());
}

showMessage is a simple function which displays a Toast using runOnUiThread :

public void showMessage(final String strMessage) {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast toast = Toast.makeText(getApplicationContext(), strMessage, Toast.LENGTH_LONG);
            toast.show();
        }
    });
}

The imports for my main activity now have these additional imports:

import com.pusher.client.Pusher;
import com.pusher.client.PusherOptions;
import com.pusher.client.channel.Channel;
import com.pusher.client.channel.SubscriptionEventListener;
import com.pusher.client.connection.ConnectionEventListener;
import com.pusher.client.connection.ConnectionStateChange;

Add some private variables for object instances and also for the key, channel name etc (could have used string resource) :

private static String coPusherKey = "yourkeyvalue";
private static String coChannel = "my_channel";
private static String coEvent = "new_message";
private Pusher pushTest = null;
private Channel pushChannel = null;
private PusherOptions pushOptions = null;

Then in the onCreate for the activity, simply add the following code (the PusherOptions is not required – I added whilst testing)

pushOptions = new PusherOptions();
pushOptions.setEncrypted(true);
pushTest = new Pusher(coPusherKey, pushOptions);

pushTest.connect(this);

pushChannel = pushTest.subscribe(coChannel);
pushChannel.bind(coEvent,this);

Pusher.connect takes no parameters in the Pusher example – I added ‘this’ as implementing ‘ConnectionEventListener’.

The ConnectionEventListener is very useful as without this it is not apparent why the connection is not working (or even if it is working).  Running through debugger pushTest.connection.state == ‘DISCONNECTED’.

Pusher1

Having the ConnectionEventListener enables visibility into the status changes and also through ‘onError’ to get information on the problem occurring when a connection fails.  showMessage could/should write to log etc but visual testing, so using a Toast.  Running gives the following:

PusherError

This tells us that the Internet permission is needed for the Android application.  Add the permission to the Manifest :

<uses-permission android:name="android.permission.INTERNET"/>

PusherManifest

This is now a functioning Android application which connects to the channel and displays any events incoming.

To test open a browser and go to your Pusher account, then navigate to the debug console and enter a test message (I used the default).  Finally click the ‘Send Event’ button.  The message will appear in your running Android application.

The message then appears in the android app.

PusherMessageReceived

 

 

Removed Handler code

Whilst battling with the issues of a callback from a thread updating the UI, I had implemented a handler to call the method which updates the UI.  More recent solution for another thread was to use ‘runOnUIThread’ which works well (see previous post).

Removed the handler code

final android.os.Handler handler = new android.os.Handler() {
    public void handleMessage(Message msg) {
        if (msg.arg1 == 1) {
            DisplayQuestion(questionAsker.getCurrentQuestion());
        }
        // OK so call the DisplayQuestion here
    }
};

and replaced with runOnUiThread:

public void onFDDisplayQuestion(Question qstCurrent) {
    // Removed message code and replaced with runOnUIThread.
    /*
    Message msg = handler.obtainMessage();
    msg.arg1 = 1;
    handler.sendMessage(msg);
    */
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            DisplayQuestion(questionAsker.getCurrentQuestion());
        }
    });
    // DisplayQuestion(qstCurrent);
}

runOnUiThread utilises handler anyway if needed.

Next I’m going to look at using AsyncTask : http://developer.android.com/reference/android/os/AsyncTask.html

Android TextToSpeech onUtteranceCompleted : android.view.ViewRootImpl$CalledFromWrongThreadException solution

Moved the runOnUiThread to the interface function used by the call back to make the UI update instead :

@Override
public void onSoundComplete(String strSoundID) {
    runOnUiThread(new Runnable() {
        public void run() {
            TextView lblSound = (TextView) findViewById(R.id.lblCallback);
            lblSound.setText("In Soundcall back: "+nCount);
        }
    });
}

Solution was found here : http://stackoverflow.com/questions/12134766/how-to-access-layout-in-tts-onutterancecompleted-callback

Works great in test app.  Update: Works fine in actual application also.

 

Android – Layout

After design / preview issues a couple of days ok were resolved, now needed to have multiple lines of controls for test program.  Two lines needed one to display (and have button) a simple counter, the second line to display text when a call back from the sound thread received.  It is a simple test program to work out problems with counter and separate thread for sound, and updating the UI from a call back from the sound or counter thread.

Changed primary layout within the content.xml to LinearLayout with orientation as vertical:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    .. CUT ..
    android:orientation="vertical"
    >

Then had two embedded layouts (one for each line):

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:text="Counter: " />
    <TextView
        android:id="@+id/lblCounter"
        />
    <Button
        android:id="@+id/button"
        android:onClick="btnNumberClick" />
</LinearLayout>

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/lblCallback"
            />

</LinearLayout>

Content of the controls removed to save space.

 

 

 

Android Studio – Design layout preview

With :
app:layout_behavior=”@string/appbar_scrolling_view_behavior”
in the content_main.xml (included from activity_main.xml) the layout on the running App is correct, but it fails to display in Android Studio (version 1.5).

Removing from the XML results in rendering, but misplaced (IE under the toolbar) content.

Solution: In Design / Preview view, switch to using Android 6 (API 23) – I had to install API23 to enable this.AndroidStudioDesignPreview

After doing this, design / preview works for API22,21 and 19.  15 and 14 with issues (due to class differences)

Blank layout preview / design preview in new Android Studio project

So after creating the new Gitlab repository and corresponding Android Studio project, the design preview / layout was no visible at all for the main activity (the default blank activity created).

To get around this do the following :

Clean Project, then Build Project under the ‘Build’ menu:

AndroidStudioCleanAndBuild

After this, the preview appears, however with the following issue on rendering :

Rendering Problems
Missing styles. Is the correct theme chosen for this layout?
Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.

The following classes could not be instantiated:
– android.support.design.widget.FloatingActionButton (Open Class, Show Exception, Clear Cache)

Had also recently updated Android Studio, so possible that Caches issues.  Tried Invalidate Caches/Restart :

AndroidStudioInvalidateCaches

Now getting blank preview (nothing appearing) again – Clean and Rebuild no change.

Tracked down to the include of @layout/content_main (which includes the “hello word”)

This line in the content_main.xml is causing render failure :

app:layout_behavior=”@string/appbar_scrolling_view_behavior”

Added the following to ../Android/Sdk/tools/proguard/proguard-android.txt however (even after clean and rebuild) still didn’t fix:

-keep class android.support.design.widget.** { *; }
-keep interface android.support.design.widget.** { *; }
-dontwarn android.support.design.**

Suggestion from : http://stackoverflow.com/questions/30562330/using-appcompat-layout-behavior-with-string-appbar-scrolling-view-behavior

Removed and works (although layout is no good)