2013-04-07 25 views
-3

我在我的代碼中有4個數組,每次用戶在edittext中寫入一些內容我想將該字符串存儲在數組中的一個數組中,我嘗試使用toCharArray方法,但是我不「知道如何定義在字符串應該被放在陣列:S如何添加新的字符串到某個數組

String [] array7 = {"Hey","Was Up","Yeahh"}; 
    TextView txtV1,txtV2; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.layouttry); 
     txtV1=(TextView)findViewById(R.id.textView1); 
     txtV2=(TextView)findViewById(R.id.textView2); 



     Bundle extras = getIntent().getExtras(); 
     String value = extras.getString("Key"); // this value I want to add to the stringarray 
+3

一些代碼肯定會使這個問題有意義。 – christopher 2013-04-07 18:23:11

+0

謝謝:)這是非常有幫助的! – Marques 2013-04-07 18:25:40

+0

他的意思是。你的問題並不清楚,將你的代碼複製並粘貼到問題中,或者至少試着更具體一些 - 數組是什麼類型,你將如何決定每個字符串的數組等等。 – 2013-04-07 18:31:21

回答

2

如果您需要添加新的元素,我建議使用的ArrayList更換您的陣列。這將允許您使用add方法插入新元素。這方面的一個例子:

ArrayList<String> stringList = new ArrayList<String>(); 
stringList.add("Text here"); 
0

在你的代碼中,我只能在字符串上看到一個數組,所以我不確定你實際需要什麼。儘管我會盡力而爲。

您的字符串數組被硬編碼爲只有三個單元格,並且它們都已滿。如果你想將字符串到這些地方,這樣做:

array7[0] = value; //or: 
array7[1] = value; //or: 
array7[1] = value; 

如果你想添加value到陣列,而不刪除現有的值,你可以做這樣的事情:

//Create a new array, larger than the original. 
String[] newArray7 = new String[array7.length + 1 /*1 is the minimum you are going to need, but it is better to add more. Two times the current length would be a good idea*/]; 

//Copy the contents of the old array into the new one. 
for (int i = 0; i < array7.length; i++){ 
    newArray7[i] = array7[i]; 
} 

//Set the old array's name to point to the new array object. 
array7 = newArray7; 

你可以用單獨的方法來做到這一點,所以無論何時需要重新調整陣列的大小,都可以使用它。你應該知道ArrayList和Vector類已經爲你實現了這個機制,並且你可以儘可能多地使用arrayList.add(string)

相關問題