WELCOME Abdennour : Software engineer

Apr 7, 2012

Summary Of Matos's Android Tutos(Part2)


( Following of Intents Summary)
Intent+Result Back Code Source Example :

A)Layout XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/label1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000cc"
        android:text="This is Activity1"
        android:textSize="20sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="54px"
        android:text="content://contacts/people/"
        android:textSize="18sp"
        width="fill parent" />

    <Button
        android:id="@+id/btnPickContact"
        android:layout_width="149px"
        android:layout_height="wrap_content"
        android:text="Make Phone Call"
        android:textStyle="bold" />

</LinearLayout>  
B)Activity Java Code:





















package slm.Abdennour.android.intentwithresultback;



import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;



public class IntentWithResultManager extends Activity {

  TextView label1;

  EditText text1;

  Button btnCallActivity2;



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    try {

      setContentView(R.layout.main);

      label1 = (TextViewfindViewById(R.id.label1);

      text1 = (EditTextfindViewById(R.id.text1);

      btnCallActivity2 = (ButtonfindViewById(R.id.btnPickContact);

      btnCallActivity2.setOnClickListener(new ClickHandler());

    catch (Exception e) {

      Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG)

          .show();

    }



  }



  private class ClickHandler implements OnClickListener {

    @Override

    public void onClick(View v) {

      try {

        // myData refer to: content://contacts/people/

        String myData = text1.getText().toString();

        // you may also try ACTION_VIEW instead

        Intent myActivity2 = new Intent(Intent.ACTION_PICK,

            Uri.parse(myData));

        // start myActivity2.

        // Tell it that our requestCodeID (or nickname) is 222

        startActivityForResult(myActivity2, 222);

      catch (Exception e) {

        label1.setText(e.getMessage());

      }

    }// onClick

  }//



  @Override

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // TODO Auto-generated method stub

    super.onActivityResult(requestCode, resultCode, data);

    try {

      // use requestCode to find out who is talking back to us

      switch (requestCode) {

      case (222){

        // 222 is our friendly contact-picker activity

        if (resultCode == Activity.RESULT_OK) {

          String selectedContact = data.getDataString();

          // it will return an URI that looks like:

          // content://contacts/people/n

          // where n is the selected contacts' ID

          label1.setText(selectedContact.toString());

          // show a 'nice' screen with the selected contact

          Intent myAct3 = new Intent(Intent.ACTION_VIEW,

              Uri.parse(selectedContact));

          startActivity(myAct3);

        else {

          // user pressed the BACK button // p

          label1.setText("Selection CANCELLED " + requestCode + " "

              + resultCode);

        }

        break;

      }

      }// switch

    catch (Exception e) {

      Toast.makeText(getBaseContext(), e.getMessage()

          Toast.LENGTH_LONG).show();

    }

  }

}


C)Result:


Activity Exchange With Bundle Code Source Example :(intents)


A)Activities:
A.1.Activity1:


public class Activity1 extends Activity {

  EditText txtVal1;

  EditText txtVal2;

  TextView lblResult;

  Button btnAdd;



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    txtVal1 = (EditTextfindViewById(R.id.EditText01);

    txtVal2 = (EditTextfindViewById(R.id.EditText02);

    lblResult = (TextViewfindViewById(R.id.TextView01);

    btnAdd = (ButtonfindViewById(R.id.btnAdd);

    btnAdd.setOnClickListener(new OnClickListener() {

      @Override

      public void onClick(View v) {

        // Â get values from the UI

        Double v1 = Double.parseDouble(txtVal1.getText().toString());

        Double v2 = Double.parseDouble(txtVal2.getText().toString());

        // Â create intent to call Activity2

        Intent myIntentA1A2 = new Intent(Activity1.this,

            Activity2.class);

        // Â create a container to ship data

        Bundle myData = new Bundle();

        // Â add <key,value> data items to the container

        myData.putDouble("val1", v1);

        myData.putDouble("val2", v2);

        // Â attach the container to the intent

        myIntentA1A2.putExtras(myData);

        // Â call Activity2, tell your local listener to wait for response

        startActivityForResult(myIntentA1A2, 101);

      }

    });

  }

  @Override

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // TODO Auto-generated method stub

    super.onActivityResult(requestCode, resultCode, data);

    try {

      if  ((requestCode==101)&&(resultCode==Activity.RESULT_OK)){

        Bundle myResults  =data.getExtras();

        Double vresult  =myResults.getDouble("vresult");

        lblResult.setText("Sum is "+ vresult);

        }  

    catch (Exception e) {

      lblResult.setText("pb: "+requestCode+" "+resultCode);

    }

    

  }

}


A.2.Activity2:


public class Activity2 extends Activity implements OnClickListener {

  EditText dataReceived;

  Button btnDone;



  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main2);

    dataReceived = (EditTextfindViewById(R.id.etDataReceived);

    btnDone = (ButtonfindViewById(R.id.btnDone);

    btnDone.setOnClickListener(this);

    // Â pick call made to Activity2 via Intent

    Intent myLocalIntent = getIntent();

    // Â look into the bundle sent to Activity2 for data items

    Bundle myBundle = myLocalIntent.getExtras();

    Double v1 = myBundle.getDouble("val1");

    Double v2 = myBundle.getDouble("val2");

    // Â operate on the input data

    Double vResult = v1 + v2;

    // Â for illustration purposes. show data received & result

    dataReceived.setText("Data received is \n" "val1= " + v1 + "\nval2= "

        + v2 + "\n\nresult= " + vResult);

    // Â add to the bundle the computed result  

    myBundle.putDouble("vresult", vResult);

    // Â attach updated bumble to invoking intent

    myLocalIntent.putExtras(myBundle);

    // Â return sending an OK signal to calling activity

    setResult(Activity.RESULT_OK, myLocalIntent);

  }



  @Override

  public void onClick(View v) {

    // Â close current screen ‐ terminate Activity2

    finish();

  }// onClick

}



B)Layout XML File:

Main.xml
Main2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000ff"
        android:text="Activity1"
        android:textSize="22sp" />

    <EditText
        android:id="@+id/EditText01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter first value (a signed double)"
        android:inputType="numberDecimal|numberSigned|number" />

    <EditText
        android:id="@+id/EditText02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Second value (a positive integer)"
        android:inputType="number" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Values" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000ff"
        android:text="Sum is..."
        android:textSize="28sp" />

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000ff"
        android:text="Activity2"
        android:textSize="22sp" />

    <EditText
        android:id="@+id/etDataReceived"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Data reveived..." />

    <Button
        android:id="@+id/btnDone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Done  Callback" />

</LinearLayout>
C)Manifest XMl:
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:label="@string/app_name" android:name="Activity1">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".Activity2"/>
    </application>

3.going back and forth(Vas et vient) between Avtivities Code Source Example :



A)Layout XML File:
Layout/main.xml
Layout/main2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ff555555"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/caption1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffff3300"
        android:padding="4sp"
        android:text=" Activity1 "
        android:textColor="#ff000000"
        android:textSize="20px"
        android:textStyle="bold" >
    </TextView>

    <TextView
        android:id="@+id/widget107"
        android:layout_width="fill_parent"
        android:layout_height="2sp" >
    </TextView>

    <TextView
        android:id="@+id/label1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dip"
        android:background="#ff0033cc"
        android:text="Data to be sent to SubActivity:"
        android:textStyle="bold|normal" >
    </TextView>

    <Button
        android:id="@+id/btnCallActivity2"
        android:layout_width="149px"
        android:layout_height="wrap_content"
        android:padding="6sp"
        android:text="Call  Activity2"
        android:textStyle="bold" >
    </Button>

    <TextView
        android:id="@+id/label1Returned"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dip"
        android:background="#ff0033cc"
        android:text=" Data returned by Activity2"
        android:textStyle="bold|normal" >
    </TextView>

</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff77"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffff9900"
        android:padding="4sp"
        android:text=" Activity2"
        android:textSize="20px"
        android:textStyle="bold" >
    </TextView>

    <TextView
        android:id="@+id/widget107"
        android:layout_width="fill_parent"
        android:layout_height="2sp" >
    </TextView>

    <TextView
        android:id="@+id/label2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_margin="7dip"
        android:background="#ff0033cc"
        android:text="Data Received from Activity1 ..."
        android:textStyle="normal" >
    </TextView>

    <Button
        android:id="@+id/btnCallActivity1"
        android:layout_width="149px"
        android:layout_height="wrap_content"
        android:padding="6sp"
        android:text="CallBack   Activity1"
        android:textStyle="bold" >
    </Button>

    <TextView
        android:id="@+id/spyBox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="7dip"
        android:background="#ff0033cc"
        android:text="(SPY) Data Received from Activity1 ..."
        android:textStyle="normal" >
    </TextView>

</LinearLayout>

B)Activity Code :





B.1.Activity1(MainAcrivity.java) Code :


package com.__b_vatetvienentreactivities;



import android.app.Activity;

import android.content.Intent;

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;



public class MainActivity extends Activity {

