Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

2016/09/21

Collection of App Inventor 2 Tips

Here is a collection of App Inventor 2 tips which I find very helpful. More will be added when I come across them in the future.

General / Beginner

Android Development for Beginners
https://www.youtube.com/watch?v=ugWu3gyte4I

AI2 Text Blocks
http://appinventor.mit.edu/explore/ai2/support/blocks/text.html

AI2 http://appinventor.mit.edu/explore/content/math-blocks.htmlMath Blocks

Example 1. How do you start and pause a sound file when the user clicks a button?
http://www.appinventor.org/content/howDoYou/Conditionals/startStop

2016/09/18

App Inventor 2 + Arduino - Controlling Arduino via Bluetooth using an Android Phone

This is a simple example on how to control the on/off of the LED attached to pin 13 of an Arduino Uno board using an Android App. developed using MIT App Inventor 2.

Schematic

- HC-06 RXD -> Arduino Uno Pin 3
- HC-06 TXD -> Arduino Uno Pin 2
- HC-06 GND -> Arduino Uno GND
- HC-06 VCC -> Arduino Uno 5V

2016/09/15

App Inventor 2 - Add Play / Pause Feature To The Song Player App.

This post is the continuation of my 2 previous posts on AI2 (see below links).

Learning Android Programming Through MIT App Inventor 2
http://wei48221.blogspot.tw/2016/09/learning-android-programming-through.html#more

App Inventor 2 - How to Duplicate Project
http://wei48221.blogspot.tw/2016/09/app-inventor-2-how-to-duplicate-project.html#more

In "Learning Android Programming Through MIT App Inventor 2", I created a simple App. which plays back a song when the image (which represents a button) on the screen is touched. In this post, I want to add the start -> pause -> start (resume) feature. That's, when the image is touched for the 1st time, the App. will play back the song. When the image is touched again, the playback is paused. The playback is resumed when the image is touched again.

Below is a simple flow chart showing the entire process.




2016/09/14

Android Studio 2.2 - How to solve the issue of "Warning: [I18N] Hardcoded string......."

When seeing warning message such as "Warning: [I18N] Hardcoded string......." it means that instead of using a string resource to hold the string, the string is hard coded into the App. Hard coding the string into the App. is not recommended because it makes it difficult for the App. to support multiple languages.



Android Studio 2.2 - How to solve the issue of "Error. The id "textView" is not defined anywhere. Did you meant textView2?"

This is a quick summary of how to solve the issue of "Error. The id "textView" is not defined anywhere. Did you meant textView2?"

Description:

When viewing the layout in Design view mode. There is a warning mark on the upper right corner of the Design view window (circled in red in the below photo).


2016/09/07

Learning Android Programming Through MIT App Inventor 2

To me, the most difficult part in doing Android programming is in knowing details such as which libraries to be included, which functions to be invoked, what parameters to pass, etc..

