11

I am new to Android. How should I pass a String array between two classes?

I tried Intent, by sharing String array between the class, but I get only one String, the rest of the Strings will not displayed.

Can I use a Bundle? Is there some better way to pass a String array?

1

4 Answers 4

45

If you are trying to send a String-array from one Activity to another this can be done in the Intent.

In ClassA:

Intent intent = new Intent(this, ClassB);
String[] myStrings = new String[] {"test", "test2"};
intent.putExtra("strings", myStrings);
startActivity(intent);

In ClassB:

public void onCreate() {
  Intent intent = getIntent();
  String[] myStrings = intent.getStringArrayExtra("strings");
}
Sign up to request clarification or add additional context in comments.

1 Comment

1

I suggest you to make get_array of set_array function in the class it is very simple I hope you already know this.

//Right in A... Class

String array[]=new String[5];
public void set_array(String arg[])
{
    array=arg;
}

public String[] get_array()
{
    return array;
}

//Right in B.. class for geting a string array

A mAObject=new A();
String classA_array=mAObject.get_array();

Comments

1

If what you want to do is to pass data back and forth between activities, ie from Activity A, start Activity B and pass the string array, you can use the putStringArrayListExtra method when creating the intent:

http://developer.android.com/reference/android/content/Intent.html#putStringArrayListExtra%28java.lang.String,%20java.util.ArrayList%3Cjava.lang.String%3E%29

so in Activity A you would do something like:

Intent intentB = new Intent(this, ActivityB.class);
intentB.putStringArrayListExtra("name", <the array>);
this.startActivity(intentB)

Comments

0

Intent can send serializable data between activities. If you want to send an serializable object, follow behind:

class MyObject implements Serializable{
    // ...
}
Intent intent = new Intent();
// myObject needs to be serializable
MyObject myObject = new MyObject();
intent.putExtra("extra", myObject);
startActivity(intent);

ArrayList is serializable, so you can send it by Intent directly.

Intent intent = new Intent();
ArrayList<String> arr = new ArrayList<>;
intent.putExtra("arr", arr);
startActivity(intent);

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.