  TextView label1;

  TextView label1Returned;

  Button btnCallActivity2;

  // Â arbitrary interprocess communication ID (just a nickname!)

  private final int IPC_ID = (int) (10001 * Math.random());



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);



    try {

      setContentView(R.layout.main);

      label1Returned = (TextViewfindViewById(R.id.label1Returned);

      btnCallActivity2 = (ButtonfindViewById(R.id.btnCallActivity2);

      btnCallActivity2.setOnClickListener(new Clicker1());

      // Â for demonstration purposes‐ show in top label

      label1.setText("Activity1   (sending...) \n\n"

          "RequestCode  ID: " + IPC_ID + "\n"

          "myString1:    Hello Android" "\n"

          "myDouble1:    3.141592     " "\n"

          "myIntArray:   {1 2 3} ");

    catch (Exception e) {

      Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG)

          .show();

    }

  }



  private class Clicker1 implements OnClickListener {

    public void onClick(View v) {

      try {

        // Â create an Intent to talk to Activity2

        Intent myIntentA1A2 = new Intent(MainActivity.this,

            Activity2.class);

        // Â prepare a Bundle and add the data pieces to be sent

        Bundle myData = new Bundle();

        myData.putInt("myRequestCode", IPC_ID);

        myData.putString("myString1""Hello Android");

        myData.putDouble("myDouble1"3.141592);

        int[] myLittleArray = 12};

        myData.putIntArray("myIntArray1", myLittleArray);

        // Â bind the Bundle and the Intent that talks to Activity2

        myIntentA1A2.putExtras(myData);

        // Â call Activity2 and wait for results

        startActivityForResult(myIntentA1A2, IPC_ID);

      catch (Exception e) {

        Toast.makeText(getBaseContext(), e.getMessage(),

            Toast.LENGTH_LONG).show();

      }

    }// Â onClick

  }

}


B.2.Activity2(MainAcrivity.java) Code :
public class Activity2 extends Activity {

