开发者

Passing String array between two class in android application

开发者 https://www.devze.com 2023-02-15 18:13 出处:网络
I a开发者_开发技巧m 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

I a开发者_开发技巧m 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?


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");
}


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();


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)


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号