Showing posts with label passing object. Show all posts
Showing posts with label passing object. Show all posts

Sunday, 6 January 2013

Sending ArrayList of Objects as extras from one Activity to Other

Question.java
public class Question implements Serializable {

    private int[] operands;
    private int[] choices;
    private int userAnswerIndex;

    public Question(int[] operands, int[] choices) {
        this.operands = operands;
        this.choices = choices;
        this.userAnswerIndex = -1;
    }

    public int[] getChoices() {
        return choices;
    }

    public void setChoices(int[] choices) {
        this.choices = choices;
    }

    public int[] getOperands() {
        return operands;
    }

    public void setOperands(int[] operands) {
        this.operands = operands;
    }

    public int getUserAnswerIndex() {
        return userAnswerIndex;
    }

    public void setUserAnswerIndex(int userAnswerIndex) {
        this.userAnswerIndex = userAnswerIndex;
    }

    public int getAnswer() {
        int answer = 0;
        for (int operand : operands) {
            answer += operand;
        }
        return answer;
    }

    public boolean isCorrect() {
        return getAnswer() == choices[this.userAnswerIndex];
    }

    public boolean hasAnswered() {
        return userAnswerIndex != -1;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        // Question
        builder.append("Question: ");
        for(int operand : operands) {
            builder.append(String.format("%d ", operand));
        }
        builder.append(System.getProperty("line.separator"));

        // Choices
        int answer = getAnswer();
        for (int choice : choices) {
            if (choice == answer) {
                builder.append(String.format("%d (A) ", choice));
            } else {
                builder.append(String.format("%d ", choice));
            }
        }
        return builder.toString();
       }

      }

In your Source Activity, use this :

List<Question> mQuestionList = new ArrayList<Question>;
int[] ops = {1,2,3,4,5};
int[] choices = {12,45,23,16};
mQuestionList.add(new Question(ops, choices));

ops1 = {11,22,33,44,55};
choices1 = {122,453,423,516};
mQuestionList.add(new Question(ops1, choices1));

Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("QuestionListExtra", ArrayList<Question>mQuestionList);


In your Target Activity, use this :

List<Question> questions = new ArrayList<Question>();
 questions = (ArrayList<Question>)getIntent().getSerializableExtra("QuestionListExtra");

Passing Object From one Activity to other by serializable in Android

First, create  user interface layouts that are needed as follows and your project structure should like this :

Project Structure :


main.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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="22dp"
        android:layout_marginTop="24dp"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/name_edit_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/textView1"
        android:ems="10"
        android:inputType="textPersonName" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@id/name_edit_text"
        android:layout_marginTop="33dp"
        android:text="Age"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/age_edit_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/textView2"
        android:layout_marginLeft="22dp"
        android:layout_toRightOf="@+id/textView2"
        android:ems="10" />

    <Button
        android:id="@+id/passing_list_of_obj_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_centerVertical="true"
        android:text="Passing an Object" />

</RelativeLayout>

second_layout.xml

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

        <TextView
            android:id="@+id/tar_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="54dp"
            android:layout_marginTop="56dp"
            android:text="Age"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </RelativeLayout>

Person.java

package com.rajeshvijayakumar.model;

import java.io.Serializable;

public class Person implements Serializable {

    private static final long serialVersionUID = -3166526974851472532L;
   
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }   
}


MainActivity.java

package com.rajeshvijayakumar.extrasdemo;

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.EditText;

import com.rajeshvijayakumar.model.Person;

public class MainActivity extends Activity implements OnClickListener {

    // UI reference
    private EditText mNameEditText;
    private EditText mAgeEditText;
    private Button mPassingListOfObjButton;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mNameEditText = (EditText) findViewById(R.id.name_edit_text);
        mAgeEditText = (EditText) findViewById(R.id.age_edit_text);
        mPassingListOfObjButton = (Button) findViewById(R.id.passing_list_of_obj_button);
        mPassingListOfObjButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Class<?> clazz = null;
        String nameText = mNameEditText.getText().toString();
        String ageText = mAgeEditText.getText().toString();
        Person person = new Person(nameText, Integer.valueOf(ageText));

        switch (v.getId()) {
        case R.id.passing_list_of_obj_button:
            clazz = TargetActivity.class;
            break;
        }

        if (clazz != null) {
            Intent intent = new Intent(MainActivity.this, clazz);
            intent.putExtra("PERSON_OBJ_KEY", person);
            startActivity(intent);
        }
    }
}

TargetActivity.java

package com.rajeshvijayakumar.extrasdemo;

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

import com.rajeshvijayakumar.model.Person;

public class TargetActivity extends Activity {

    private TextView mTarTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_layout);
        mTarTextView = (TextView) findViewById(R.id.tar_text_view);
        Person person = (Person) getIntent().getSerializableExtra("PERSON_OBJ_KEY");
        String textVal = "Name : "+ person.getName() + " \nAge : "+ person.getAge();
        mTarTextView.setText(textVal);
    }

}

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rajeshvijayakumar.extrasdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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=".TargetActivity" />
    </application>

</manifest>

Output :





Source : Download this Example Here