  TextView label2;

  TextView spyBox;

  Button btnCallActivity1;



  /**

   @see android.app.Activity#onCreate(Bundle)

   */

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main2);

    // bind UI variables to Java code

    label2 = (TextViewfindViewById(R.id.label2);

    spyBox = (TextViewfindViewById(R.id.spyBox);

    btnCallActivity1 = (ButtonfindViewById(R.id.btnCallActivity1);

    btnCallActivity1.setOnClickListener(new Clicker1());

    // Â create a local Intent handler – we have been called!

    Intent myLocalIntent = getIntent();

    // grab the data package with all the pieces sent to us

    Bundle myBundle = myLocalIntent.getExtras();

    // extract the individual data parts of the bundle 

    int int1 = myBundle.getInt("myRequestCode");

    String str1 = myBundle.getString("myString1");

    double dob1 = myBundle.getDouble("myDouble1");

    int[] arr1 = myBundle.getIntArray("myIntArray1");

    // Â use bundle methods to extract its data

    String spy = "\nSPY>>\n";

    Set<String> myKeyNames = myBundle.keySet();

    for (String keyName : myKeyNames) {

      Serializable keyValue = myBundle.getSerializable(keyName);

      String keyType = keyValue.getClass().toString();

      if (keyType.equals("class java.lang.Integer")) {

        keyValue = Integer.parseInt(keyValue.toString());

      else if (keyType.equals("class java.lang.Double")) {

        keyValue = Double.parseDouble(keyValue.toString());

      }



      else if (keyType.equals("class java.lang.Float")) {

        keyValue = Float.parseFloat(keyValue.toString());

      else if (keyType.equals("class [I")) {

        int[] arrint = myBundle.getIntArray(keyName);

        int n = arrint.length;

        keyValue = arrint[n - 1];// show only the last! 

      else {

        keyValue = (StringkeyValue.toString();

      }

      spy += keyName + ": " + keyValue + " " + keyType + "\n";

    }

    spyBox.append(spy);

    // Â +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++               

    // do something with the data here (for example...)

    String strArr = "{ ";

    int sumIntValues = 0;

    for (int i = 0; i < arr1.length; i++) {

      sumIntValues += arr1[i];

      strArr += Integer.toString(arr1[i]) " ";

    }

    strArr += " } their sum is= " + sumIntValues;

    // show arriving data in GUI label2

    label2.append("\n\nActivity2   (receiving...) \n\n"

        "Caller's requestCode  ID: " + int1 + "\n" "myString1:"

        + str1 + "\n" "myDouble1:" + Double.toString(dob1"\n"

        "myIntArray1: " + strArr);

    // now go back to myActivity1 with some new data made here    

    double someNumber = sumIntValues + dob1;

    myBundle.putString("myReturnedString1""Adios Android");

    myBundle.putDouble("myReturnedDouble1", someNumber);

    myBundle.putString("myCurrentTime"new Date().toLocaleString());

    myLocalIntent.putExtras(myBundle);

    // Â all done! 

    setResult(Activity.RESULT_OK, myLocalIntent);

  }



  private class Clicker1 implements OnClickListener {

    public void onClick(View v) {

      // clear Activity2 screen so Activity1 could be seen

      finish();

    }// onClick

  }// Clicker1

}
C)Manifest XML:

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:label="@string/app_name" android:name="MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".Activity2"/>
    </application>

4.ActivitiesExchange Wih Bundles+Complex Obbect (Person) Code Source Example :

A)Layout XML File:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>

B)Activities Code File:
B.1.Activity 1 :


public class Activity1 extends Activity {

    /** Called when the activity is first created. */

  final int IPC_ID=343;

    @Override

    public void onCreate(Bundle savedInstanceState) {

      

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Bundle myData = new  Bundle();

        // creating an object and passing it into the bundle

        Person p1=new Person("Abdennour","Macarena");

        myData.putSerializable("person",p1);

        // bind the Bundle and the Intent that talks to Activity2

     //  myIntentA1A2.putExtras(myData);

        // call Activity2 and wait for results

       // startActivityForResult(myIntentA1A2, IPC_ID);

    }

}


B.2.Activity 2 :


public class Activity2 extends Activity {

  /**

   @see android.app.Activity#onCreate(Bundle)

   */

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // TODO Put your code here

    Intent myLocalIntent  = getIntent();

    //grab the data package with all the pieces sent to us

    Bundle myBundle  =myLocalIntent.getExtras();

    //extract the individual data parts of the bundle 

    Person p=(Person)myBundle.getSerializable("person");

    String pval=p.getFullName();

  }

}


C)Complex Object:


public class Person implements Serializable {



  /**

   

   */

  private static final long serialVersionUID = 1L;

  private String firstName;

  private String lastName;

  

  

  public String getFirstName() {

    return firstName;

  }

  public void setFirstName(String firstName) {

    this.firstName = firstName;

  }

  public String getLastName() {

    return lastName;

  }

  public void setLastName(String lastName) {

    this.lastName = lastName;

  }

  public Person(String firstName, String lastName) {

    super();

    this.firstName = firstName;

    this.lastName = lastName;

  }

  

  public String getFullName(){

    return firstName+" "+lastName;

  }



}





Summary Of MultiThreading :(13)



-Threads in the same VM interact and synchronize by the use of shared objects and monitors associated with these objects. 
-To have Thread execute App Code :
1)Class extends Thread ==> override Run() method.
ou
2)new Thread(<Runnable_object>)
==>start() =to execute the new thread.

