ListView with ArrayAdapter,当我点击一行时出现异常

时间:2012-07-23 09:23:25

标签: android listview android-arrayadapter

我正在使用ArrayAdapter创建一个listView。每个视图包含4个TextView和一个ImageButton。当我点击一行时,它会在表格中显示数据,如果我点击行中的imageButton,它会将用户发送到另一个活动。

我的问题是:当我滚动列表并单击一个imageButton(在开始时不在列表的可见部分)我有一个例外

07-23 11:07:50.150: E/AndroidRuntime(9326): FATAL EXCEPTION: main
07-23 11:07:50.150: E/AndroidRuntime(9326): java.lang.IllegalStateException: Could not execute method of the activity
07-23 11:07:50.150: E/AndroidRuntime(9326):     atandroid.view.View$1.onClick(View.java:2700)
07-23 11:07:50.150: E/AndroidRuntime(9326):at ndroid.view.View.performClick(View.java:3127)
07-23 11:07:50.150: E/AndroidRuntime(9326): at android.view.View$PerformClick.run(View.java:12025)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at android.os.Handler.handleCallback(Handler.java:587)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at android.os.Looper.loop(Looper.java:132)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at android.app.ActivityThread.main(ActivityThread.java:4126)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at java.lang.reflect.Method.invokeNative(Native Method)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at java.lang.reflect.Method.invoke(Method.java:491)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at dalvik.system.NativeStart.main(Native Method)
07-23 11:07:50.150: E/AndroidRuntime(9326): Caused by: java.lang.reflect.InvocationTargetException
07-23 11:07:50.150: E/AndroidRuntime(9326):     at java.lang.reflect.Method.invokeNative(Native Method)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at java.lang.reflect.Method.invoke(Method.java:491)
07-23 11:07:50.150: E/AndroidRuntime(9326):     at android.view.View$1.onClick(View.java:2695)
07-23 11:07:50.150: E/AndroidRuntime(9326):     ... 11 more
07-23 11:07:50.150: E/AndroidRuntime(9326): Caused by: java.lang.NullPointerException
07-23 11:07:50.150: E/AndroidRuntime(9326):     at com.android.androidlistview.MainActivity.MyHandler(MainActivity.java:48)

这是我的代码:

MainActivity:

public class MainActivity extends ListActivity {

private ListView listView;

private String id;
private static final int REQUEST_CODE = 1;
private AccountNameListAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<Account> accountData = new ArrayList<Account>();
    for (int i = 0; i < 50; i++) {
        Account account = new Account("n" + i, "test", "0154654654",
                "gdfg", "gfdg", "2635454564");
        accountData.add(account);
    }

    adapter = new AccountNameListAdapter(this, R.layout.list_detail,
            accountData);

    listView = this.getListView();
    listView.setAdapter(adapter);

}

public void MyHandler(View v) {
    ImageButton cb = (ImageButton) v;

    int position = Integer.parseInt(cb.getTag().toString());


    View o = listView.getChildAt(position).findViewById(R.id.blocCheck);

    TextView t = (TextView) listView.getChildAt(position).findViewById(
            R.id.id);
    Toast.makeText(getApplicationContext(), t.getText(), Toast.LENGTH_LONG)
            .show();

    Intent editIntent = new Intent(MainActivity.this, EditActivity.class);
    editIntent.putExtra("accountId", t.getText());
    startActivityForResult(editIntent, REQUEST_CODE);

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {

        final Account account = new Account("424242", "RhfghOCK", "0154654654",
                "ghfgh", "hgfh", "2635454564");

        adapter.add(account);
        adapter.notifyDataSetChanged();

    }

}

}

第48行对应于:

View o = listView.getChildAt(position).findViewById(R.id.blocCheck);

我的自定义广告:

public class AccountNameListAdapter extends ArrayAdapter<Account> {


    private Context context;
    private int layoutResourceId;   
    private ArrayList<Account> data;
    private TableLayout table;
    private TextView tableName;
    private TextView tableId;



    public AccountNameListAdapter(Context context, int layoutResourceId, ArrayList<Account> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
        table = (TableLayout) ((Activity) context).findViewById(R.id.tableLayout);
        tableName = (TextView) ((Activity) context).findViewById(R.id.NameText);
        tableId = (TextView) ((Activity) context).findViewById(R.id.idText);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {           

        AccountHolder holder = null;

        if(convertView == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            convertView = inflater.inflate(layoutResourceId, parent, false);

            holder = new AccountHolder();

            convertView.setClickable(true);
            convertView.setFocusable(true);

            convertView.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    new AlertDialog.Builder(context).setTitle("touched").show();                   
                    table.setVisibility(0);
                    tableName.setText("ok name");
                    tableId.setText("ok "+ data.get(position).getAccountId());                      
                }

            });


