Android:自定义ArrayAdapter无法显示文本

时间:2015-07-14 14:32:18

标签: android android-listview android-arrayadapter

我正在开发一个Android项目,我想创建一个CustomArray适配器,首先显示我从服务器获取的餐馆名称,当用户点击其中一个对象时,它的ID是在后端检索(未显示,在UI上没有任何内容)。目前,由于它不起作用,我遇到了一些问题。

注意的 请注意,我不是Android程序员,如果你帮助我,我会非常感激,但请尽量理解,我对Android概念并不熟悉,所以我可能不太清楚你想说的是什么可能会有一些后续评论。如果您有时间,请使用代码以简单的方式发布答案。对不起,但我有类似的问题,这不是一个很好的经验。谢谢。如果我很粗鲁,我很抱歉,但我觉得这很重要。

这是布局代码:

<?xml version="1.0" encoding="UTF-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</ListView>

这是RestRestaurant类:

public class RestRestaurant {

    private int restaurantId;

    private String restaurantName;
//getters and setters ommitted;
}

最后,这是活动代码:

public class RestaurantList extends ListActivity {

    String restaurantList = "http://192.168.178.60:8080/restaurant/listing";

    private ResponseEntity<RestRestaurant[]> responseEntity;

    private OrderAdapter m_adapter;

    private ArrayList<RestRestaurant> m_orders = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.restos);
        RestTemplate restTemplate = StaticRestTemplate.getRest();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
                requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
                HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                responseEntity= restTemplate.exchange(restaurantList, HttpMethod.GET,requestEntity,RestRestaurant[].class);
            }
        });
        thread.start();
        ProgressDialog progress = new ProgressDialog(this);
        progress.setTitle("Loading");
        progress.setMessage("Wait while loading...");
        while (thread.getState()!=Thread.State.TERMINATED){
            progress.show();
        }
        progress.dismiss();

        RestRestaurant[] restRestaurantList = responseEntity.getBody();

        m_orders = new ArrayList<RestRestaurant>();
        this.m_adapter = new OrderAdapter(this, android.R.layout.simple_list_item_1, m_orders);

        for (RestRestaurant restRestaurant1 : restRestaurantList){
            m_adapter.add(restRestaurant1);

        }

        setListAdapter(this.m_adapter);
    }


    private class OrderAdapter extends ArrayAdapter<RestRestaurant> {

        private ArrayList<RestRestaurant> items;

        public OrderAdapter(Context context, int textViewResourceId, ArrayList<RestRestaurant> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            RestRestaurant o = items.get(position);
            Log.d("Restaurant id is ",String.valueOf(o.getRestaurantId()));
            return v;
        }
    }

    @Override
    public void onBackPressed()
    {
        Intent intent = new Intent(RestaurantList.this, Login.class);
        StaticRestTemplate.jsessionid = null;
        StaticRestTemplate.replyString = null;
        startActivity(intent);
        finish();
    }
}

错误日志:

07-14 11:23:52.690    1534-1543/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)

请理解,我只想显示餐馆的名称,点击后,在活动课程中获取ID,我会自己处理剩下的东西。非常感谢。

更新

row.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">

</LinearLayout>

错误日志:

07-15 10:25:13.951    2666-2666/com.example.TestLunch E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.TestLunch, PID: 2666
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at com.example.TestLunch.Activity.RestaurantList$OrderAdapter.getView(RestaurantList.java:125)

发生在这里:

RestRestaurant item = getItem(position);
            if (item != null) {
// on below line
                holder.tvRestourantName.setText(item.getRestaurantName());
            }

1 个答案:

答案 0 :(得分:1)

错误意味着您已经打开了一些东西而没有关闭它。接口Closable提供了您应该调用的方法close(),以便释放不再需要的资源。

您可以查看here并检查您是否正在使用某个实现Closable的类

getView()的正确实现是:

public View getView(int position, View convertView, ViewGroup parent) { 
    View rowView = convertView;
    ViewHolder holder;

    if(rowView == null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);           
        rowView = inflater.inflate(R.layout.custom_row_layout, parent, false);
        holder = new ViewHolder(); 
        holder.tvRestourantName= (TextView) rowView.findViewById(R.id.restourant_name); // restourant_name is the ID of the view inside yout custom layout 

        rowView.setTag(holder); 
    }else{
        holder = (ViewHolder) rowView.getTag(); 
    }

    Contact item = getItem(position);
    if (item!= null) {
        holder.tvRestourantName.setText(item.getRestourantName());
    }

    return rowView;
}

static class ViewHolder { 
    TextView tvRestourantName; 
}

您需要在单独的XML文件中定义列表中行的布局。我把它命名为custom_row_layout.xml

然后在列表中设置点击监听器:

getListView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                  RestRestaurant item = (RestRestaurant)getListView().getAdapter().getItem(position);
                  int id = item.getRestaurantId(); // now you have the ID

            }
        });