Programmer's Blog

Programmer's reference

Category Archives: Android

[Android] Horizontal Progress Bar

The following code is to create a Horizontal progress bar in the Activity. By default, the loading bar is a circle, but through some modification it can be changed to horizontal.

        style="@android:style/Widget.ProgressBar.Horizontal" />

ProgressBar mProgress = (ProgressBar) findViewById(;
mProgress.setMax(100);      //set the maximum value of the bar
mProgress.setProgress(50);  //50% this statement can be replaced
                            //with loop or comparisons


[Android] Run program on touch event

//Inside onCreate();

public boolean onTouchEvent(MotionEvent event) {   if (event.getAction() == MotionEvent.ACTION_DOWN) {     //function here     return true;   }   return super.onTouchEvent(event); }

[Android] AsyncTask as Background Thread to update UI

The AsyncTask is a method of threading in Android. Here is a demonstration

on updating the number to the textView in looping.

The AsyncTask is Inhereted from the class

AsyncTask< 1, 2 , 3>

1. doInBackgroundParam

2. onProgressUpdateParam

3. onPostExecutiveParam

//Execute the thread using

new Counting().execute(Param1, Param2);  

//each param will inputted as params[1], params[2] in doInBackground()

//the three variable types are the Parameter type of the 3 Param mentioned above
//e.g. doInBackground inputs a String type parameter

private class Counting extends AsyncTask<String, Integer, String> {

        protected void onPreExecute() {}

        protected String doInBackground(String... params) {   //The param is the input from execute();
            for ( int i = 0; i < 100; i++) {                  //it is an array
                try {
                    publishProgress(i);          //throw the value i to onProgressUpdate()
                    Thread.sleep(500);          //Where i is int, thus 
                } catch (InterruptedException e) {   //Param onProgressUpdate() is int
            return "Executed";               //The String is returned to onPostExecute

        protected void onProgressUpdate(Integer... values) {
            message = Integer.toString(values[0]);     //values[0] from publishProgress function

        protected void onPostExecute(String result) { }
        //You can select to post the result here


[Android] Threading to replace for loop on dynamical textView

The Activity in the Android is cannot be updated automatically on a textView.

e.g. counting from 1 to 100. If using for-loop, the result will be straight away to 99 since there is no interruption in execution of the for-loop to update the Activity even using setText(message).

The method to solve this is using Threading to put the content in the loop into the thread, once one iteration t is completed there is an “interruption” and the activity can be updated.

======in onCreate Function or onClick=========

Thread t = new Thread() {

public void run() {
      try {
      while (!isInterrupted()) {
            Thread.sleep(100);   //The update delay in mil_sec
            runOnUiThread(new Runnable() {
                   public void run() {
                          //content inside the for-loop


[Android] Add event Listener to Button

The following is a very simple example to demonstrate how to include the Click action listener for a button


//The sendMessage is the function we defined in the MainActivity when the button is clicked

======Main Activity========
public void sendMessage(View view) {
  //Actions Here

[Android] Initiate new Activity through Intent

An activity is initiated by intent, and some values from one activity may stored in the object Intent to be passed to the new Activity.

In the MainActivity

import android.content.Intent;

-----In the class of MainActivity-------
static final static String EXTRA_MESSAGE = "com.myapp.MESSAGE"
//EXTRA_MESSAGE is the String name , it is represented in form of class object

 -----In the button function------ 
Intent intent = new Intent(this, NewActivity.class); 

String message = ("Hello World");
intent.putExtra(EXTRA_MESSAGE, message);

Open a NewActivity using  New -> Android Activity

with the option parent_class is the MainActivity.

——-In the NewActivity, OnOptionsItemSeleted()———-

switch (item.getItemId()) {

 return true;


In the NewActivity, display the message on screen using textview

import android.content.Intent;
import android.widget.TextView;

Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

TextView textView = new TextView(this);


[Android] Create Alert Dialog

The alert dialog is a white message box appear at the center of the screen displaying alert message


------inside function of Listener----
//create AlertDialog object
AlertDialog abox = new AlertDialog.Builder(this).create();

abox.setMessage("Hello World");;

//There are also other settings available:
abox.setCancelable(False)  //user cannot quit the dialog by return

[Android] To extract text from a EditText

The following script is to extract the text in the Edittext (textbox in android) and save in the message variable.

The method is to find the id of the view, and the id of all the views are stored in the R.xml, therefore using findViewById we can retrieve the view object.

import android.widget.EditText;

EditText mytext = (EditText) findViewById(;
String message = mytext.getText().toString();

[Android] Ignore Missing Translation error

The following script is the extract of the res/values/string.xml

To prevent the missing translation error when the project is created

<string name="text" tools:ignore="MissingTranslation">Push</string>