I am writing an application on Android Studio. Through the code at the press of a button, additional fields are added to the post.

In the loop, I get values ​​from dynamically added fields. Question: how to put all the fields in a variable to use it in the future?

String[] items = new String[allEds.size()]; //запускаСм Ρ‡Ρ‚Π΅Π½ΠΈΠ΅ всСх Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚ΠΎΠ² этого списка ΠΈ запись Π² массив for (int i = 0; i < allEds.size(); i++) { String strNamePers = (items[i] = ((EditText) allEds.get(i).findViewById(R.id.perona1)).getText().toString()); String strNameVoz = (items[i] = ((EditText) allEds.get(i).findViewById(R.id.peronavoz2)).getText().toString()); String strNameTreb = (items[i] = ((EditText) allEds.get(i).findViewById(R.id.peronatreb3)).getText().toString()); String strNameInt = (items[i] = ((EditText) allEds.get(i).findViewById(R.id.peronasumm4)).getText().toString()); String hr="<hr>"; String br = "<br>"; fnlstr = (br +"Π½Π°Π·Π²Π°Π½ΠΈΠ΅ пСрсонаТа: " + strNamePers + br+"возраст: "+strNameVoz+br+"трСбования ΠΊ Ρ‚ΠΈΠΏΠ°ΠΆΡƒ: "+strNameTreb+br+"Π‘ΡƒΠΌΠΌΠ° ΠΎΠΏΠ»Π°Ρ‚Ρ‹"+strNameInt+br+hr); Log.d("mylog", "масив с ΠΏΠΎΠ»Π΅ΠΉ " + fnlstr); } 

The problem is that the variable fnlstr stores only the value of the last iteration of the loop. How to make all iterations add up to one line and enter the fnlstr variable?

    1 answer 1

    If you need to concatenate (concatenate) all the received strings into one, then this is done through the operator + ( += ):

     fnlstr += (br +"Π½Π°Π·Π²Π°Π½ΠΈΠ΅ пСрсонаТа: " + strNamePers + br+"возраст: "+strNameVoz+br+"трСбования ΠΊ Ρ‚ΠΈΠΏΠ°ΠΆΡƒ: "+strNameTreb+br+"Π‘ΡƒΠΌΠΌΠ° ΠΎΠΏΠ»Π°Ρ‚Ρ‹"+strNameInt+br+hr); 

    If the fnlstr loop fnlstr not initialized, then you need to do it.

     fnlstr = ""; for... 

    Unfortunately, string concatenation in a loop is similarly inefficient, since each iteration creates a new, longer string. So when you need to add strings together in a loop, you use a StringBuilder .

     StringBuilder fnlstrBuilder = new StringBuilder(); for (int i = 0; i < allEds.size(); i++) { //ΠΏΡ€ΠΎΠΏΡƒΡ‰Π΅Π½ Π½Π΅ ΠΈΠΌΠ΅ΡŽΡ‰ΠΈΠΉ ΠΎΡ‚Π½ΠΎΡˆΠ΅Π½ΠΈΡ ΠΊ Π΄Π΅Π»Ρƒ ΠΊΠΎΠ΄ fnlstrBuilder.append(br +"Π½Π°Π·Π²Π°Π½ΠΈΠ΅ пСрсонаТа: " + strNamePers + br+"возраст: "+strNameVoz+br+"трСбования ΠΊ Ρ‚ΠΈΠΏΠ°ΠΆΡƒ: "+strNameTreb+br+"Π‘ΡƒΠΌΠΌΠ° ΠΎΠΏΠ»Π°Ρ‚Ρ‹"+strNameInt+br+hr); } 

    After the loop, you can get the string with toString :

     fnlstr = fnlstrBuilder.toString(); 
    • The application crashes with the error java.lang.NullPointerException
    • the first option is fnlstr + = (br + "character name:" + strNamePers + br + "age:" + strNameVoz + br + "type requirements:" + strNameTreb + br + "Payment amount" + strNameInt + br + hr); Perfectly put all the iterations .... Thank you) - dimasta68
    • @ dimasta68 Please, if that error says that you have not created a StringBuilder . Check that the code is = new StringBuilder(); and that it is assigned to the correct variable. - default locale