如何设置列表视图使用自定义适配器?自定义适配器如何在下面给出的代码中工作?

时间:2015-01-16 06:38:11

标签: android android-listview custom-adapter jsonobject

我尝试了各种方法。我在列表中的每一行使用文本视图和一个按钮。当我运行代码时,我得到 null pointerexception 。是否有必要在此使用视图持有者例子?我还在一个例子中添加了视图并试过但运气不好。检查下面的代码。

 adapter1= new custadapter(this, R.layout.lisarrange, todisplay);
 listview.setAdapter(adapter1);

custadapter.java

public class custadapter extends ArrayAdapter<JSONObject> {

Itemdatabase database;
String idstring;

private int layoutResourceId;
private Context context;
ArrayList<JSONObject> list;


public custadapter(Context context, int layoutResourceId, ArrayList<JSONObject> _list) {
    super(context, layoutResourceId,_list);

    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.list = _list;

}


@Override
public int getCount() {
    // TODO Auto-generated method stub
    return list.size();
}


@Override
public JSONObject getItem(int position) {
    // TODO Auto-generated method stub
    return list.get(position);
}


@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}


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

    View row= convertView;
     LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    //row = inflater.inflate(layoutResourceId, parent, false);

    if (convertView == null){
        row = inflater.inflate(R.layout.lisarrange, parent, false);
              }
    TextView titlerow = (TextView) row.findViewById(R.id.txttitleview);

    Button btnrow = (Button) row.findViewById(R.id.btndel);


    try {
        titlerow.setText(list.get(position).getString("name"));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    btnrow.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            try {
                idstring = list.get(position).getString("id");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int id1=Integer.valueOf(idstring);
            database.deleteContact(id1);
        }
    });

    return row;
}




}

我试过的另一个代码是

扩展Baseadapter的bseadapter.java

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



    ViewHolder holder;
    if(convertView == null) {
        convertView = LayoutInflater.from(a).inflate(R.layout.lisarrange, null);
        holder = new ViewHolder();

        holder.titlerow = (TextView) convertView.findViewById(R.id.txttitleview);
        holder.btnrow=(Button) convertView.findViewById(R.id.btndel);
        convertView.setTag(holder);

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

    JSONObject listtemp = list.get(position);

    try {
        holder.titlerow.setText(listtemp.getString("name"));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    holder.btnrow.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            try {
                idstring = list.get(position).getString("id");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

    int id1=Integer.valueOf(idstring);
    database.deleteContact(id1);

    return convertView;



}

private static class ViewHolder{
    TextView titlerow;
    Button btnrow;
}

}

logcat的

01-16 12:12:38.005: E/AndroidRuntime(27502): FATAL EXCEPTION: main
01-16 12:12:38.005: E/AndroidRuntime(27502): java.lang.NullPointerException
01-16 12:12:38.005: E/AndroidRuntime(27502):    at com.examplenotetest.bseadapter.getView(bseadapter.java:75)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.widget.AbsListView.obtainView(AbsListView.java:2627)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.widget.ListView.measureHeightOfChildren(ListView.java:1259)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.widget.ListView.onMeasure(ListView.java:1171)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.View.measure(View.java:16831)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.View.measure(View.java:16831)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.View.measure(View.java:16831)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.View.measure(View.java:16831)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2586)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.View.measure(View.java:16831)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2189)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1352)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1535)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6364)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.Choreographer.doCallbacks(Choreographer.java:591)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.Choreographer.doFrame(Choreographer.java:561)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.os.Handler.handleCallback(Handler.java:730)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.os.Looper.loop(Looper.java:137)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at android.app.ActivityThread.main(ActivityThread.java:5419)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at java.lang.reflect.Method.invokeNative(Native Method)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at java.lang.reflect.Method.invoke(Method.java:525)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
01-16 12:12:38.005: E/AndroidRuntime(27502):    at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

好的,首先要确保你正在查看抛出异常的类,根据logcat这是 bseadapter.java

其次,如果在onClickListener中为变量 idstring 赋值,则必须将其声明为final。这同样适用于您在侦听器内部使用的位置。您可能想重新考虑单击流程的方式,因为它在那里不起作用。

第三,替换以下行

