Christine
Christine

Reputation: 514

Implement OnClickListener to the ListView Items

I have sucessfully got the data from my server and displayed it in my ListView and now i want to implement Click event in the ListView Items. For now i am displaying the "id" and "SomeText" in my List view.

My Question is How to implement a Click event in the ListView in such a way that if i click one particular row, it would display the "id" from the server(not from the actual array which starts from "0") in the toast message.

Below is the Code and screen shot of what i am getting when the list items are being clicked.

I hope someone could help me out with this one; any link or a snippet of code would be very helpful.

Thank you soo much. Christine

SCREENSHOT enter image description here

CODE public class Welcome extends Activity {

public static String token;
String nam;
String dat;
String name;
JSONArray tasks;
long id2;
TextView textView;

ListView lvList;
private ArrayAdapter<String>mListData;
String emailAdd = "[email protected]";

@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.welcome);
    //======================================================================================================
    //======================== GETTING THE VALUE FROM THE SHARED PREF ======================================

    SharedPreferences sharedpreferences = getSharedPreferences(Login.MyPREFERENCES, Context.MODE_PRIVATE);
    token = sharedpreferences.getString("tokenKey","");
    //Log.e("TOKEN", token);

    //======================================================================================================
    //=====================================================================================================
    lvList = (ListView) findViewById(R.id.chat_drawer);
    textView = (TextView) findViewById(R.layout.msg_chat);

    mListData = new ArrayAdapter<String>(this, R.layout.msg_chat);
    lvList.setAdapter(mListData);
    mListData.setNotifyOnChange(true);

    historyMessage();
}

private void historyMessage() {
    // TODO Auto-generated method stub

    new Thread(new Runnable(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try{
                HttpClient client = new DefaultHttpClient();
                String SetServerString = "";
                HttpGet httpget = new HttpGet("http://xxxx.xxx.com/api/v1/agent-tasks?token="+token);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                SetServerString = client.execute(httpget, responseHandler);
                //Log.e("LIST vIEW ", SetServerString);
                HttpResponse mike = client.execute(httpget);
                HttpEntity entit = mike.getEntity();
                dat = EntityUtils.toString(entit);
                //Log.e("STRING From ", dat);

                try{
                    JSONObject responseObject = new JSONObject(SetServerString);
                    JSONArray responseArray = responseObject.getJSONArray("response");
                    JSONObject firstResponse = responseArray.getJSONObject(0);
                    tasks = firstResponse.getJSONArray("tasks");
                    //System.out.println("asdfasdfsadf" + tasks);

                        runOnUiThread(new Runnable(){

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                for(int i = 0; i < tasks.length(); i++){
                                    try{
                                    JSONObject task = tasks.getJSONObject(i);

                                    id2 = task.getInt("id");
                                    name = task.getString("name");
                                    String fulldata = id2 + "." + " " + name;

                                mListData.add(fulldata);


                                //mListData.notifyDataSetChanged();
                                ListView lvList = (ListView) findViewById(R.id.chat_drawer);
                                lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {


                                    public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
                                            long id2) {
                                        // TODO Auto-generated method stub

                                        TextView textView = (TextView) viewClicked;
                                        String message = "you clicked #"+id2+" "+ ",which is string:"+ " " +textView.getText().toString();
                                        Toast.makeText(Welcome.this, message, Toast.LENGTH_LONG).show();

                                    }


                                });
                                    }
                                    catch (JSONException e){
                                        e.printStackTrace();
                                    }
                            }
                            }


                        });
                } catch (JSONException e){
                    e.printStackTrace();
                }
            }catch (ClientProtocolException e){
                Log.d("HTTPCLIENT", e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d("HTTPCLIENT", e.getLocalizedMessage());
            }


        }

    }).start();
}

Upvotes: 1

Views: 418

Answers (2)

inmyth
inmyth

Reputation: 9070

I would say the main reason you cannot get other information than the String name is because there is no other information than the String name in the adapter's list. So you would need to have a suitable data model and adapter that corresponds to this model. It is perfectly fine to use ArrayAdapter. The snippet would go like this:

class Data {
  String name;
  int id;

  public Data(String name, int id){
      this.name = name;
      this.id = id;
  }
}

class ViewHolder {
    TextView msg;

    public ViewHolder(View convertView){
       msg = (TextView)findViewById(R.id.msgid);//appropriate text view element
                                               // from R.layout.msg_chat
    }

}

class MyAdapter extends ArrayAdapter<Data>{
    public MyAdapter(Context context) {
        super(context, R.layout.msg_chat);
    }

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

      if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.msg_chat, parent, false);

        ViewHolder viewHolder = new ViewHolder(convertView);
        rowView.setTag(viewHolder);
      }

      ViewHolder holder = (ViewHolder) rowView.getTag();
      Data data = getItem(position);
      holder.msg.setText("The id is" + data.id);
      return convertView;           
    }  
}

Instantiate it:

 private MyAdapter mListData;
 ...
 mListData = new MyAdapter(this);

And add the data to adapter like this:

mListData.add(new Data(name, id2));

Upvotes: 1

letz
letz

Reputation: 1792

You should implement a custom base adapter See where how. to bind each element (id and name) to an list view row, instead of a simple ArrayAdapter.

I would also recommend to wrap the response from your server in a java object:

public class AgentTask {
    private int id;
    private String name;

  // getters and setters
}

An then when your onItemClick method is called you will have an instance of AgentTask instead of a simple string.

Hope it helps

Upvotes: 1

Related Questions