Advantages of Multi-Threading

-Independence execution between the Threads.


-a multithreaded program operates faster on computer
systems that have multiple CPUs.
INVCONV :
1)Code tends to be cmplex.
2)it must detect ,avoid & resolve les deadlocks.


An application may involve a time-consuming operation, however we want the
UI to be responsive to the user. Android offers two ways for dealing with this
scenario:
1. Do expensive operations in a background service, using notifications to
  inform users about next step
2.      Do the slow work in a background thread.

Interaction between Android Threads :
1)use Handler objects ; 2) poste Runnable objects to the main view.v

Handler :
-The main thread run a message queues to manage the top level application objects(actvities,intent receivers..)
-The rôle of the Handler is to communicate to secondary threads when the application in th main thread.
==>Handle (destiné au messages queue)will deliver messages and runnables to that message queue and execute them as they come out of(are effect by) the message queue.
When use Handler :
(1)   to schedule messages and runnables to be executed as some point in thefuture; and
(2)   to enqueue an action to be performed on another thread.

RQ :
Background threads are not allowed to interact with the UI.
-only the main process can access to the view of the main activity .
-Class Statics can be seen and updated in the threads.
Message Queue of Handler :
-obtainMessage()=>invoced by secondary thread to comminucate to main thread. (by request msg token)
-sendMessage()=>used by the background Thread to :fill data into msg token &Attach msg token to message queue of the Handler .
-handleMessage() =>used by the Handler to attend continuously new messages arriving from main Thread.
-post()=>to return some data  (or request the execution of runnable objects)from message extracted from process' queue.
  