While searching for ways to solve my problem, I came across a video called "Convert App Inventor to Java" (https://www.youtube.com/watch?v=FqNTc4DVYW8). I found that the way Derek converted his App. made with App. Inventor into Java seemed like a good solution.

This is a quick summary of how I created an App. using App Inventor 2 and re-wrote it in Java using Android Studio 2.2.

The App. that I made using App Inventor 2 is a very simple App. that plays back a song whenever I click on the picture on the screen. The detail on how to build this App. can be found at http://www.appinventor.org/content/CourseInABox/Intro/courseinabox.

The MIT App Inventor 2 is available for free at http://ai2.appinventor.mit.edu/.

App. developed using MIT App. Inventor 2

2016/09/06

Android Studio 2.2 - What SDK components to download and install

This is a quick summary of what SDK components to download and install for Android Studio 2.2.

Below is a diagram that shows the distribution of various Android platforms and their API levels. When you click on a platform on the left in Android Studio, the features available since that platform are shown on the right.


2015/12/12

Beginner's Android App Development - Simplest Price Comparison

This post is a summary of my 1st Android App. This App allows its user to enter the price and quantity per package (bag, can, pound, kg, inch, meter, etc.) of a product and calculate and keep the unit price in a list for easy comparison. I developed this App to help me find the product with the lowest unit price when I face similar products of different quantity and price.

Sample Screen Shots


Source Code

MainActivity.java



Layout

activity_main_add_header.xml



about.xml



Manifests

AndroidManifest.xml



Download & Installation:

This App can be found at the link below.

https://play.google.com/store/apps/details?id=com.whhuang.simplest_price_compare&hl=en

This is a work in progress as I am very new to Android App. development. I welcome any comments and suggestions on how to improve my skill and this App.

Further Works:
- Add support for multi-language (English, Chinese);
- Support for different screen resolutions;
- Take photo of the product and represent each product with its photo;
- Save result to local storage space;
- Save result to cloud storage;
- Beautify the UI.

2015/05/16

Solution to problem uploading APK to Google Play Store

Solution to problem uploading APK to Google Play Store

Problem:

Upload failed
You need to use a different version code for your APK because you already have one with version code 1.


Solution:

In addition to updating the “android:versionCode” and ”android:versionName” in AndroidManifest.xml, the “versionCode” and “versionName” in build.gradle also need to be updated.



AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.whhuang.simplest_price_compare"

    android:versionCode="3"
    android:versionName="1.3">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.whhuang.simplest_price_compare"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 3
        versionName "1.3"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

After the APK is successfully uploaded, a summary sheet similar to the one below will appear.



Reference: http://stackoverflow.com/questions/24772407/upload-failed-you-need-to-use-a-different-version-code-for-your-apk-because-you

2015/05/11

Android Button and AlertDialog Sample

This post is about Android Button and AlertDialog Sample.

MainActivity.java

package com.example.wei_hsiunghuang.helloworld;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

    Button showMsgBtn;

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

        // ** Added for the Android Button and AlertDialog sample **

        showMsgBtn = (Button) findViewById(R.id.btnShowMsg);
        showMsgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               // the following codes are from Stack Overflow
               // http://stackoverflow.com/questions/13268302/alternative-setbutton

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Alert Title")
                .setMessage("Alert Message String")
                        .setCancelable(false)
                        .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // here you can add functions
                                dialog.cancel();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });

        // ** End of the added codes **

    }

    // The following codes are provided by Android Studio upon project creation

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Message"
        android:id="@+id/btnShowMsg"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="72dp" />
</RelativeLayout>


- Development Environment: Android Studio 1.2.
- Other than the above 2 files, all other files of this project remain unchanged.

2015/04/14

2015/04/11

Declaring DeviceListActivity in AndroidManifest.xml

Logcat output

04-10 16:47:14.546  13580-13580/com.example.wei_hsiunghuang.my1stbluetooth E/AndroidRuntime FATAL EXCEPTION: main
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.wei_hsiunghuang.my1stbluetooth/com.example.wei_hsiunghuang.my1stbluetooth.DeviceListActivity}; have you declared this activity in your AndroidManifest.xml?
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
-----------------------------------------------------------------------------------------------------------------
The DeviceListActivity is indeed missing in the AndroidManifest.xml.

AndroidManifest.xml – Original Version

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.example.wei_hsiunghuang.my1stbluetooth" >

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

    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:theme="@style/AppTheme" >
        <
activity
           
android:name=".MainActivity"
           
android:label="@string/app_name" >
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />
                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
    </
application>

Check and make sure that “DeviceListActivity.java” is in the project before adding the declaration for it in AndroidManifest.xml



AndroidManifest.xml – Updated Version

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.example.wei_hsiunghuang.my1stbluetooth" >

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

    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:theme="@style/AppTheme" >
        <
activity
           
android:name=".MainActivity"
           
android:label="@string/app_name" >
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>

        <
