Android: ваш контент должен иметь ListView, атрибут id которого равен android.R.id.list.

Я получаю эту ошибку во время выполнения, и я действительно изо всех сил пытаюсь понять ее суть: «Ваш контент должен иметь ListView, атрибут id которого равен android.R.id.list».

Вот мой код:

public class ShowAllJobsInArea extends ListActivity{

    Context context;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_jobs_in_area);
        context=getApplicationContext();

        String area=Cookie.getAreaSelected();

        final ProgressBar thinger=(ProgressBar) findViewById(R.id.progressBar2);
        TabHost tabHost=(TabHost)findViewById(android.R.id.tabhost);
        tabHost.setup();

        TabSpec spec1=tabHost.newTabSpec("Tab 1");
        spec1.setContent(R.id.tab1);
        spec1.setIndicator("Starting");

        TabSpec spec2=tabHost.newTabSpec("Tab 2");
        spec2.setContent(R.id.tab2);
        spec2.setIndicator("# Days");        

        TabSpec spec3=tabHost.newTabSpec("Tab 3");
        spec3.setContent(R.id.tab3);
        spec3.setIndicator("Rate");


        tabHost.addTab(spec1);
        tabHost.addTab(spec2);
        tabHost.addTab(spec3);

        Handler handler = new Handler() {
             public void handleMessage(Message message) {
                  switch (message.what) {
                      case HttpConnection.DID_START:
                          thinger.setVisibility(View.VISIBLE);
                          break;
                      case HttpConnection.DID_SUCCEED:
                          String response = (String) message.obj;
                          Log.i("EOH",response);

                          ArrayList<String> startDates=new ArrayList<String>();
                          ArrayList<String> ns=new ArrayList<String>();
                          ArrayList<String> rates=new ArrayList<String>();
                          HashMap<String, JSONObject> countyObjs=new HashMap<String, JSONObject>();

                          JSONObject object = null;
                          try {
                              object = (JSONObject) new JSONTokener(response).nextValue();

                              for(int i=0;i<object.length();i++){
                                  String area="";
                                  String endDate="";
                                  String endTimes="";
                                  String id="";
                                  String startDate="";
                                  String startTimes="";
                                  String rate="";
                                  String alreadyApplied="";
                                  String n="";
                                  JSONObject countyObj=object.getJSONObject(String.valueOf(i));
                                  countyObjs.put(id, countyObj);

                                  area=countyObj.getString("area");
                                  endDate=countyObj.getString("endDate");
                                  endTimes=countyObj.getString("endTimes");
                                  id=countyObj.getString("id");
                                  startDate=countyObj.getString("startDate");
                                  startTimes=countyObj.getString("startTimes");
                                  rate=(countyObj.getString("rates").split(","))[0];
                                  alreadyApplied=countyObj.getString("alreadyApplied");
                                  n=countyObj.getString("n");

                                  startDates.add(startDate+","+id);
                                  ns.add(n+","+id);
                                  rates.add(rate+","+id);
                              }
                          }catch (JSONException e) {
                              e.printStackTrace();
                          }

                          Collections.sort(startDates);
                          Collections.sort(ns);
                          Collections.sort(rates);                    

                          String[] startDates_str = new String[startDates.size()];
                          startDates.toArray(startDates_str);

                          setListAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, startDates_str));
                          //setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
                          ListView lv = getListView();
                          lv.setTextFilterEnabled(true);



                          thinger.setVisibility(View.INVISIBLE);

                          break;
                      case HttpConnection.DID_ERROR:
                          thinger.setVisibility(View.INVISIBLE);
                          break;
                      default:
                          break;
                  }
             }
        };

        List<NameValuePair> params = new ArrayList<NameValuePair>(1);
        params.add(new BasicNameValuePair("area", area)); 
        new HttpConnection(handler).post("http://www.xlhi.com/ajax/getJobsInArea.php",params);
    }
}

show_jobs_in_area.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <TabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent">
        <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
            <TabWidget android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/tabs"></TabWidget>
            <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@android:id/tabcontent">
                <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tab1" android:orientation="vertical">
                    <ProgressBar android:id="@+id/progressBar2" android:layout_height="wrap_content" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="25dip"></ProgressBar>
                    <ListView android:id="@+id/listView1" android:layout_height="wrap_content" android:layout_width="match_parent"></ListView>
                </LinearLayout>
                <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tab2"></LinearLayout>
                    <ListView android:id="@+id/listView2" android:layout_height="wrap_content" android:layout_width="match_parent">
                </ListView>
                <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tab3">
                    <ListView android:id="@+id/listView3" android:layout_height="wrap_content" android:layout_width="match_parent"></ListView>
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</LinearLayout>

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

Я пытался изменить идентификатор на android.id="@android:id/list" безрезультатно - все равно получаю ту же ошибку. Я думал, что это как-то связано с асинхронным запросом, который я делаю... Сейчас я действительно застрял и надеюсь, что кто-то может помочь.

Спасибо заранее,


person Eamorr    schedule 11.07.2011    source источник


Ответы (2)


Если у вас есть более одного ListView в вашем макете, вы не должны расширять ListActivity, а скорее расширять Activity и обрабатывать ListViews самостоятельно;

ListView list1 = (ListView) findViewById(R.id.myList1);
list1.setAdapter(...);

ListView list2 = (ListView) findViewById(R.id.myList2);
list2.setAdapter(...);

ListActivity — это сокращенный вспомогательный класс, который упрощает жизнь, когда вы работаете только с одним ListView в макете.

person Karl-Bjørnar Øie    schedule 11.07.2011
comment
Да, кажется, это помогает! К сожалению, теперь я получаю исключение nullpointerexception ListView list1 = (ListView) findViewById(android.R.id.list); list1.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,startDates_str); - person Eamorr; 11.07.2011
comment
В вашем случае, возможно, это должны быть findViewById (android.R.id.listView1) и findViewById (android.R.id.listView2)? - person Karl-Bjørnar Øie; 11.07.2011
comment
Докопались до сути... ListView list1 = (ListView) findViewById(R.id.listView1);list1.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,startDates_str)); - person Eamorr; 11.07.2011
comment
Большое спасибо за эту подсказку! +1 - person Redfox; 29.11.2011
comment
Но как обновить эти адаптеры? Я использую myAdapter.notifyDataSetChanged(); но ничего не происходит! Помогите пожалуйста - person Leo; 11.08.2012
comment
@Leo, у вас могут быть проблемы с реализацией адаптера, если адаптер использует курсор, попробуйте отправить событие notifyChange курсора context.getContentResolver().notifyChange(SomeURI.CONTENT_URI, null) - person Karl-Bjørnar Øie; 14.08.2012

если вы используете getListView(); убедитесь, что идентификатором целевого списка является «список».

person user2814778    schedule 04.03.2014