Main Thread
Backgroun Thread

...
Handler myHandler = new Handler() {

  @Override
  public void handleMessage(Message msg) {

     // do something with the message...
     // update GUI if needed!
     ...
  }//handleMessage

};//myHandler

...
...
Thread backgJob = new Thread (new Runnable (){

   @Override
   public void run() {
   //...do some busy work here ...
   //get a token to be added to 
    //the main's message queue
   Message msg = myHandler.obtainMessage();
     ...
    //deliver message to the 
    //main's message-queue
   myHandler.sendMessage(msg);          
   }//run 
         
});//Thread
       
//this call executes the parallel thread 
backgroundJob.start();
...


      
Messages :
obtainMessage()=>  used by the thread before send a message to the handler.
Example
  //  thread 1 produces some local data
  String localData = “Greeting from thread 1”;
  //  thread 1 requests a message & adds localData to it 
  Message mgs = myHandler.obtainMessage (1, localData);


sendMessage*() => Deliver the message.
SendMessage*
Role
 sendMessage()
 puts the message at the end of the queue immediately
sendMessageAtFrontOfQueue()
 puts the message at the front of the queue immediately (most priority)
sendMessageAtTime()
(puts the message on the queue at the stated
timeSystemClock.uptimeMillis()
sendMessageDelayed()
 puts the message on the queue after a delay(in milliscd)


handleMessage( . . . )   =>implemented by the Handler to process messages sent by background                                                          t                                          threads.
                                       =>called  with each message appears on the message-queue.
SO ,Handler can update the UI as needed

Using  the AsyncTask  class :

AsyncTask : allows to perform background operations and publish results on the
UI thread without having to manipulate threads and/or handlers.
-An asynchronous task = runs on a background thread+ whose result is published on the UI thread.
 -An asynchronous task = defined by <Params, Progress, Result> 
==>Params : type of the parameters sent to the task upon execution. 
==>Progress :type of the progress units published during the background computation.
==>Result :type of the result of the background computation.

Methods of AsyncTask
onPreExecute(),  invoked on the UI thread immediately after the task is executed.  This step is
normally used to setup the task, for instance by showing a progress bar in the user interface
doInBackground(Params...),  invoked on the background thread immediately after onPreExecute()
finishes executing. This step is used to perform background computation that can take a long time.
The parameters of the asynchronous task are passed to this step. The result of the computation
must be returned by this step and will be passed back to the last step. This step can also use
publishProgress(Progress...) to publish one or more units of progress. These values are published
on the UI thread, in the onProgressUpdate(Progress...) step. 
onProgressUpdate(Progress...),  invoked on the UI thread after a call to 
publishProgress(Progress...).  The timing of the execution is undefined. This method is used  to
display any form of progress in the user interface while the background computation is still
executing. For instance, it can be used to animate a progress bar or show logs in a text field. 
onPostExecute(Result),  invoked on the UI thread after the background computation finishes. The
result of the background computation is passed to this step as a parameter. 


============
Summary Persistency


Choisir la solution de stocker les data Selon le Type de données à persister=>(private/public;small/large)
Option de Stockage
Type de données
Shared Preferences  

Store private primitive data in key-value pairs. 

Internal Storage  
(=SDCard)
Store private data on the device memory. 

External Storage

Store public data on the shared external storage.

SQLite Databases
Store structured data in a private database. 

Network Connection  


Store data on the web with your own network server.
 Content Provider 

Shared repository globally shared by all apps.

1)Android Data Storage :

-Android utilise un système de partage de données particulier:
Sur Android, toutes les données de l'application détenus dans la zone de l'appareil de mémoire privée est privée à cette application.
==>On Android, all application data (including files)  are private to that application. 
-Content Providers :-provide a data-layer for non-Sql developers
                                 -used for global data obkects(image,audio,video File &personal contact information)
- Preferences: est un mécanisme léger pour stoker et récuperer les donnés primitives ont la forme pair<key,value>(appelled Maps,Arrays Associatives)
                        (key:String;value:TypeDonneePrimitive)
                     -utilisé pour garder l'information d'état  et les données partagées entre les activities d'une meme application.
                      -Similar to Bundles however Bundles isn't persistent
  1. getPreferences () dans votre activité, pour accéder aux préférences d'activité spécifiques