activity
           
android:name=".DeviceListActivity"
           
android:label="@string/select_device"
           
android:theme="@style/DialogTheme" />

    </
application>

</
manifest>

---------------------------------------------------------------------------------------------------------------------------

The @style/DialogTheme is defined in res/values/styles.xml.

Styles.xml - Original Version

<resources>
   
<!-- Base application theme. -->
   
<style name="AppTheme" parent="Theme.Sherlock"/>
</
resources>

---------------------------------------------------------------------------------------------------------------------------

Styles.xml - Updated Version

<resources>
   
<!-- Base application theme. -->
   
<style name="AppTheme" parent="Theme.Sherlock"/>
    <
style name="DialogTheme" parent="@android:style/Theme.Dialog"/>
</
resources>


Solution to Problem Launching Android Device Monitor In Android Studio

Encironment:
-          Android Studio 1.2 Beta
-          Windows 8.1 64-bit

Problem:

When launching Android Device Monitor in Android Studio, a window pop up with the error message “An error has occurred. See the log file……”


Window with error message


The log file.


Solution:

This problem can be solved by launching Android Studio in “Administrative Mode”.

1.      Close Android Studio;
2.      Right click on the shortcut for Android Studio then click on “Properties”;



3.      Click on “Compatibility” and check the box for “Run this program as an administrator”;


4.      Click on “Apply” then “OK” to clock the window;

5.      Click on the shortcut for Android Studio to launch the program. Click on “Yes” when asked whether to allow Android Studio to change the computer setting;

6.      Lunch Android Device Monitor again.



2015/04/05

Android Chats with Arduino via Bluetooth

This project allows Arduino Uno to receive the text sent from Android to it via Bluetooth connection and display the received text on the LCD attached to Arduino Uno. In addition, Arduino Uno will periodically send text to Android via the same Bluetooth connection and the received text will be display on Android.

1.      Wiring Diagram


2.      Arduino Code

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>

// initialize the LCD library with the numbers of the Arduino digital pins above
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

SoftwareSerial nss(2, 3); // (RX, TX)

int const chatInterval = 30000; // after 30 seconds, send a message to the connected Android device.
int numberOfTimesToSend = 2; // the number of times to send the message (spaced out by number of chatInterval above)
int lastChatSendTime = 0; //the last time - in millis() - that we sent a message to the Droid
String chatMessage = "Hello from Arduino"; // change this to anything you want to send to the Android device
int chatSendCounter = 0; //the number of times we've sent the message

void setup()
{
 
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  // serial port communications from Arduino to Bluetooth Firefly module (BlueSMiRF Gold)
  // BlueSMiRF Gold defaults to 115.2k BAUD.  Change to 57.6k BAUD.
  // Don't ever use low BAUD like 4800 and 9600. 
  nss.begin(19200);  // was 57600
 
  //clear parallel LCD and set the cursor to the first row, first column.
  lcd.clear();
  lcd.setCursor(0, 0);

  //reset the timer so we can send a message to the Droid in "chatInterval" seconds from now (30 seconds unless you change it in initialization above)
  lastChatSendTime = millis();

}

void loop()
{
  //*************receiving a message from Android and printing on Arduino*************************
  if (nss.available())
   {
     lcd.write(nss.read()); //get message from Android device on the Arduino NewSoftSerial serial port and print it out on the LCD
   }

   //*************sending a message from Arduino to Android *************************  
   if (((millis() - lastChatSendTime) > chatInterval) && (chatSendCounter < numberOfTimesToSend))
   //send a predefined message to the Android device after 'chatInterval' seconds and do this 'numberOfTimesToSend' times.
    {
      lastChatSendTime = millis(); 
      chatSendCounter++; //increment chat counter
      nss.print(chatMessage); //print out the message on the NewSoftSerial serial port which then travels via Bluetooth to the Android device  
    }

}

3.      Android Code

