Janos Janos - 4 months ago 16
Android Question

Arraylist elements starting too much activity

I am developing an application, that sends a string array with putStringArrayListExtra. In the second activity I am receiving. The problem, if I send 2 item, 2 activity will open. The second element is on the listview(shows just one), when i click back, there is now the first item. I want the 2 item in the SAME listview. What am I doing wrong?

First activity

final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
// String result = "";
String ar="";


for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
cnt++;
ar = nev[i];
selectImages = nev[i] + "|";
// List<String> myList = new ArrayList<String>(Arrays.asList(selectImages));
ArrayList<String> arr = new ArrayList<String>();
arr.add(selectImages);

Intent intent = new Intent(Gallery.this,Upload.class);
intent.putStringArrayListExtra("array_list", arr);

startActivity(intent);

// Log.i("adat","galleri:" + arr);





}

}
if (cnt == 0){
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else {





Toast.makeText(getApplicationContext(),
"You've selected Total " + cnt + " image(s).",
Toast.LENGTH_LONG).show();

}
}
});


Second activity

ListView listView;

ArrayAdapter<String> adapter;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

listView = (ListView) findViewById(R.id.list);

Bundle b = getIntent().getExtras();


// ArrayList<String> arr = (ArrayList<String>)b.getStringArrayList("array_list");
ArrayList<String> arr = b.getStringArrayList("array_list");
Log.i("adat","UPLOAD:"+arr);


ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, arr);
listView.setAdapter(adapter);

}

Answer

Do like below while you are creating new arraylist everytime when you loop thats why you are not getting correct values.

And also take you intent outside the loop too.

  ArrayList<String> arr = new ArrayList<String>();
  for (int i =0; i<len; i++)
            {
                if (thumbnailsselection[i])
                {
                    cnt++;
                    ar = nev[i];
                    selectImages = nev[i] + "|";
                    // List<String> myList = new ArrayList<String>(Arrays.asList(selectImages));
                    //ArrayList<String> arr = new ArrayList<String>();
                    arr.add(selectImages); 
                    // Log.i("adat","galleri:" + arr);

                } 
            }

                    Intent intent = new Intent(Gallery.this,Upload.class);
                    intent.putStringArrayListExtra("array_list", arr);
                    startActivity(intent);