2. getSharedPreferences () à partir de votre activité pour accéder à l'application au niveau des préférences

3. getDefaultSharedPreferences (), sur PreferencesManager, pour obtenir les préférences partagées qui travaillent de concert avec le cadre d'Android préférence globale
- the getXXX Preference methods return a Preference object. (XXX= { Long, Int, Double, Boolean, String } )
-a Preference object  is manupilated by an editor .
-th Editor place data in & out the Preference container by : putXXX & getXXX

 the process of removing existing traces of an application from the phone’s system area using device’s Application Manager :



The file xml for preferences is create on this path :/data/data/<nom_package_project>/shared_prefs/YYY.xml
Avec YYY is the name of xml File for perferences  / SharedPreferences mySharedPreferences = getSharedPreferences(YYY,
                mode);



To Write in Preferences File(YYY.xml)
To Read from Preferences File(YYY.xml)
SharedPreferences settings = getSharedPreferences("<YYY>", 
                                                     Context.MODE_PRIVATE);  
SharedPreferences.Editor editor = settings.edit();
           editor.put<TYPE>(<name>, <value>);
           editor.putInt("favorite_number", 101);
   editor.commit();

  String favColor = settings.get<TYPE>(<name>, <default_value>);
   int favNumber = settings.getInt("favorite_number", 0);

