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();
Prakash
  • 5
  • 1
  • 2

2 Answers2

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;
    }
}
Rotemmiz
  • 7,933
  • 3
  • 36
  • 36
  • I disagree with the use of Singletons. You can find a discussion here http://stackoverflow.com/questions/3826905/singletons-vs-application-context-in-android – Frohnzie Jan 28 '12 at 16:54
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();
Frohnzie
  • 3,559
  • 1
  • 21
  • 24