0

I have an Input with a button to add items in a listview but I want to recover all item in other activity but there are 4 activitys where I want to recover items. I hope somebody can help me. There is the code of my MainActivity where is the input to add in the listview

public class MainActivity extends AppCompatActivity {

private Button bt2;
private EditText et;
private Button bt;
private ListView lv;
public ArrayList<String> arrayList;
private ArrayAdapter<String> customeAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    et = (EditText) findViewById(R.id.editText);
    bt = (Button) findViewById(R.id.button);
    lv = (ListView) findViewById(R.id.listview);
    bt2 = (Button) findViewById(R.id.button2);

    arrayList = new ArrayList<String>();
    customeAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);

    bt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            intent.putStringArrayListExtra("arraylist",arrayList);
            startActivity(intent);
        }
    });

    lv.setAdapter(customeAdapter);
    onBtnClick();

}

public void onBtnClick() {
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           String result = et.getText().toString();
           arrayList.add(result);
           customeAdapter.notifyDataSetChanged();
        }
    });
}

}

public class Main2Activity extends AppCompatActivity {

private TextView tv;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    tv = (TextView) findViewById(R.id.tvMainTwo);


    Intent intent = getIntent();
    ArrayList<String> arrayList = intent.getStringArrayListExtra("arrayList");


    Random theRandom = new Random();
    int playersNumb = theRandom.nextInt(arrayList.size());
    tv.setText(tv.getText() + " " + arrayList.get(playersNumb));

}

}

  • What do you want exactly? – Beyazid Apr 09 '19 at 12:41
  • What do you mean by recover ? do you mean to pass this list to activity? – Mayur Gajra Apr 09 '19 at 12:41
  • Possible duplicate of [How to share same data between multiple activities](https://stackoverflow.com/questions/7885276/how-to-share-same-data-between-multiple-activities) – Kunu Apr 09 '19 at 12:42
  • I create a game where people have to write the name of all players and then in the activity, one is choose randomly and write in a textView. Does it help you to understand what i want to say ? – Gabriel Gofflot Apr 09 '19 at 12:43

6 Answers6

0

you may try using shared viewmodel to share data between activities. or you can save the data's into SQlite database.

Md Golam Rahman Tushar
  • 2,175
  • 1
  • 14
  • 29
0

There is built in android feature for your problem. It is called Intents and putExtra. Sample code below

val parametersGoHere: ArrayList<SomethingParcalableOrSerializable> = arrayListOf()
val intent = Intent(context, AnotherActivity.javaClass).putExtra("key", parametersGoHere)
context.startActivity(intent)

In next activity you can recover data by calling

(ArrayList<OfYourType>)(getIntent().getExtras().getSerializable("key"))
Sebastian Pakieła
  • 2,970
  • 1
  • 16
  • 24
0

In one activity you have an ArrayList which backs your listview. You update the ArrayList by some input through the user interface. Then you want to use the data in that ArrayList in other activities.

The alternatives you have are:

1) Send the data in an intent.
The data must be Serializable or Parcelable

2) Pesist the data and have the other activities read the persisted data.
In some way you will also need to serialize the data in order to persist it. The alternatives for persisting data are SharedPreferences, a flat file for convenience in the app's private storage folder, or in SQLite.

If you have complex objects in the ArrayList as data, one way you can make the ArrayList a String that can be serialized, is to encode it to Json using the Gson library. Depending on the way you choose to go you can use Gson() with the entire ArrayList or with each element.

EDIT I

For ArrayList<String> in particular you can sen the ArrayList in the intent itself.

Intent intent = new Intent(this, AnotherActivity.class);
intent.putStringArrayListExtra("arraylist",arraylist);
startActivity(intent);

In AnotherActivity class

private ArrayList<String> arraylist;

and in onCrate():

// You will have to add the checking for null values.

Intent intent = getIntent();
arraylist = intent.getStringArrayListExtra("arraylist");
Juan
  • 5,525
  • 2
  • 15
  • 26
0

For open/display second screen, use Intnet and pass the arraylist with extras.

Intent intent = new Intent(CurretnActivity.this, SecondActivity.class);
intent.putExtra("arrayList", arrayList);
startActivity(intent);

get the arraylist in SecondActivity using below line.

ArrayList<String> arrayList = new ArrayList<>();
if (getIntent() != null) {
      arrayList = (ArrayList<String>) getIntent().getSerializableExtra("arrayList");
}
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
0

you should create a singleton data class and get list from every activity on create and and update list from each activity

public class DataHolder {
private String data;
public String getData() {return data;}
public void setData(String data) {this.data = data;}

private static final DataHolder holder = new DataHolder();
public static DataHolder getInstance() {return holder;}
} 

for getting data:

String data = DataHolder.getInstance().getData();
  • Better than the usual singletons, I prefer using a class which directly returns and write data from/to SharedPreferences. It will save you from those NPEs when the OS clears the singleton in case of low memory. – Sufian Apr 09 '19 at 13:10
  • you can check data before using it but yes its safer to use room or SharedPreferences – Poorya Taghizade Apr 09 '19 at 13:15
0

Intent.class

To start others activities and send values.

Send values

Map<String, String> hashMap = new HashMap<>(); // or List, or Set...
Intent intent = new Intent(SourceActivity.this, DestinationActivity.class);
intent.putExtra("hashMap", hashMap); // putArray(), putChars()...
startActivity(intent);

Receive values

Intent intent = getIntent();    
HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("hashMap");

¡¡CODE NOT TESTED BUT IDEA IS CORRECT!!

bgtiban
  • 1
  • 1