===============================================
Summary of Files Tuto (Stream):
-We can put Resources files in ./res/drawable/* (with images,icons,..)
-To create InputStream to a file  ./res/drawable/my_base_data.txt
==> InputStream is = this.getResources()  .openRawResource(R.drawable.my_base_data);
- File is stored in the phone’s memory under: /data/data/app/files

External Storage:(on SDCard):
il faut ajouter cette permission dans manifest XML:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"> </uses-permission>


File myFile = new File("/sdcard/mysdfile.txt"); 
myFile.createNewFile();  


Ready Methods For IO Streams:


public class AvecTextProcedures {

  /**

   

   @param context

   @param idFile

   *            (as: R.drawable.my_file (if th file is in

   *            ./res/drawable/my_file.txt)

   @return

   @throws IOException

   */

  public String readFromFileToString(ContextWrapper context, int idFile)

      throws IOException {

    // idFile=R.drawable.my_base_data;

    String str = "";

    StringBuffer buf = new StringBuffer();



    InputStream is = context.getResources().openRawResource(idFile);



    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    if (is != null) {

      while ((str = reader.readLine()) != null) {

        buf.append(str + "\n");

      }

    }

    is.close();

    Toast.makeText(context.getBaseContext(), buf.toString(),

        Toast.LENGTH_LONG).show();

    return buf.toString();

  }



  public String readFromFileToString(ContextWrapper context, String fileName) {

    StringBuffer buf = null;

    try {

      InputStream in = context.openFileInput(fileName);

      if (in != null) {

        BufferedReader reader = new BufferedReader(

            new InputStreamReader(in));



        String str = "";

        buf = new StringBuffer();



        while ((str = reader.readLine()) != null) {

          buf.append(str + "\n");

        }

        in.close();



      }// if

    catch (java.io.FileNotFoundException e) {

      return null;

      // that's OK, we probably haven't created it yet

    catch (Throwable t) {

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

      return null;

    }

    return buf.toString();

  }



  public void writeFromStringToFile(ContextWrapper context, String nameFile,

      String text) {

    try {

      OutputStreamWriter out = new OutputStreamWriter(

          context.openFileOutput(nameFile, 0));



      // get your data from the screen’s text box

      out.write(text);

      out.close();

    catch (Throwable t) {

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

    }

  }



  public void writeOnSDCardFile(ContextWrapper context,

      String pathFileFromSDCard, String TxttoWrite) {

    // write on SD card file data from the text box

    String deviceSDCARD = Environment.getExternalStorageDirectory()

        .getPath() "/";

    try {

      File myFile = new File(deviceSDCARD + TxttoWrite);

      if (!myFile.exists()) {

        myFile.createNewFile();

      }



      FileOutputStream fOut = new FileOutputStream(myFile);

      OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

      myOutWriter.append(TxttoWrite);

      myOutWriter.close();

      fOut.close();

      Toast.makeText(context.getBaseContext(),

          "Done writing SD '" + myFile.getName() "'",

          Toast.LENGTH_SHORT).show();

    catch (Exception e) {

      Toast.makeText(context.getBaseContext(), e.getMessage(),

          Toast.LENGTH_SHORT).show();

    }

  }



  public String readFromSDCardFile(ContextWrapper context,

      String pathFileFromSDCard) {

    try {

      // String pathSDCard=

      // Environment.getExternalStorageDirectory().getPath()+"/";

      // /*(="/sdcard/")*/

      File myFile = new File("/sdcard/mysdfile2.txt");

      FileInputStream fIn = new FileInputStream(myFile);

      BufferedReader myReader = new BufferedReader(new InputStreamReader(

          fIn));

      String aDataRow = "";

      String aBuffer = "";

      while ((aDataRow = myReader.readLine()) != null) {

        aBuffer += aDataRow + "\n";

      }



      myReader.close();

      Toast.makeText(context.getBaseContext(),

          "Done reading SD " + myFile.getName()1).show();

      return aBuffer;

    catch (Exception e) {

      Toast.makeText(context.getBaseContext(), e.getMessage()1).show();

      return null;

    }

  }



  private void TMMMPPPtestScannerFiles(EditText tvMessage) {

    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("Hola Android");

      outfile.println("Adios Android");

      outfile.println(new Date().toString());

      outfile.close();

      // read SD-file,show records.

      Scanner infile = new Scanner(new FileReader(mySDFileName));

      String inString = "\n\nReading from: " + 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());

    }

  }



  public void writeOnSDCardFileByScanner(ContextWrapper context,

      String pathFileFromSDCard, String TxttoWrite) {

    try {

      String SDcardPath = Environment.getExternalStorageDirectory()

          .getPath();

      String mySDFileName = SDcardPath + "/" + pathFileFromSDCard;

      Toast.makeText(context, "Writing to: " + mySDFileName, 1);

      PrintWriter outfile = new PrintWriter(new FileWriter(mySDFileName));

      outfile.println(TxttoWrite);

      outfile.close();

    catch (FileNotFoundException e) {

      Toast.makeText(context, "Error: " + e.getMessage()1);

    catch (IOException e) {

      Toast.makeText(context, "Error: " + e.getMessage()1);

    }



  }



  public void writeOnSDCardFileFromListByScanner(ContextWrapper context,

      String pathFileFromSDCard, List<String> listToWrite) {

    try {

      String SDcardPath = Environment.getExternalStorageDirectory()

          .getPath();

      String mySDFileName = SDcardPath + "/" + pathFileFromSDCard;

      Toast.makeText(context, "Writing to: " + mySDFileName, 1);

      PrintWriter outfile = new PrintWriter(new FileWriter(mySDFileName));

      for (String line : listToWrite) {

        outfile.println(line);

      }

      ;

      outfile.close();

    catch (FileNotFoundException e) {

      Toast.makeText(context, "Error: " + e.getMessage()1);

    catch (IOException e) {

      Toast.makeText(context, "Error: " + e.getMessage()1);

    }



  }



  public List<String> readFromSDCardFileToListByScanner(

      ContextWrapper context, String pathFileFromSDCard) {

    List<String> lines = new ArrayList<String>();

    // read SD-file,show records.

    try {

      String SDcardPath = Environment.getExternalStorageDirectory()

          .getPath();

      String mySDFileName = SDcardPath + "/" + pathFileFromSDCard;

      Scanner infile = new Scanner(new FileReader(mySDFileName));

      while (infile.hasNextLine()) {

        lines.add(infile.nextLine());

      }

      infile.close();

      return lines;

    catch (FileNotFoundException e) {

      Toast.makeText(context, "Error: " + e.getMessage()1);

      return null;

    }



  }



  public String readFromSDCardFileByScanner(ContextWrapper context,

      String pathFileFromSDCard) {

    // read SD-file,show records.

    try {

      String SDcardPath = Environment.getExternalStorageDirectory()

          .getPath();

      String mySDFileName = SDcardPath + "/" + pathFileFromSDCard;

      Scanner infile = new Scanner(new FileReader(mySDFileName));

      String inString = "";

      while (infile.hasNextLine()) {

        inString += infile.nextLine() "\n";

      }

      infile.close();

      return inString;

    catch (FileNotFoundException e) {

      Toast.makeText(context, "Error: " + e.getMessage()1);

      return null;

    }



  }



  public void writeByPrintWriter(ContextWrapper context, String fileName,

      String txtToWrite) {

    FileOutputStream fos;

    try {

      fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);

      PrintWriter outfile = new PrintWriter(fos);

      outfile.println(txtToWrite);

      outfile.close();

    catch (FileNotFoundException e) {

      // TODO Auto-generated catch block

      e.printStackTrace();

    }



  }



  public void writeFromListByPrintWriter(ContextWrapper context,

      String fileName, List<String> listToWrite) {

    FileOutputStream fos;

    try {

      fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);

      PrintWriter outfile = new PrintWriter(fos);

      for (String line : listToWrite) {

        outfile.println(line);

      }



      outfile.close();

    catch (FileNotFoundException e) {

      // TODO Auto-generated catch block

      e.printStackTrace();

    }



  }



  public String readByPrintWriter(ContextWrapper context, String fileName) {



    InputStream is;

    try {

      is = context.openFileInput(fileName);

      Scanner infile = new Scanner(is);

      String inString = "";

      while (infile.hasNextLine()) {

        inString = inString.concat(infile.nextLine());



      }



      return inString;

    catch (FileNotFoundException e) {



      e.printStackTrace();

      return null;

    }



  }



  public static List<String> readFromListByPrintWriter(ContextWrapper context,

      String fileName) {

    List<String> lines = new ArrayList<String>();

    InputStream is;

    try {

      is = context.openFileInput(fileName);

      Scanner infile = new Scanner(is);

      while (infile.hasNextLine()) {

        lines.add(infile.nextLine());



      }



      return lines;

    catch (FileNotFoundException e) {



      e.printStackTrace();

      return null;

    }



  }



}


Flow(Flux)(IO/Stream) Code Source Example :

A)Activity:


public class FluxFileManager extends Activity {

  AvecTxtAndroid aveTxtAndroid;
  String result;
  Button read;
  Button write;
  Button readFromSDCard;
  Button writeToSDCard;
  EditText textToWrite;
  EditText contenuFile;

  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);



    setContentView(R.layout.main);
    read = (ButtonfindViewById(R.id.button1);
    write = (ButtonfindViewById(R.id.button2);
    readFromSDCard = (ButtonfindViewById(R.id.button3);
    writeToSDCard = (ButtonfindViewById(R.id.button4);
    textToWrite = (EditTextfindViewById(R.id.editText1);
    contenuFile = (EditTextfindViewById(R.id.editText2)
    

    

    read.setOnClickListener(new OnClickListener() {

      

      @Override

      public void onClick(View v) {

        try {

          PlayWithRawFiles(contenuFile);

        catch (IOException e) {

          Toast.makeText(getApplicationContext(),

              "Problems: " + e.getMessage()1).show();

        }

        

      }

    });

    

    write.setOnClickListener(new OnClickListener() {

      

      @Override

      public void onClick(View v) {

        

        

      }

    });

    



  }



  public void PlayWithRawFiles(EditText textReadedthrows IOException {

    String str = "";

    StringBuffer buf = new StringBuffer();



    InputStream is = this.getResources().openRawResource(

        R.drawable.my_base_data);



    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    if (is != null) {

      while ((str = reader.readLine()) != null) {

        buf.append(str + "\n");

      }

    }

    is.close();

    Toast.makeText(getBaseContext(), buf.toString(), Toast.LENGTH_LONG)

        .show();

    textReaded.setText(buf.toString());

  }

  

  

  public void writeToSDcard(String namFile,EditText txtData){

    String pathSDCard= Environment.getExternalStorageDirectory().getPath()+"/"/*(="/sdcard/")*/

    try {

      OutputStreamWriter myOutWriter;

    File myFile = new File("/sdcard/"+namFile);

    myFile.createNewFile();

    myOutWriter = new OutputStreamWriter

                new FileOutputStream(myFile) );

    myOutWriter.append(txtData.getText());

    myOutWriter.close();

    catch (IOException e) {

      // TODO Auto-generated catch block

      e.printStackTrace();

    }

    

  }



  public void tryWithMyFW() {

    InputStream is = this.getResources().openRawResource(

        R.drawable.my_base_data);

    aveTxtAndroid = new AvecTxtAndroid("", is);

    result = aveTxtAndroid.lireDeFEcrireDansStringWithInputStream();

    System.out.println(result);

    try {

      aveTxtAndroid.getInputStream().close();

    catch (IOException e) {



      e.printStackTrace();

    }

    if (result.equals(null)) {

      result = "je suis null";

    }

    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG);

  }

}

B)Layout XML File:
todo

C)Manifest XML File:
todo


D)Result:




No comments:

Post a Comment