android listview not working

浪尽此生 提交于 2020-01-03 05:37:34

问题


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);
}

回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/25313342/android-listview-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!