Add Items to an ArrayList<String> that has been passed between Activities

帅比萌擦擦* 提交于 2020-01-05 12:12:30

问题


I have Looked around here on StackOverflow and the internet and tried a few things but all of them are giving me the same general problem.

I have an ArrayList that I create in one activity and then send it through (another activity or 2 others depending on the users choices) and in each activity (including the one that the arraylist is created in) has the user select a single button from a group. Upon selecting the button I have a listener that creates a simple string and then adds that String to the ArrayList, or at least that's what I want it to do.

  1. I have tried using Serialized classes to pass the same list through all the activities it needs to go through
  2. I have tried making a new ArrayList in each class, copying the one from the previous class that was sent via an intent.putExtra() and then received so it could be copied into a new arraylist to do the same thing until it gets to the final Activity.
  3. I have tried to make sense of Parcleable implementation but It just seems like to much for me (I'm not to good at this right now).

All of these have given me the same NullPointerException whenever I try and use the .add() method of the ArrayList (or the .addAll() in terms of the second attempt to get this done.

Any suggestions along with explanations you would have to give to a beginner would be greatly appreciated! I can put code if needed!!


回答1:


First thing, you should use Parcelable, it is more efficient in this case. Have a look at this link for the "why":
https://medium.com/@theblackcat102/passing-object-between-activity-using-gson-7dfa11d74e06

Second, I'd do it like this:

public class ActivityOne extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        Intent intent = new Intent(this, ActivityTwo.class);
        ArrayList<Person> strings = new ArrayList<Person>(Arrays.asList(new Person("Bob"),new Person("Dude")));
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(ActivityTwo.PARCELABLE_KEY,strings);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}


public class ActivityTwo extends Activity {
    public static final String PARCELABLE_KEY = "array_key";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        if (getIntent() != null) {
            ArrayList<Person> persons = getIntent().getParcelableArrayListExtra(PARCELABLE_KEY);
            Log.d("test", persons.toString());
        }
    }
}

public class Person implements Parcelable {

    private String name;

    public String getName() {
        return name;
    }

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

    public Person() {
    }

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


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.name);
    }

    public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
        public Person createFromParcel(Parcel source) {
            return new Person(source);
        }

        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

    private Person(Parcel in) {
        this.name = in.readString();
    }
}

Also, do not be afraid of Parcelables! And as a good developer, you should be lazy, then use a Parcelable generator such as:
http://www.parcelabler.com/

Just copy your POJO class(es) and generate (an Android Studio plugin also exists).

Finally, don't forget that you cannot pass unlimited data between 2 activities. You could also consider putting your data into a database.




回答2:


I put together a quick example of passing the array list to other activities and adding items to it.

public class FirstActivity extends Activity {

    public static final String EXTRA_FIRST_ARRAY = "ExtraFirstArray";

    private static final String TAG = FirstActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayList<String> firstArrayList = new ArrayList<String>();

        firstArrayList.add("First Activity Test1");
        firstArrayList.add("First Activity Test2");
        firstArrayList.add("First Activity Test3");

        Log.d(TAG, "First Array List: ");

        for (String value : firstArrayList) {
            Log.d(TAG, "Value: " + value);
        }

        Intent intent = new Intent(this, SecondActivity.class);
        intent.putStringArrayListExtra(EXTRA_FIRST_ARRAY, firstArrayList);
        startActivity(intent);
    }
}

public class SecondActivity extends Activity {

    public static final String EXTRA_SECOND_ARRAY = "ExtraSecondArray";

    private static final String TAG = SecondActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().getExtras() != null) {

            final ArrayList<String> firstArrayList = getIntent().getStringArrayListExtra(FirstActivity.EXTRA_FIRST_ARRAY);

            ArrayList<String> secondArrayList = new ArrayList<String>();

            secondArrayList.addAll(firstArrayList);

            secondArrayList.add("Second Activity Test1");
            secondArrayList.add("Second Activity Test2");
            secondArrayList.add("Second Activity Test3");

            Log.d(TAG, "Second Array List: ");

            for (String value : secondArrayList) {
                Log.d(TAG, "Value: " + value);
            }

            Intent intent = new Intent(this, ThirdActivity.class);
            intent.putStringArrayListExtra(EXTRA_SECOND_ARRAY, secondArrayList);
            startActivity(intent);
        }
    }
}

public class ThirdActivity extends Activity {

    private static final String TAG = ThirdActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().getExtras() != null) {

            final ArrayList<String> secondArrayList = getIntent().getStringArrayListExtra(SecondActivity.EXTRA_SECOND_ARRAY);

            ArrayList<String> thirdArrayList = new ArrayList<String>();

            thirdArrayList.addAll(secondArrayList);

            thirdArrayList.add("Third Activity Test1");
            thirdArrayList.add("Third Activity Test2");
            thirdArrayList.add("Third Activity Test3");

            Log.d(TAG, "Third Array List: ");

            for (String value : thirdArrayList) {
                Log.d(TAG, "Value: " + value);
            }
        }
    }
}



回答3:


If you have some data that you want to share among activities i would personally suggest that u keep them as a field on the application object so u would need to extend the application class.

public class MyApplication extend Application{

private List<SomeData> data;

@overrite
public void onCreate(){
super.onCreate();
data = new ArrayList<SomeData>();
}

public List<SomeData> getData(){

return data
}
}

In the manifest file you would have to configure ur application class in the application xml-tag

<application
android:name:"package.name.MyApplication">
</application>

Finally in ur activities you can access them by calling:

((MyApplication)getApplication()).getData();

In this way you dont consume resources on serializing/deserializing and you have access globally in the application context. Just pay attention to not overdo this as those data will occupy the memory independently from any activity. but if intend to persist some data which u will frequently access from different this is a optimized solution compare to serializing or passing through Parcelable interface.




回答4:


You can use also custom intent :

public class SharedIntent extends Intent {
    private List list;

    public void putArrayList(List list){
        this.list = list;
    }

    public List getList(){
        return list;
    }
}

Send :

public class SenderActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedIntent intent = new SharedIntent();
        intent.putArrayList(new ArrayList<String>());
    }
}

Retrieve :

public class GettingActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent() instanceof SharedIntent) {
            SharedIntent intent = (SharedIntent) getIntent();
            ArrayList<String> list = (ArrayList<String>) intent.getList();
        }
    }
}


来源:https://stackoverflow.com/questions/25002788/add-items-to-an-arrayliststring-that-has-been-passed-between-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!