13,14,15 appseamolec

Upload: nila-novita-sari

Post on 05-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 13,14,15 appseamolec

    1/19

    Capter 13. Thread Demo 1 Progress Bar

    List program

    ThreadDemo1ProgressBarActivity.java

    package app.seamolec;

    import java.util.Random;

    import android.app.Activity;

    import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;

    import android.widget.ProgressBar;import android.widget.TextView;public 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) {

  • 8/2/2019 13,14,15 appseamolec

    2/19

    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

    @Overridepublic 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 stringintTest= 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 hereThread.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++;

  • 8/2/2019 13,14,15 appseamolec

    3/19

    //request a message token and put some data in itMessage msg= handler.obtainMessage(1, (String)data);

    // if thread is still alive send the messageif(isRunning) {handler.sendMessage(msg);}

    }} catch(Throwable t) {// just end the background thread

    }}//run});//backgroundisRunning= true;

    background.start();

    }//onStart} //class

    Main.xlm

  • 8/2/2019 13,14,15 appseamolec

    4/19

    CAPTER 13. Threads Posting

    ThreadsPostingActivity.java

    package app.seamolec;

    import android.app.Activity;import android.os.Bundle;

    import android.os.Handler;import android.text.Editable;

    import android.text.style.BackgroundColorSpan;import android.view.View;

    import android.widget.Button;import android.widget.EditText;import android.widget.ProgressBar;

    import android.widget.TextView;import 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. "+

  • 8/2/2019 13,14,15 appseamolec

    5/19

    "\nPleasebe patient. ";Handler myHandler= new Handler();

    /** Called when the activity is first created. */@Overridepublic 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 doneThread myThread1 = new Thread(BackgroundTask, "backAlias1");

    myThread1.start();

    myBar.incrementProgressBy(0);}// this is the foreground "Runnable" object responsible for GUI updatesprivate 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 threadprivate Runnable backgroundTask= new Runnable() {

    public void run() {

  • 8/2/2019 13,14,15 appseamolec

    6/19

    //busy work goes here...try{

    for(int n=0; n

  • 8/2/2019 13,14,15 appseamolec

    7/19

    android:layout_height="wrap_content"android:padding="4px"

    android:layout_marginLeft="20px"android:text="Do Something"/>

    CAPTER 14. Preference1Activity

    Preference1Activity.java

    package app.seamolec;

    import java.util.Date;

    import android.app.Activity;

    import android.content.SharedPreferences;

    import android.content.SharedPreferences.Editor;

    import android.os.Bundle;

    import android.widget.EditText;

    import android.widget.TextView;

    publicclass Preference1Activity extends Activity {

    publicstaticfinal StringMYPREFS = "MySharedPreferences001";//this data values describe a typical customer record

    String custName = "n.a.";intcustAge = 0;

  • 8/2/2019 13,14,15 appseamolec

    8/19

    floatcustCredit = 0;

    longcustNumber = 0;

    String custDateLastCall;TextView captionBox;EditText txtPref;finalintmode = Activity.MODE_PRIVATE;

    publicvoid 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 objectint 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

    protectedvoid 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();}protectedvoid savePreferences(){

    //create the shared preferences objectSharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,

    mode);

    //obtain an editor to add data to (my)SharedPreferences objectSharedPreferences.Editor myEditor = mySharedPreferences.edit();

    //put some data in the preferences objectmyEditor.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();}

  • 8/2/2019 13,14,15 appseamolec

    9/19

    publicvoid showSavedPreferences() {//retrieve the SharedPreferences object

    SharedPreferences mySharedPreferences =getSharedPreferences(MYPREFS, mode);//extract the 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 screenString msg = "name: " + custName + "\nAge: " + custAge +

    "\nCredit: " + custCredit +

    "\nLastCall: " + custDateLastCall;txtPref.setText(msg);

    }//loadPreferences}//Preferences1

    main.xml

    CAPTER 14. Preference Demo

  • 8/2/2019 13,14,15 appseamolec

    10/19

    PreverenceDemoOActivity.java

    package app.seamolec;

    import java.sql.Date;

    import android.app.Activity;import android.content.SharedPreferences;

    import android.graphics.Color;

    import android.graphics.Typeface;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;

    import android.widget.Button;import android.widget.TextView;

    import android.widget.Toast;

    import 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 objectSharedPreferences mySharedPreferences;

    // obtain an editor to add data to my SharedPreferences objectSharedPreferences.Editor myEditor;

  • 8/2/2019 13,14,15 appseamolec

    11/19

    @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 objectmySharedPreferences = 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);

    }

    @Overridepublic void onClick(View v) {

    // clear all previous selectionsmyEditor.clear();// what button has been clicked?

    if (v.getId() == btnSimplePref.getId()) {myEditor.putInt("backColor", Color.BLACK);// black backgroundmyEditor.putInt("textSize", 12); // humble small font} else { // case btnFancyPref

    myEditor.putInt("backColor", Color.BLUE); // fancy bluemyEditor.putInt("textSize", 20); // fancy bigmyEditor.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();

  • 8/2/2019 13,14,15 appseamolec

    12/19

    }

    public void applySavedPreferences() {// extract the pairs, use default param for missing dataint 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

  • 8/2/2019 13,14,15 appseamolec

    13/19

    android:id="@+id/txtCaption1"android:layout_width="fill_parent"

    android:layout_height="wrap_content"android:background="#ff006666"android:text="This is some sample text "/>

    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;

  • 8/2/2019 13,14,15 appseamolec

    14/19

    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();

    }

    });

    }//onCreatepublic 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();

  • 8/2/2019 13,14,15 appseamolec

    15/19

    }

    catch(Throwable t) {

    Toast.makeText(this, "Exception: "+ t.toString(), 2000).show();

    }

    }

    }//class

    main.xml

    CAPTER 15. Demo

  • 8/2/2019 13,14,15 appseamolec

    16/19

    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;

  • 8/2/2019 13,14,15 appseamolec

    17/19

    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

  • 8/2/2019 13,14,15 appseamolec

    18/19

    private void testScannerFiles(){

    // Add to manifest the following permission request

    //

    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

  • 8/2/2019 13,14,15 appseamolec

    19/19

    android:layout_width="143px"android:layout_height="44px"

    android:text="1. Write SD File"/>