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.

-----fragment_main.xml-------
<ProgressBar 
        android:id="@+id/progress_bar1"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Horizontal" />

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

Advertisements

[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> {

        @Override
        protected void onPreExecute() {}

        @Override
        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
                    e.printStackTrace();
                }
            }
            return "Executed";               //The String is returned to onPostExecute
        }

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

        @Override
        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() {

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

t.start();

[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

=======fragment_main.xml=========
<Button
....
    android:onClick="sendMessage"
/>

//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);
startActivity(intent);

Open a NewActivity using  New -> Android Activity

with the option parent_class is the MainActivity.

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

switch (item.getItemId()) {

case android.R.id.home:
 NavUtils.navigateUpFromSameTask(this);
 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);
textView.setTextSize(40);
textView.setText(message);

setContentView(textView);

[Android] Create Alert Dialog

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

import android.app.AlertDialog;

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

abox.setMessage("Hello World");
abox.show();

//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(R.id.editText1);
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>