0

我正在尝试实现一个简单的 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,我是否必须在处理时保存它响应?我需要使用内容提供者或数据库来提供这种行为吗?我真的很困惑,在此先感谢您的帮助!

4

3 回答 3

0

您的列表在适配器中:

private List<Cliente> clientes;

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

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

intent.putExtra(EXTRA_CUSTOMER_ID, customer_id);
于 2012-11-22T16:17:03.903 回答
0

获取单击的项目的位置,并从数组列表中获取该位置存在的对象,并使用它来获取所需的详细信息。

利用

@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()

    }
于 2012-11-22T16:15:31.113 回答
0

这里有关于如何将数据从一个活动传递到另一个活动的很好的例子,在活动之间传递对象。您可能想先看看这些链接上的解决方案。

请参阅下面的示例,该示例可以使您走上正轨。

列出适配器类:

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);
    }
});
于 2012-11-23T09:32:45.200 回答