Kulwant
Kulwant

Reputation: 35

For Loop array is not working in listview in android

I want to display array items in listview but when I used simple array then it works properly and when I create array using loop it does not working. here is my code

public class MainActivity extends Activity {
String nm;
int number=0;
int ttl;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv=(TextView) findViewById(R.id.textView1);
    ListView listView = (ListView) findViewById(R.id.list);
    //String[] values =new String[]{"val1","val2"};
ContentResolver cr=getContentResolver();    
 Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
         null, null, null, null);
 ttl=cur.getCount()+1;
    String[] myString = new String[ttl];

    List<String> values = new ArrayList<String>();

    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));
        String name = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
            //Query phone here.  Covered next
           nm=nm + name;
          number++;
  //   myString[number] = "image" + number;
    values.add(myString[number]);
        }
            }
    }

String[] myString1 = new String[12];
    for (int number1 = 0; number1 <= 11; number1++) {

        myString1[number1] = "image1" + number1;
    }


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



        }

Upvotes: 0

Views: 463

Answers (2)

Aniruddha
Aniruddha

Reputation: 4487

Replace this

values.add(myString[number]);

by

values.add(nm);

You are adding myString[number] to ArrayList. Where as the myString doesn't contain any elements, it is just an empty array with size ttl. If you had not initialized like String[] myString = new String[ttl] then at values.add(myString[number]) you would have got ArrayIndexOutOfBounds exception. And you don't need to use nm=nm + name, it is unnecessary.

Assuming you want to add the names into the list. If you want to add "image" + number; into the list then just uncomment that line.

Upvotes: 2

user3651987
user3651987

Reputation: 21

Replace your code by this.

Use Array list instead of string array. It gives add method to add String in it.

  ArrayList<String> ar=new ArrayList<String>();

    for (int number1 = 0; number1 <= 11; number1++) {


        ar.add("image1" + number1);


    }

Upvotes: 0

Related Questions