a.      Download the source code from the link below.

https://developer.android.com/samples/BluetoothChat/index.html

b.      Locate “BluetoothChatService.java” and find the below lines of code.

private static final UUID MY_UUID_SECURE = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");

c.       Replace the above lines with the following lines.

private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

d.      Save the file and run the modified BluetoothChat App on a real Android phone (the App won’t work on emulator).

4.      The Result


Note,
-          Arduino version: 1.6.1
-          Android Studio version: 1.2 Beta


2014/11/08

Beginning’s Introduction to Developing with Google Maps V2 for Android

This is a summary of my experience with getting Google Maps V2 API to work on my Samsung Galaxy S3 phone.


Development Environment.


Android ADT Version: 23.0.2.






















JDK version: 1.7.0_71












Eclipse Version: 4.2.1



-----------------------------------------------------------------------------------------------------------------


Building the project


  1. Create new project. For our example, the project will be namedcom.example.maptest01”


Note, this name must be the same as the one you use for applying your Google MAPs V2 API for Android.


  1. Include “google-play-services_lib”


Right click on project (com.example.maptest01) -> select Properties




Select “Android” -> “Add”























  1. Adding support library.


Right click on project (com.example.maptest01) -> select Android Tools -> select Add Support Library.



Note, this is for supporting API 11 or earlier system.


  1. Checking support libraries.























  1. Writing the codes


-----------------------------------------------------------------------------------------------------------------
MainActivity.java
-----------------------------------------------------------------------------------------------------------------


package com.example.maptest01;


import android.support.v4.app.FragmentActivity;
import android.os.Bundle;


public class MainActivity extends FragmentActivity {


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


-----------------------------------------------------------------------------------------------------------------
activity_main.xml
-----------------------------------------------------------------------------------------------------------------


<fragment xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/map"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   class="com.google.android.gms.maps.MapFragment" />


-----------------------------------------------------------------------------------------------------------------
AndroidManifest.xml
-----------------------------------------------------------------------------------------------------------------


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.maptest01"
   android:versionCode="1"
   android:versionName="1.0" >


   <uses-sdk
       android:minSdkVersion="8"
       android:targetSdkVersion="16" />
   
   <uses-feature
       android:glEsVersion="0x00020000"
       android:required="true" />
   
   <permission
       android:name="com.example.maptest01.permission.MAPS_RECEIVE"
       android:protectionLevel="signature" />
   <uses-permission
     android:name="com.example.maptest01.permission.MAPS_RECEIVE" />
   <uses-permission android:name="android.permission.INTERNET" />
   
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
   
   <uses-permission
       android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission
       android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
   <uses-permission
       android:name="android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission
       android:name="android.permission.ACCESS_FINE_LOCATION" />
   
   <application
       android:allowBackup="true"
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       <activity
           android:name=".MainActivity"
           android:label="@string/app_name" >
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   
    <meta-data
           android:name="com.google.android.maps.v2.API_KEY"
           android:value="Your Google Maps API V2 Key" />
   
    <meta-data
       android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
   
   </application>


</manifest>


-----------------------------------------------------------------------------------------------------------------


  1. Upload to actual device (for this example: Samsung Galaxy S3)


Right click on project (com.example.maptest01) -> select Run As -> select Android Application.


Note, Currently, Google Maps V2 API for Android doesn’t run on Emulator. There are ways to make it runs on Emulator, please check the reference links at the end of this post for details. I haven’t made it work successfully yet.


Select the device in AVD and click OK.



The map will show up within seconds.




































References:


The info. in the following links are very helpful and contains more info. on how to apply for Google Maps V2 API Key, further development of Apps. using the API, and more.


Getting the API Key
Note, It’s very important that the path to keystore (in this example: debug.keystore) doesn’t contain any blank space. Otherwise, keytool will not function properly. If  blank space exists in the path, copy the keystore to a different directory without blank space in its path.