0

I'm trying to implement a simple android REST Client and i having some problems understanding how to pass data between my activities.

I have this ListActivity (I'm using the Spring REST Template) :

    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);
        }

    } 

}

And this is My 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;
    }

}

This the POJO class of the data iḿ getting :

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;
    }
}

When i select an element from the listView i would like show details specific about this element on another activity or fragment, but i don't know how to obtain the customer_id of this element from the list, do i have to save it when i procesing the response? do I need to use content provider or database provide this behavior? i'm really confused, thanks in advance for any help!

Henry1988
  • 83
  • 1
  • 1
  • 8
  • Have you tried with "putExtra()" on the Intent? You may want to take a look here: http://stackoverflow.com/questions/3848148/sending-information-with-intent-putextra and here: http://stackoverflow.com/questions/2736389/how-to-pass-object-from-one-activity-to-another-in-android – Radu Dan Nov 22 '12 at 16:14
  • why you commented the setContentView() ?? – Houcine Nov 22 '12 at 16:31
  • Hey @Houcine there's no specific reason, i was trying something, but it works this way. Also with the setContentView but the layout has to have an list with an espefic id android:id/list – Henry1988 Nov 22 '12 at 19:00
  • Hi @Radu i have not tried that. i will , thanks for the links. – Henry1988 Nov 22 '12 at 19:09

3 Answers3

0

get the position of the item clicked and get the object present at that position from the arraylist and use it to get the required details.

use

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

    }
G_S
  • 7,068
  • 2
  • 21
  • 51
0

Your list is in the adapter:

private List<Cliente> clientes;

In onListItemClick, you can get the Cliente from this list using the position parameter.

You pass information to another activity when you call startActivity, passing it an Intent. The Intent may have additional information, in your case you could set the customer_id as an int extra, something like:

intent.putExtra(EXTRA_CUSTOMER_ID, customer_id);
Sofi Software LLC
  • 3,879
  • 1
  • 36
  • 34
0

There are good examples on how to pass data from one activity to another here, pass objects between activities. You may want to take a look first to the solutions on those links.

Please see below an example that can put you on the right track.

List adapter class:

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;
    }

}

You see that we used a ViewHolder class for memory management. This is a good practice for holding view elements inside your list adapter. You can find more info about list views, explained by Romain Guy - The World of ListViews.

From your MainActivity allocate the adapter and get your item on click:

//---- 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);
}

Another example is with implementing an interface in the adapter like this:

//--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--//

And from your MainActivity start the second activity like this:

adapter.setOnSaveEditsListener(new OnSaveEditsListener() {

    @Override
    public void onSaveEdits() {
        //Start activity from here
        //--code--//
        startActivity(intent);
    }
});
Community
  • 1
  • 1
Radu Dan
  • 453
  • 4
  • 22