JSONObject listtemp = (JSONObject)list.get(position); //this isn't wrong per se, but use the functions thats intended for this pupose

JSONObject listtemp = getItem(position);

然后在执行任何其他代码之前检查listtemp是否为null。将其余代码包装在if语句中:

if(listtemp != null){
   //do all your stuff here
}

第四,你在哪里

listtemp.getString("name")

您必须首先检查列表是否为空(因此前面提到的 if(listtemp!= null))。然后,您无法假设 listtemp 具有属性名称。所以总是使用

optString("name") 

而不是

getString("name")

有关详细信息,请查看JsonObject文档 optString()

最后确保 Itemdatabase数据库已初始化

答案 1 :(得分:0)

这里使用的是ArrayAdapter类,因此在处理数据数组时不需要覆盖getCount()和getItem()等方法。

只需要只覆盖一个方法,即getView()并执行所有操作。

供您参考,请尝试以下代码:

BusinessOwnerArrayAdapter boaa = new BusinessOwnerArrayAdapter(getApplicationContext(), m_ArrayList, this);
            lv = (ListView) findViewById(R.id.business_owner_list);
            lv.setAdapter(boaa);

以上m_ArrayList是arraylist。

boaa是ArrayAdapter类

lv是您的列表视图。

现在你的ArrayAdapter类看起来像这样..

/**
 * @author VIVEK
 * All Product Info list array adapter class.
 */
public class ClaimSummaryArrayAdapter extends ArrayAdapter<ClaimSummaryModel> {

    private final Context context;
    private final ArrayList<ClaimSummaryModel> values;
    ImageLoader imgLoader;
    String _activityString;
    ClaimsSummaryFragment ubf;
    CommonMethodStuff cms;

    public ClaimSummaryArrayAdapter(Context context,
            ArrayList<ClaimSummaryModel> values, ClaimsSummaryFragment ubf) {
        super(context, R.layout.claim_summary_row, values);
        this.context = context;
        this.values = values;
        imgLoader = new ImageLoader(context);
        cms = new CommonMethodStuff();
        this.ubf = ubf;
    }

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

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.claim_summary_row, parent, false);

        final ClaimSummaryModel model = values.get(position);

        Typeface font = Typeface.createFromAsset(context.getAssets(), "OpenSans-Regular.ttf" );
        Typeface font1 = Typeface.createFromAsset(context.getAssets(), "OpenSans-Semibold.ttf" );

        TextView promotion_name = (TextView) rowView.findViewById(R.id.promotion_name_claim);
        promotion_name.setTypeface(font1);
        if(model.promotion_name.equalsIgnoreCase(""))
            promotion_name.setText("");
        else
            promotion_name.setText(cms.toTheUpperCaseSingle(model.promotion_name));

        TextView product_name = (TextView) rowView.findViewById(R.id.product_name);
        //product_name.setTypeface(font);
        if(model.product_name.equalsIgnoreCase(""))
            product_name.setText("");
        else
            product_name.setText(cms.toTheUpperCaseSingle(model.product_name));


        TextView serial_number = (TextView) rowView.findViewById(R.id.serial_number);
        serial_number.setTypeface(font);
        serial_number.setText(model.serial_number);

        return rowView;
    }

希望这能澄清您的需求。如果有任何疑问,请告诉我。 干杯!

答案 2 :(得分:0)

@Override

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

ViewHolder holder;
if(convertView == null) {
    convertView = LayoutInflater.from(a).inflate(R.layout.lisarrange, null);
    holder = new ViewHolder();

    holder.titlerow = (TextView) convertView.findViewById(R.id.txttitleview);
    holder.btnrow=(Button) convertView.findViewById(R.id.btndel);
    convertView.setTag(holder);

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

JSONObject listtemp = list.get(position);

try {
    holder.titlerow.setText(listtemp.getString("name"));
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

holder.btnrow.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        try {
            idstring = list.get(position).getString("id");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
});

int id1=**Integer.valueOf(idstring);***emphasized text*
database.deleteContact(id1);

return convertView;

}

第一次当列表视图被Integer.valueOf(idstring)中的适配器填充时;声明idstring将为null,因此它给你NullPointerException。