            holder.txtName = (TextView)convertView.findViewById(R.id.nom);
            holder.txtId = (TextView)convertView.findViewById(R.id.id);

            convertView.setTag(holder);


        }
                   else{
        holder = (AccountHolder)convertView.getTag();
        }

        holder.txtName.setText(data.get(position).getName());
        holder.txtId.setText(data.get(position).getAccountId());


        ImageButton img = (ImageButton) convertView.findViewById (R.id.check);  
        img.setTag (position);
        });


        return convertView;
    }

    static class AccountHolder
    {
        TextView txtName;
        TextView txtId;
    }


}

list_detail.xml:

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


<TableLayout android:id="@+id/blocCheck" 
    android:background="#EEF9F8"
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp">


    <TableRow android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:paddingLeft="4sp"
        android:paddingBottom="4sp">
        <LinearLayout
            android:orientation="horizontal" 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:paddingLeft="20sp"
            android:layout_weight="1" 
            android:gravity="center"
            >

            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" 
                android:textSize="20sp"
                android:text="Name : " 
                android:layout_gravity="left"
                android:layout_marginRight="5sp" />
            <TextView android:id="@+id/nom" 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" 
                android:textSize="20sp"
                android:layout_gravity="left" />
        </LinearLayout>
    </TableRow>


    <TableRow android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:paddingLeft="4sp"
        android:baselineAligned="true">
        <LinearLayout
            android:orientation="horizontal" 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:paddingLeft="20sp"
            android:layout_weight="1" 
            android:gravity="center">
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" 
                android:textSize="20sp"
                android:text="Id : " 
                android:layout_gravity="left"
                android:layout_marginRight="5sp" />
            <TextView android:id="@+id/id" 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" 
                android:textSize="20sp"
                android:layout_gravity="left" />
        </LinearLayout>
        <ImageButton android:layout_height="wrap_content" 
            android:id="@+id/check"
            android:layout_width="wrap_content" 
            android:background="@drawable/edit"
            android:layout_gravity="right"
            android:layout_marginRight="10sp" 
            android:onClick="MyHandler"/>
    </TableRow>
</TableLayout>

2 个答案:

答案 0 :(得分:0)

只有当位置对应于屏幕上的可见子项时,方法getChildAt才会为ListView返回有效的Viewnull静止)。提供给该方法的整数必须位于ListView.getLastVisiblePosition() - ListView.getFirstVisiblePosition()定义的区间内。

尝试从position中减去getFirstVisiblePosition()的值:

View o = listView.getChildAt(position - listView.getFirstVisiblePosition()).findViewById(R.id.blocCheck);

答案 1 :(得分:0)

尝试设置自定义列表Linearlayout ID并基于该点击事件调用....

这是ListAdapter的调用

lv.setAdapter(new Listadapter(getApplicationContext(), R.id.listView1, list));

这是ListAdapter类....

public class Listadapter extends ArrayAdapter<BinForBlog>
        {
            ArrayList<BinForBlog> mList = new ArrayList<BinForBlog>();
            public Listadapter(Context context, int textViewResourceId,ArrayList<BinForBlog> list) 
            {
                super(context, textViewResourceId, list);
                this.mList = list;


            }
            @Override
            public View getView(int position, View convertView, ViewGroup parent) 
            {

                View v = convertView;

                if(v==null)
                {
                    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v=li.inflate(R.layout.custom_blog, null);

                }

                TextView Title = (TextView) v.findViewById(R.id.blog_title);
                TextView Date = (TextView) v.findViewById(R.id.blog_date);
                TextView Desc = (TextView) v.findViewById(R.id.blog_desc);
                LinearLayout content = (LinearLayout) v.findViewById(R.id.lnrblog);


                final BinForBlog listitem = mList.get(position);

                // For Underline
                SpannableString text = new SpannableString(listitem.getTitle());
                text.setSpan(new UnderlineSpan(), 0, text.length(), 0);

                Title.setText(text);
                Date.setText(listitem.getDate());
                Desc.setText(listitem.getDesc());


                content.setOnClickListener(new OnClickListener()
                {

                    public void onClick(View arg0) 
                    {

                        Intent i = new Intent(getApplicationContext(),show_blog_web.class);
                        i.putExtra("link1", listitem.getLink());
                        startActivity(i);


                    }
                });


                return v;
            }


        }