Don Grey
Don Grey

Reputation: 1

android listview not working

i am new to android development, and i just learnt about list views and array adapters etc. I have a project in android studio that has multiple activities and in one i have a array adapter and a list view, but every time i run the app and switch to the activity that has the list view in it the app does not respond and it closes. I have checked the code and it is the same as the code in the several tutorials i have seen. I think that it has something to do with the multiple activities i have, can someone help me?

public class StoreActivity extends ActionBarActivity {

String[] storeList = {"Ship 1", "Ship 2", "Ship 3"};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_store);

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

    ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, storeList);
    store.setAdapter(adapter);
}

Upvotes: 0

Views: 1496

Answers (2)

Jorgesys
Jorgesys

Reputation: 126445

If you are unsing an ArrayAdapter this is the correct way to initialize it:

  ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, storeList);

for example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_store);

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

    //ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, storeList);
     ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, storeList);
    store.setAdapter(adapter);
}

but supossing that you want to load data inside your custom row layout (row_layout.xml), add the id of the textView (i think this is what you need) :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_store);

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

    //ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, storeList);
     ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.row_layout,  R.id.myTextView, storeList);
    store.setAdapter(adapter);
}

Upvotes: 1

cheko506
cheko506

Reputation: 368

Change this line

    ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, storeList);

to this:

ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, R.id.TextViewofRow_layoutstoreList, storeList);

You need to say in which textview you will put your data.

Upvotes: 1

Related Questions