martedì 21 gennaio 2014

Passare dati tra Activity


Obbiettivo:
       - Chiamare un'altra activity passando dati.
       - Leggere i dati che ci vengono passati da una activity.

Strumenti necessari:
    Android Developer Tools (ADT) .
       - AVD / Smartphone debug.

Cose da fare:
      1) Creare il progetto
      2) Creo 2 layout
      3)  Creo 2 activity corrispondenti 
      4) Definire il Manifest



1) Creare il progetto
     - File >> New >> Android Application
      - Insert name project: TestAndroid
     - packcage: com.example.exercise.android
      - Finish

2) Creo 2 Layout
    - Definiamo i 2 layout, uno si chiamerà activity_one e l'altro activity_two.
      
      - res/layout/activity_one.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    <TextView
        android:id="@+id/tvHelloWorld"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello world" />
    <Button
        android:id="@+id/btnPassData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvHelloWorld"
        android:layout_marginTop="26dp"
        android:layout_centerHorizontal="true"
        android:onClick="clickStartTwoActivity"
        android:text="Pass Data to Another Activity" />
</RelativeLayout>


- res/layout/activity_two.xml

<?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:id="@+id/respMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>



3)  Creo 2 activity corrispondenti 

      - src/com/example/exercise/android/OneActivity.java
      - Avrà un metodo clickStartTwoActivity già stato definito nel layout (button) che eseguirà lo  start        di     un'altra activity passando come parametro  una stringa "Hello from mainActivity" :

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
    }
        
        public void clickStartTwoActivit(View view){
      

       // 1. create l'intent relativa alla classe da chiamare.
        Intent intent = new Intent(getApplicationContext(),TwoActivity.class);
        // 2. put key/value data
        intent.putExtra("message", "Hello From MainActivity");
        // 3. or you can add data to a bundle
       
        Bundle extras = new Bundle();
        extras.putString("status", "Data Received!");
               
                //con il bundle si può anche passare un oggetto;
        // l'importante è avere un oggetto che implementa Serialize
        // e fare il put cosi:
        // extras.put("objKey", oggettoSerialize);
        // 4. add bundle to intent
        intent.putExtras(extras);
        // 5. start the activity
        startActivity(intent);
   }
 
      - src/com/example/exercise/android/TwoActivity.java
      - Nel metodo onCreate andremo a riprendere il valore (Hello From MainActivity) e lo setteremo nella textview presente nel secondo layout. Creiamo anche un Toast per visualizzare la scritta dello "status" che compare solo per qualche istante (essendo un toast)

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        // 1. get passed intent
        Intent intent = getIntent();
        // 2. get message value from intent
        String message = intent.getStringExtra("message");
        // 3. show message on textView
        ((TextView)findViewById(R.id.respMessage)).setText(message);
        // 4. get bundle from intent
        Bundle bundle = intent.getExtras();
        // 5. get status value from bundle
        String status = bundle.getString("status");
        // 6. show status on Toast
        Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
        toast.show();
    }
4) Definire il Manifest
- Tutte le activity devono essere dichiarate nel manifest.xml
 <?xml version="1.0" encoding="utf-8"?>
    package="com.example.exercise.android"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.exercise.android.OneActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.exercise.android.TwoActivity"
            android:label="@string/app_name" > 
        </activity>
    </application>
</manifest>
 

Nessun commento:

Posta un commento