Android: ошибка принудительного закрытия

1

Я писал приложение Android (простой список контактов) в соответствии с видеоуроком O'Really. Но меня остановила раздражающая ошибка, что я не в состоянии справиться сам. Пожалуйста помоги.

Текст ошибки в эмуляторе Android:

The application ContactList (process my.contactlist) had stopped unexpectedly. Please, try again

После отладки я обнаружил, что проблема возникает в ContactAdapter по строке

 ci = (ContactItem) View.inflate(context, R.layout.contact_item, null);

LogCat говорит:

12-19 12:19:30.727: ERROR/AndroidRuntime(522): FATAL EXCEPTION: main
        java.lang.ClassCastException: android.widget.LinearLayout
        at my.contactlist.ContactAdapter.getView(ContactAdapter.java:45)
        at android.widget.AbsListView.obtainView(AbsListView.java:1430)
        at android.widget.ListView.makeAndAddView(ListView.java:1745)
        at android.widget.ListView.fillDown(ListView.java:670)
        at android.widget.ListView.fillFromTop(ListView.java:727)
        at android.widget.ListView.layoutChildren(ListView.java:1598)
        at android.widget.AbsListView.onLayout(AbsListView.java:1260)
        at android.view.View.layout(View.java:7175)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
        at android.view.View.layout(View.java:7175)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
        at android.view.View.layout(View.java:7175)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1047)
        at android.view.View.layout(View.java:7175)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
        at android.view.View.layout(View.java:7175)
        at android.view.ViewRoot.performTraversals(ViewRoot.java:1140)
        at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:3683)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:507)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
        at dalvik.system.NativeStart.main(Native Method)

Код основных классов и макетов:

public class MainActivity extends ListActivity {

    private ContactApp app;
    private ContactAdapter adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        setUpViews();
        app = (ContactApp) getApplication();
        app.getContacts().add(new Contact("AAA", "BBB", "CCC"));
        adapter = new ContactAdapter(this,  app.getContacts());
        setListAdapter(adapter);
        Toast.makeText(this, "count="+adapter.getCount(), Toast.LENGTH_SHORT).show();
    }

    private void setUpViews() {
        Button addButton = (Button) findViewById(R.id.newContact);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
                startActivity(intent);


              }
            });
        }

        @Override
        protected void onResume() {
           super.onResume();
           // adapter.notifyDataSetChanged();
        }
    }

ContactAdapter.java:

public class ContactAdapter extends BaseAdapter {

    private ArrayList<Contact> contacts;
    private Context context;

    public ContactAdapter(Context context, ArrayList<Contact> contacts) {
        super();
        this.contacts = contacts;
        this.context = context;
    }

    @Override
    public int getCount() {
        return contacts.size();
    }

    @Override
    public Contact getItem(int i) {
        return (contacts == null) ? null : contacts.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
       ContactItem ci;
      if (view == null) {
          ci = (ContactItem) View.inflate(context, R.layout.contact_item, null);
      } else {
          ci = (ContactItem)view;
      }

       ci.setContact(contacts.get(i));
       return ci;
    }

    public void forceReload() {
         notifyDataSetChanged();
    }
}

Contact.java:

public class Contact {

    private String lastname;
    private String name;
    private String phoneNumber;

    public Contact(String lastname, String name, String phoneNumber) {
        this.lastname = lastname;
        this.name = name;
        this.phoneNumber = phoneNumber;
    }


    public String getLastname() {
        return lastname;
    }

    public String getName() {
        return name;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

contact_item.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="horizontal">

    <ImageView
            android:id="@+id/img"
            android:src="@drawable/person"
            android:layout_width="24px"
            android:layout_height="24px"
            android:layout_marginLeft="2px"
            android:layout_marginRight="5px"
            android:layout_marginTop="5px"
            />

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:orientation="vertical">
        <TextView
                android:id="@+id/show_name"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:textSize="12px"
                android:textColor="#AAAAFF"

                />
        <TextView
                android:id="@+id/show_phone"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:textSize="12px"
                android:textColor="#AAAAFF"


                />
    </LinearLayout>

</LinearLayout>

ContactItem.java

public class ContactItem extends LinearLayout {

   // private Contact contact;
    private TextView name;
    private TextView phone;


    public ContactItem(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();    
        name = (TextView) findViewById(R.id.show_name);
        phone = (TextView) findViewById(R.id.show_phone);
    }

    public void setContact(Contact contact) {
        //this.contact = contact;
        name.setText(contact.getLastname());//+" "+contact.getName());
        phone.setText(contact.getPhoneNumber());
    }
}

Какие-либо предложения?

Теги:

1 ответ

5
Лучший ответ

Макет, который вы надуваете, - это LinearLayout. Вы не можете наложить LinearLayout на ContactItem, но вы можете отнести ContactItem к LinearLayout. Поскольку вы определили ContactItem, почему бы вам не изменить корень вашего макета на ContactItem?

  • 0
    Спасибо за совет! Теперь все отлично работает!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню