使用自定义列表视图

时间:2016-06-26 04:59:59

标签: android listview

在我的android项目中我使用自定义列表视图,其中从服务器检索所有值并显示在列表视图中。我在listview条目中有一个按钮和textview,现在我希望按钮的功能就像我点击它时将获取同一组的任何textview中的值并将其显示在警告框中。我检索了数据并成功显示但我无法破解如何使用该按钮获取列表的textview值..提前感谢您的任何帮助...我的代码发布在下面。

这是我的联系适配器类:

package com.example.sohan.doctor;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sohan on 6/9/2016.
 */
public class ContactAdapter extends ArrayAdapter {
    notification nt = new notification();
    List list = new ArrayList();
    View row;
    ContactHolder contactHolder;
    public ContactAdapter(Context context, int resource) {
        super(context, resource);
    }


    public void add(List<Contacts> updatedList) {
        list.clear();
        list.addAll(updatedList);
        notifyDataSetChanged();
    }


    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public int getCount() {
        return list.size();
    }

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

        if(row==null){
            LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.view_symptom_layout,parent,false);
            contactHolder = new ContactHolder();
            contactHolder.Name =(TextView) row.findViewById(R.id.textView2);
            contactHolder.Age =(TextView) row.findViewById(R.id.textView3);
            contactHolder.Height =(TextView) row.findViewById(R.id.textView4);
            contactHolder.Weight =(TextView) row.findViewById(R.id.textView5);
            contactHolder.Symptom =(TextView) row.findViewById(R.id.textView6);
            contactHolder.button = (Button) row.findViewById(R.id.button3);
            contactHolder.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String name;
                    name = nt.newList.get(position).getName(); // This is where I'm stucked.
                    Toast.makeText(getContext().getApplicationContext(), name+" is served ", Toast.LENGTH_LONG).show();
                }
            });

            row.setTag(contactHolder);
        }
        else{

            contactHolder = (ContactHolder)row.getTag();
        }



        Contacts contacts = (Contacts)this.getItem(position);
        contactHolder.Name.setText("Name: "+contacts.getName());
        contactHolder.Age.setText("Age: "+contacts.getAge());
        contactHolder.Height.setText("Height: "+contacts.getHeight());
        contactHolder.Weight.setText("Weight: "+contacts.getWeight());
        contactHolder.Symptom.setText("Symptoms: "+contacts.getSymptom());
        return row;



    }

    static class ContactHolder{
        TextView Name;
        TextView Age;
        TextView Height;
        TextView Weight;
        TextView Symptom;
        Button button;
    }

}

这是我从服务器检索所有值并将其存储在listview中的类:

package com.example.sohan.doctor;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sohan on 6/25/2016.
 */
public class notification extends Fragment implements AdapterView.OnItemSelectedListener{

    public final static String Message = "Sohan";
    View myView;
    String selectedCity;
    Context myContext;
    String jsonResult;
    JSONObject jsonObject;
    JSONArray jsonArray;
    String JSON_String;
    ContactAdapter contactAdapter;
    ListView listView;
    List<Contacts> newList;
    Button button;
    String send;
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.notification, container, false);
        myContext = inflater.getContext();
        contactAdapter = new ContactAdapter(myContext, R.layout.view_symptom_layout);
        listView = (ListView)myView.findViewById(R.id.listView);
        listView.setAdapter(contactAdapter);
        retrieveInfo ri = new retrieveInfo();
        ri.execute();
        return myView;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    class retrieveInfo extends AsyncTask<Void, Void, String> {             // send data to server

        String myUrl;


        protected void onPreExecute() {
            myUrl ="httP://myserver.com";    // change php script
        }


        protected String doInBackground(Void... args) {
            String city;
            String result = null;
            JSONArray jsonArray = null;
            try{
                URL url = new URL(myUrl);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
               // String data_to_send = URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(city,"UTF-8");
                //bufferedWriter.write(data_to_send);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream is = httpURLConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();


                while ((JSON_String = reader.readLine()) != null)
                {
                    sb.append(JSON_String+"\n");
                }
                reader.close();
                httpURLConnection.disconnect();
                is.close();
                return sb.toString().trim();
            }catch(MalformedURLException e){
                e.printStackTrace();
            }catch(IOException f){
                f.printStackTrace();
            }
            return null;
        }


        protected void onPostExecute(String result) {

            jsonResult = result;
            parseJSON(jsonResult);
        }
    }


    public void parseJSON(String json){
        Contacts contacts=null;
        try {
            jsonObject = new JSONObject(json);
            jsonArray = jsonObject.getJSONArray("patient");
            int count = 0;
            String name,age,height,weight,symptom;
            newList = new ArrayList<Contacts>();
            while (count < jsonArray.length()) {
                JSONObject jo = jsonArray.getJSONObject(count);
                name = jo.getString("Name");                          // data's are send to store in and print in listview
                age = jo.getString("Age");
                height = jo.getString("Height");
                weight = jo.getString("Weight");
                symptom = jo.getString("Symptom");
                contacts = new Contacts(name,age,height,weight,symptom);

                newList.add(contacts);                                   // data are stored in the newlist array
                count++;
            }

            contactAdapter.add(newList);                               // the newlist array are send to add in the listview

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

}

2 个答案:

答案 0 :(得分:0)

name = nt.newList.get(position).getName();

我认为应该是:

name = list.get(position).getName();

您还可以阅读这篇文章: ListView with Add and Delete Buttons in each Row in android

答案 1 :(得分:0)

您可以进行更多更改,例如以下内容。

ContactAdapter extends ArrayAdapter<Contacts>
List<Contacts> list = new ArrayList<Contacts>();

这一行:

String name,age,height,weight,symptom;

你应该将while循环初始化为null ""