从ListView中选择项目(Json数据)

时间:2012-11-22 16:04:48

标签: android json rest listview listactivity

我正在尝试实现一个简单的Android REST客户端,并且我在理解如何在我的活动之间传递数据时遇到一些问题。

我有这个ListActivity(我正在使用Spring REST模板):

    public class MainActivity extends ListActivity
{
    protected static final String TAG = MainActivity.class.getSimpleName();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeText(this, "You have selected" + position + id ,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {

        super.onStart();
        new DownloadClientesTask().execute();
    }

    private void refreshClientes(List<Cliente> clientes) {
        if (clientes == null) {
            return;
        }

        ClientesListAdapter adapter = new ClientesListAdapter(this, clientes);
        setListAdapter(adapter);
    }

    private class DownloadClientesTask extends AsyncTask<Void, Void, List<Cliente>> {

        @Override
        protected List<Cliente> doInBackground(Void... params) {
            final String url = "http://192.168.1.119/~henry/api_slim/index.php/customers";

            try {
                // Set the Accept header for "application/json"
                HttpHeaders requestHeaders = new HttpHeaders();
                List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
                acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
                requestHeaders.setAccept(acceptableMediaTypes);

                // Populate the headers in an HttpEntity object to use for the request
                HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

                // Create a new RestTemplate instance
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

                // Perform the HTTP GET request
                ResponseEntity<Cliente[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
                        Cliente[].class);

                // convert the array to a list and return it
                return Arrays.asList(responseEntity.getBody());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.e(TAG, e.getMessage(), e);
            }

            return null;

        }

        @Override
        protected void onPostExecute(List<Cliente> result) {

            refreshClientes(result);
        }

    } 

}

这是我的listAdapter:

public class ClientesListAdapter extends BaseAdapter{

    private List<Cliente> clientes;
    private final LayoutInflater layoutInflater;

    public ClientesListAdapter(Context context, List<Cliente> clientes) {
        this.clientes = clientes;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return this.clientes != null ? clientes.size() : 0;
    }

    @Override
    public Cliente getItem(int position) {
        return this.clientes.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = this.layoutInflater.inflate(R.layout.cliente_list_item, parent, false);
        }

        Cliente cliente = getItem(position);
        if (cliente != null) {
            TextView t = (TextView) convertView.findViewById(R.id.name);
            t.setText(cliente.getFirstname());
        }

        return convertView;
    }

}

这是数据的POJO类:

public class Cliente {
    private Integer id_customer; 
        private String firstname;
        public Integer getId_customer() {
        return id_customer;
    }
    public void setId_customer(Integer id_customer) {
        this.id_customer = id_customer;
    }
        public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
}

当我从listView中选择一个元素时,我希望在另一个活动或片段上显示有关此元素的详细信息,但我不知道如何从列表中获取此元素的customer_id,我是否必须保存它当我处理回应?我是否需要使用内容提供程序或数据库提供此行为?我真的很困惑,提前感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

获取项目的位置,并从arraylist获取该位置的对象并使用它来获取所需的详细信息。

使用

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeText(this, "You have selected" + position + id ,
                Toast.LENGTH_SHORT).show();
      // use  this.clientes.get(position) and pass it to the next activity or fragment  using putextras to where you need to pass and display this in the destination end using the same object by getting it using getExtra()

    }

答案 1 :(得分:0)

您的列表位于适配器中:

private List<Cliente> clientes;

在onListItemClick中,您可以使用position参数从此列表中获取Cliente。

当您调用startActivity时,将信息传递给另一个活动,并将其传递给Intent。 Intent可能有其他信息,在您的情况下,您可以将customer_id设置为int extra,如:

intent.putExtra(EXTRA_CUSTOMER_ID, customer_id);

答案 2 :(得分:0)

有很多关于如何将数据从一个活动传递到另一个活动herepass objects between activities的示例。您可能希望首先查看这些链接上的解决方案。

请参阅下面的一个示例,它可以让您走上正确的轨道。

列出适配器类:

public class ClientesListAdapter extends BaseAdapter{

    //private members
    private List<Cliente> clientes;

    //adapter position - not used for this example
    public int adapterPosition;

    //context of app
    private Context mContext;

    //default constructor
    public ClientesListAdapter(Context context, List<Cliente> clientes) {

        //context pointer
        this.mContext = context;

        //alloc
        this.clientes = new ArrayList<Cliente>(clientes.size());
        this.clientes.addAll(clients);
    }

    //Holder for events and dates (memory management)
    public static class ViewHolder{
        TextView myTextView;//this is actually findViewById(R.id.name) @see getView() method
    }

    //generated method
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return this.clientes != null ? clientes.size() : 0;
    }

    //generated method
    @Override
    public Cliente getItem(int position) {
        return this.clientes.get(position);
    }

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

    //get client's id
    public int getClienteId(int position){
        return this.clientes.get(position).getClienteId();
    }

    //get client's id without passing the position
    public int getClienteId(){
        return this.clientes.get(adapterPosition).getClienteId();
    }

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

        //row is actually convertView (the current view)
        View row = convertView;
        //holds our view elements
        ViewHolder holder;

        //if row is null 
        if(row == null){
            //inflate layout to get our view elements
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(com.yourapp.R.layout.my_layout, parent, false);//your layout here, modify code
            //set up the holder
            holder = new ViewHolder();
            holder.myTextView = (TextView) row.findViewById(com.yourapp.R.id.name);

            //give the row a tag (holder)
            row.setTag(holder);

        }else{
            //row is not null we can see it (no need to allocate memory)
            holder = (ViewHolder) row.getTag();
        }

        //get your cliente object
        Cliente cliente = this.clientes.get(position);
        if (cliente != null) {
            holder.myTextView.setText(cliente.getFirstname());
        }

        //copy position
        adapterPostion = position;

        return convertView;
    }

}

您看到我们使用ViewHolder类进行内存管理。这是在列表适配器中保存视图元素的一种很好的做法。您可以找到有关列表视图的更多信息,由Romain Guy - The World of ListViews解释。

从您的MainActivity中分配适配器并点击以获取您的项目:

//---- code --- //
ListView myListView = (ListView)findViewById(R.id.mylistview);//or you may use ListActivity
ClientesListAdapter adapter = new ClientesListAdapter(this, clientes);//"this" or "getApplicationContext()"
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();//notify
// ---- code --- //
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Toast.makeText(this, "You have selected" + position + id ,
            Toast.LENGTH_SHORT).show();

    Intent intent = new Intent(MyActivity.this, ActivityB.class);
    intent.putInt("cliente_id",adapter.getClienteId());
    startActivity(intent);
}

另一个例子是在适配器中实现一个接口,如下所示:

//--code//
//Interface method
private OnSaveEditsListener saveEditsListener = null;
public void setOnSaveEditsListener(OnSaveEditsListener l) {
    saveEditsListener = l;
}
//--code//

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

        //--code--//

        //get clicked position of calendar (get clicked day)
        convertView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                v.requestFocusFromTouch();
                currentAgendaPosition = position;
                try{
                    saveEditsListener.onSaveEdits();
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        });

        //returns current row
        return row;
    }
    //--code--//

从你的MainActivity开始第二个活动:

adapter.setOnSaveEditsListener(new OnSaveEditsListener() {

    @Override
    public void onSaveEdits() {
        //Start activity from here
        //--code--//
        startActivity(intent);
    }
});