0

How i can access ArrayList from one Activity to another and also clear ArrayList value and store & retrieve it to database?

Sample Code:

**Activity 1:**

public static ArrayList<String> arrList =new ArrayList<String>();
arrList.clear();
arrList.add(0,txt_phone1.getText().toString());
arrList.add(1,txt_phone2.getText().toString());
finish();   



**Activity 2:**

dbAdapter.openDataBase();
Cursor c = dbAdapter.selectRecordsFromDB("SELECT * FROM tbProspect where id="+row_id,null);
c.moveToFirst();
            contact_details.arrList.add(c.getString(c.getColumnIndex("Phone1")));
            contact_details.arrList.add(c.getString(c.getColumnIndex("Phone2")));
c.close();dbAdapter.close();
1
  • do you have any problem with code you posted here ? Commented Jan 28, 2012 at 12:33

2 Answers 2

2

The best way to that is to create a singleton of your shared objects, and get/set your objects when needed from anywhere in your application.

Just remember to call getInstance() at the onCreate() of each Activity.

public class SharedObjects {

    static SharedObjects instance;
    ArrayList<String> shraedList;

    private SharedObjects()
    {
        shraedList = new ArrayList<String>();
    }

    public synchronized static DataContext getInstance()
    {
        if (instance == null)
            instance = new SharedObjects();

        return instance;
    }

    public ArrayList<String> getArrayList()
    {
        return instance.shraedList;
    }

    public void setArrayList(ArrayList<String> sharedList)
    {
    this.sharedList = sharedList;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I disagree with the use of Singletons. You can find a discussion here stackoverflow.com/questions/3826905/…
0

I would recommend extending the application context:

public class MyApplication extends Application {
   // Your functions here
   getArray()
};

Update AndroidManifest.xml:

<application
        android:name=".MyApplication"
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
...
</Application>

To get application context:

(MyApplication)getApplication();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.