You are on page 1of 19

Capter 13.

Thread Demo 1 Progress Bar


List program

ThreadDemo1ProgressBarActivity.java

package app.seamolec; import java.util.Random; import import import import import import import public android.app.Activity; android.os.Bundle; android.os.Handler; android.os.Message; android.view.View; android.widget.ProgressBar; android.widget.TextView; class ThreadDemo1ProgressBarActivity extends Activity { ProgressBar bar1; ProgressBar bar2; TextView msgWorking; TextView msgReturned; boolean isRunning= false; final int MAX_SEC= 60; // (seconds) lifetime for background thread String strTest= "global value seen by all threads "; int intTest= 0; Handler handler= new Handler() { public void handleMessage(Message msg) {

String returnedValue= (String)msg.obj; //do something with the value sent by the background thread here ... msgReturned.setText("returned by background thread: \n\n" + returnedValue); bar1.incrementProgressBy(2); //testing threads termination if(bar1.getProgress() == MAX_SEC){ msgReturned.setText("Done \n back thread has been stopped"); isRunning= false; } if(bar1.getProgress() == bar1.getMax()){ msgWorking.setText("Done"); bar1.setVisibility(View.INVISIBLE); bar2.setVisibility(View.INVISIBLE); } else{ msgWorking.setText("Working..."+ bar1.getProgress() ); } } }; //handler @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); bar1= (ProgressBar) findViewById(R.id.progress); bar2= (ProgressBar) findViewById(R.id.progress2); bar1.setMax(MAX_SEC); bar1.setProgress(0); msgWorking= (TextView)findViewById(R.id.TextView01); msgReturned= (TextView)findViewById(R.id.TextView02); strTest+= "-01"; // slightly change the global string intTest= 1; }//onCreate public void onStop() { super.onStop(); isRunning= false; } public void onStart() { super.onStart(); // bar1.setProgress(0); Thread background = new Thread(new Runnable() { public void run() { try{ for(int i = 0; i < MAX_SEC && isRunning; i++) { //try a Toast method here (will not work!) //fake busy busywork here Thread.sleep(1000); //one second at a time Random rnd= new Random(); // this is a locally generated value String data = "Thread Value: "+ (int) rnd.nextInt(101); //we can see and change (global) class variables data += "\n"+ strTest+ " "+ intTest; intTest++;

//request a message token and put some data in it Message msg= handler.obtainMessage(1, (String)data); // if thread is still alive send the message if(isRunning) { handler.sendMessage(msg); } } } catch(Throwable t) { // just end the background thread } }//run });//background isRunning= true; background.start(); }//onStart } //class

Main.xlm
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff009999" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Working ...." android:textSize="18sp" android:textStyle="bold" /> <ProgressBar android:id="@+id/progress" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" /> <ProgressBar android:id="@+id/progress2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/TextView02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="returned from thread..." android:textSize="14sp" android:background="#ff0000ff" android:textStyle="bold" android:layout_margin="7px"/>

</LinearLayout>

CAPTER 13. Threads Posting

ThreadsPostingActivity.java package app.seamolec; import import import import import import import import import import import android.app.Activity; android.os.Bundle; android.os.Handler; android.text.Editable; android.text.style.BackgroundColorSpan; android.view.View; android.widget.Button; android.widget.EditText; android.widget.ProgressBar; android.widget.TextView; android.widget.Toast;

public class ThreadsPostingActivity extends Activity { private static final Runnable BackgroundTask = null; ProgressBar myBar; TextView lblTopCaption; EditText txtBox1; Button btnDoSomething; int accum=0; long startingMills = System.currentTimeMillis(); String PATIENCE= "Some important data is been collected now. "+

"\nPleasebe patient. "; Handler myHandler= new Handler(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lblTopCaption = (TextView)findViewById(R.id.lblTopCaption); myBar = (ProgressBar) findViewById(R.id.txtBox1); txtBox1.setMaxEms(100); txtBox1= (EditText) findViewById(R.id.txtBox1); txtBox1.setHint("Foreground distraction. Enter some data here"); btnDoSomething= (Button)findViewById(R.id.btnDoSomething); btnDoSomething.setOnClickListener(new OnClickListener() { public void onClick(View v) { Editable txt = txtBox1.getText(); Toast.makeText(getBaseContext(), "You said >> "+ txt, 1).show(); }//onClick });//setOnClickListener }//onCreate protected void onStart() { super.onStart(); // create background thread were the busy work will be done Thread myThread1 = new Thread(BackgroundTask, "backAlias1"); myThread1.start(); myBar.incrementProgressBy(0); } // this is the foreground "Runnable" object responsible for GUI updates private Runnable foregroundTask= new Runnable() { public void run() { try{ int progressStep= 5; lblTopCaption.setText(PATIENCE+ "\nTotalsec. so far: "+ (System.currentTimeMillis() -startingMills) / 1000 ); myBar.incrementProgressBy(progressStep); accum+= progressStep; if(accum>= myBar.getMax()){ lblTopCaption.setText("Background work is OVER!"); myBar.setVisibility(View.INVISIBLE); } } catch(Exception e) { e.printStackTrace(); } }//run

}; //this is the "Runnable" object that executes the background thread private Runnable backgroundTask= new Runnable() { public void run() {

//busy work goes here... try{ for(int n=0; n<20; n++) { //this simulates 1 sec. of busy activity Thread.sleep(1000); //now talk to the main thread myHandler.post(foregroundTask); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }//run

};//backgroundTask }//ThreadsPosting

main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff009999" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/lblTopCaption" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="2px" android:text="Some important data is been collected now. Patience please..." android:textSize="16sp" android:textStyle="bold" /> <ProgressBar android:id="@+id/myBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/txtBox1" android:layout_width="fill_parent" android:layout_height="78px" android:layout_marginLeft="20px" android:layout_marginRight="20px" android:textSize="18sp" android:layout_marginTop="10px" /> <Button android:id="@+id/btnDoSomething" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:padding="4px" android:layout_marginLeft="20px" android:text="Do Something" /> </LinearLayout>

CAPTER 14. Preference1Activity

Preference1Activity.java package app.seamolec; import java.util.Date; import import import import import import android.app.Activity; android.content.SharedPreferences; android.content.SharedPreferences.Editor; android.os.Bundle; android.widget.EditText; android.widget.TextView;

public class Preference1Activity extends Activity { public static final String MYPREFS = "MySharedPreferences001"; //this data values describe a typical customer record String custName = "n.a."; int custAge = 0;

float custCredit = 0; long custNumber = 0; String custDateLastCall; TextView captionBox; EditText txtPref; final int mode = Activity.MODE_PRIVATE; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtPref = (EditText)findViewById(R.id.txtPref); captionBox = (TextView) findViewById(R.id.captionBox); captionBox.setText("SharedPreference Container: \n\n"+ "we are working on customer Macarena \n" + "fake an interruption, press 'Back Button' \n" + "re-execute the application."); //create a reference to the shared preferences object int mode = Activity.MODE_PRIVATE; SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS, mode); // is there an existing Preferences from previous executions of this app? if (mySharedPreferences != null && mySharedPreferences.contains("custName")) { //object and key found, show all saved values showSavedPreferences(); } else { txtPref.setText("nada"); } }//onCreate protected void onPause() { //warning: activity is on last state of visibility! We are on the //edge of been killed! Better save current state in Preference object savePreferences(); super.onPause(); } protected void savePreferences(){ //create the shared preferences object SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS, mode); //obtain an editor to add data to (my)SharedPreferences object SharedPreferences.Editor myEditor = mySharedPreferences.edit(); //put some <key/value> data in the preferences object myEditor.putString("custName", "Maria Macarena"); myEditor.putInt("custAge", 21); myEditor.putFloat("custCredit", 1500000.00F); myEditor.putLong("custNumber", 9876543210L); myEditor.putString("custDateLastCall", new Date().toLocaleString()); myEditor.commit(); }

public void showSavedPreferences() { //retrieve the SharedPreferences object SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS, mode); //extract the <key/value> pairs, use default param for missing data custName = mySharedPreferences.getString("custName", "defNameValue"); custAge = mySharedPreferences.getInt("custAge", 18); custCredit = mySharedPreferences.getFloat("custCredit", 1000.00F); custNumber = mySharedPreferences.getLong("custNumber", 1L); custDateLastCall = mySharedPreferences.getString("custDateLastCall", new Date().toLocaleString()); //show saved data on screen String msg = "name: " + custName + "\nAge: " + custAge + "\nCredit: " + custCredit + "\nLastCall: " + custDateLastCall; txtPref.setText(msg); }//loadPreferences }//Preferences1

main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/linLayou1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff0000ff" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/captionBox" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="SharedPreferences Container: Customer Data" android:layout_margin="5px" android:textStyle="bold"> </TextView> <EditText android:id="@+id/txtPref" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10px"> </EditText> </LinearLayout>

CAPTER 14. Preference Demo

PreverenceDemoOActivity.java package app.seamolec; import java.sql.Date; import import import import import import import import import import import android.app.Activity; android.content.SharedPreferences; android.graphics.Color; android.graphics.Typeface; android.os.Bundle; android.view.View; android.view.View.OnClickListener; android.widget.Button; android.widget.TextView; android.widget.Toast; app.seamolec.nila.R;

public class PreferenceDemo0Activity extends Activity implements OnClickListener { /** Called when the activity is first created. */ Button btnSimplePref; Button btnFancyPref; TextView txtCaption1; Boolean fancyPrefChosen = false; View myLayout1Vertical; final int mode = Activity.MODE_PRIVATE; final String MYPREFS = "MyPreferences_001"; // create a reference to the shared preferences object SharedPreferences mySharedPreferences; // obtain an editor to add data to my SharedPreferences object SharedPreferences.Editor myEditor;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myLayout1Vertical = (View)findViewById(R.id.linLayout1Vertical); txtCaption1 = (TextView) findViewById(R.id.txtCaption1); txtCaption1.setText("This is a sample line \n" + "suggesting the way the UI looks \n" + "after you choose your preference"); // create a reference & editor for the shared preferences object mySharedPreferences = getSharedPreferences(MYPREFS, 0); myEditor = mySharedPreferences.edit(); // has a Preferences file been already created? if (mySharedPreferences != null && mySharedPreferences.contains("backColor")) { // object and key found show all saved values applySavedPreferences(); } else { Toast.makeText(getApplicationContext(), "No Preferences found", 1).show(); } btnSimplePref = (Button) findViewById(R.id.btnPrefSimple); btnSimplePref.setOnClickListener(this); btnFancyPref = (Button) findViewById(R.id.btnPrefFancy); btnFancyPref.setOnClickListener(this); }

@Override public void onClick(View v) { // clear all previous selections myEditor.clear(); // what button has been clicked? if (v.getId() == btnSimplePref.getId()) { myEditor.putInt("backColor", Color.BLACK);// black background myEditor.putInt("textSize", 12); // humble small font } else { // case btnFancyPref myEditor.putInt("backColor", Color.BLUE); // fancy blue myEditor.putInt("textSize", 20); // fancy big myEditor.putString("textStyle", "bold"); // fancy bold myEditor.putInt("layoutColor", Color.GREEN);//fancy green } myEditor.commit(); applySavedPreferences(); } protected void onPause() { // warning: activity is on its last state of visibility!. // It's on the edge of been killed! Better save all current // state data into Preference object (be quick!) myEditor.putString("DateLastExecution", new Date(0).toLocaleString()); myEditor.commit(); super.onPause();

} public void applySavedPreferences() { // extract the <key/value> pairs, use default param for missing data int backColor = mySharedPreferences.getInt("backColor",Color.BLACK); int textSize = mySharedPreferences.getInt("textSize", 12); String textStyle = mySharedPreferences.getString("textStyle", "normal"); int layoutColor = mySharedPreferences.getInt("layoutColor", Color.DKGRAY); String msg = "color " + backColor + "\n" + "size " + textSize + "\n" + "style " + textStyle; Toast.makeText(getApplicationContext(), msg, 1).show(); txtCaption1.setBackgroundColor(backColor); txtCaption1.setTextSize(textSize); if (textStyle.compareTo("normal")==0){ txtCaption1.setTypeface(Typeface.SERIF,Typeface.NORMAL); } else { txtCaption1.setTypeface(Typeface.SERIF,Typeface.BOLD); } myLayout1Vertical.setBackgroundColor(layoutColor); }// applySavedPreferences } // TODO Auto-generated method stub

main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/linLayout1Vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <LinearLayout android:id="@+id/linLayout2Horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <Button android:id="@+id/btnPrefSimple" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pref Simple UI" /> <Button android:id="@+id/btnPrefFancy" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pref Fancy UI" /> </LinearLayout> <TextView

android:id="@+id/txtCaption1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#ff006666" android:text="This is some sample text " /> </LinearLayout>

CAPTER 15. Demo

DemoActivity extends.java package app.seamolec; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import app.seamolec.nila.R;

public class DemoActivity extends Activity { private final static String NOTES="notes.txt"; private EditText editor; public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); editor=(EditText)findViewById(R.id.editor); Button btn=(Button)findViewById(R.id.close); btn.setOnClickListener(new Button.OnClickListener() { public void onClick (View v) { finish(); }

}); }//onCreate public void onResume() { super.onResume(); try{ InputStream in=openFileInput(NOTES); if(in!=null) { InputStreamReader tmp=new InputStreamReader(in); BufferedReader reader=new BufferedReader(tmp); String str; StringBuffer buf=new StringBuffer(); while((str= reader.readLine()) != null) { buf.append(str+"\n"); } in.close(); editor.setText(buf.toString()); }//if } catch(java.io.FileNotFoundException e) { // that's OK, we probably haven't created it yet } catch(Throwable t) { Toast.makeText(this, "Exception: "+ t.toString(), 2000).show(); } } public void onPause() { super.onPause(); try{ OutputStreamWriter out= new OutputStreamWriter(openFileOutput(NOTES, 0)); out.write(editor.getText().toString()); out.close();

} catch(Throwable t) { Toast.makeText(this, "Exception: "+ t.toString(), 2000).show(); } } }//class


main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <Button android:id="@+id/close" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Close" /> <EditText android:id="@+id/editor" android:layout_width="fill_parent" android:layout_height="fill_parent" android:singleLine="false" android:gravity="top" /> </LinearLayout>

CAPTER 15. Demo

FileDemo3SDActivity.java package app.seamolec; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.sql.Date; import java.util.Scanner; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import app.seamolec.nila.R; public class FileDemo3SDActivity extends Activity { // GUI controls EditText txtData; Button btnWriteSDFile; Button btnReadSDFile; Button btnClearScreen; Button btnClose;

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // bind GUI elements with local controls txtData= (EditText) findViewById(R.id.txtData); txtData.setHint("Enter some lines of data here..."); btnWriteSDFile= (Button) findViewById(R.id.btnWriteSDFile); btnWriteSDFile.setOnClickListener(new OnClickListener() { public void onClick(View v) { try{ File myFile= new File("/sdcard/mysdfile.txt"); myFile.createNewFile(); FileOutputStream fOut= new FileOutputStream(myFile); OutputStreamWriter myOutWriter= new OutputStreamWriter(fOut); myOutWriter.append(txtData.getText()); myOutWriter.close(); fOut.close(); Toast.makeText(getBaseContext(), "Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show(); } catch(Exception e) { } Throwable e = null; Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); }// onClick }); btnClearScreen= (Button) findViewById(R.id.btnClearScreen); btnClearScreen.setOnClickListener(new OnClickListener() { public void onClick(View v) { // clear text box txtData.setText(""); } }); // btnClearScreen btnClose= (Button) findViewById(R.id.btnClose); btnClose.setOnClickListener(new OnClickListener() { public void onClick(View v) { // clear text box finish(); } }); // btnClose }// onCreate

private void testScannerFiles(){ // Add to manifest the following permission request // <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> TextView tvMessage = null; try{ String SDcardPath= Environment.getExternalStorageDirectory().getPath(); String mySDFileName= SDcardPath+ "/"+ "mysdfiletest.txt"; tvMessage.setText("Writing to: "+ mySDFileName); PrintWriter outfile= new PrintWriter( new FileWriter(mySDFileName) ); outfile.println("HolaAndroid"); outfile.println("Adios Android"); outfile.println(new Date(0).toString()); outfile.close(); // read SD-file,showrecords. Scanner infile= new Scanner(new FileReader(mySDFileName)); String inString= "\n\nReadingfrom: "+ mySDFileName+ "\n"; while(infile.hasNextLine()) { inString+= infile.nextLine() + "\n"; } tvMessage.append(inString); infile.close(); } catch(FileNotFoundException e) { tvMessage.setText( "Error: "+ e.getMessage()); } catch(IOException e) { tvMessage.setText( "Error: "+ e.getMessage()); } } }
main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff0000ff" android:orientation="vertical" > <EditText android:id="@+id/txtData" android:layout_width="fill_parent" android:layout_height="180px" android:text="Enter some data here ..." android:textSize="18sp" /> <Button android:id="@+id/btnWriteSDFile"

android:layout_width="143px" android:layout_height="44px" android:text="1. Write SD File" /> <Button android:id="@+id/btnClearScreen" android:layout_width="141px" android:layout_height="42px" android:text="2. Clear Screen" /> <Button android:id="@+id/btnReadSDFile" android:layout_width="140px" android:layout_height="42px" android:text="3. Read SD File" /> <Button android:id="@+id/btnClose" android:layout_width="141px" android:layout_height="43px" android:text="4. Close" /> </LinearLayout>

You might also like