简体   繁体   English

BaseAdaper中的广播接收器

[英]Broadcast receiver in BaseAdaper

I want to update a textview into a listView when i get my current position (GPS). 我想在获取当前位置(GPS)时将textview更新为listView。

So i send a broadcast in my activity when i had my position. 因此,当我担任职务时,我会在活动中发送广播。 In my listViewAdapter, i have a receiver who set text. 在我的listViewAdapter中,我有一个设置文本的接收器。 But i don't know where i can registrer and unregistrer my broadcast. 但是我不知道在哪里可以注册和取消注册我的广播。

May be there is an other solution to send parameter to my listViewAdapter when my current position is available. 当我当前位置可用时,可能还有另一种解决方案将参数发送到我的listViewAdapter。

MainActivity : 主要活动 :

private ArrayList<Establishment> listEstablishment;
private ListViewEstablishmentsAdapter adapter;


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_layout);

        pr = new PositionReceiver();

        //Get the list view
        ListView l = (ListView) findViewById(R.id.listviewEstablishments);

        //Create WebService to retrieve establishments datas
        EstablishmentInfosWebService ews = new EstablishmentInfosWebService("select * from establishment");
        listEstablishment = ews.getData();


        //Create a new adapter View
         adapter = new ListViewEstablishmentsAdapter(this, listEstablishment);
        l.setAdapter(adapter);



         public class PositionReceiver extends BroadcastReceiver {

            @Override
            public void onReceive(Context context, Intent intent) {
                Location l = (Location) intent.getExtras().get("LOCATION");
                int i = 0;
                for(Establishment e : listEstablishment) {
            double d = distance(e.getLatitude(), e.getLongitude(), l.getLatitude(), l.getLongitude(), 'K');
                e.setDistance(d+"");
            Log.d(TAG,"onreceive "+i);
            i++;
        }
            }
        }



 @Override
        public void onResume() {
            super.onResume();
            registerReceiver(pr, new IntentFilter("com.example.smartoo.POSITION_INTENT"));
        }

        /*
         * Called when the Activity is going into the background.
         * Parts of the UI may be visible, but the Activity is inactive.
         */
        @Override
        public void onPause() {

            unregisterReceiver(pr);
            super.onPause();
        }

ListViewAdapter : ListViewAdapter:

public class ListViewEstablishmentsAdapter extends BaseAdapter {

    private static final String TAG = "com.example.smartoo.ListViewEstablishmentAdapter";

    //Un mécanisme pour gérer l'affichage graphique depuis un layout XML
    private LayoutInflater mInflater;
    //Le contexte dans lequel est présent notre adapter
    private final Context context;
    // Une liste d'établissements
    private ArrayList<Establishment> establishmentsList = null;



    private ViewHolder holder;

    //TODO add my currentLocation to constructor
    /**
     *
     * @param context
     * @param values
     *
     * Constructor
     */
    public ListViewEstablishmentsAdapter(Context context, ArrayList<Establishment> values) {
        super();
        this.context = context;
        establishmentsList = values;
        mInflater = LayoutInflater.from(context);
    }

    /**
     * @return number of establishments
     */
    @Override
    public int getCount() {
        return establishmentsList.size();
    }

    /**
     * @param position
     * @return Establishment to position "position"
     */
    @Override
    public Object getItem(int position) {
        return establishmentsList.get(position);
    }

    /**
     * @param position
     * @return The position of item
     */
    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //ViewHolder holder = null;
        // Si la vue n'est pas recyclée
        if (convertView == null) {
            // On récupère le layout
            convertView = mInflater.inflate(R.layout.item, null);

            holder = new ViewHolder();
            // On place les widgets de notre layout dans le holder
            holder.Name = (TextView) convertView.findViewById(R.id.name);
            holder.Description = (TextView) convertView.findViewById(R.id.description);
            holder.Distance = (TextView) convertView.findViewById(R.id.distance);

            // puis on insère le holder en tant que tag dans le layout
            convertView.setTag(holder);
        } 
        else {
            // Si on recycle la vue, on récupère son holder en tag
            holder = (ViewHolder) convertView.getTag();
        }

        // Dans tous les cas, on récupère le contact téléphonique concerné
        Establishment e = (Establishment) getItem(position);
        // Si cet élément existe vraiment…
        if (e != null) {
            // On place dans le holder les informations sur le contact
            holder.Name.setText(e.getName());
            holder.Description.setText(e.getDescription());
            //TODO calculate distance with my position and longitude and latitdue
            holder.Distance.setText(e.getDistance());
        }
        return convertView;

    }

    static class ViewHolder {
        public TextView Name;
        public TextView Description;
        public TextView Distance;
    }

    public void updateEstablishmentList(ArrayList<Establishment> newlist) {
        establishmentsList.clear();
        establishmentsList.addAll(newlist);
        this.notifyDataSetChanged();
    }
}

Establishment : 成立时间:

public class Establishment {

    //An identifer
    private int idEstablishment;

    //A Name
    private String name;

    //An address
    private String address;

    //An url picture
    private String urlImage;

    //A description
    private String description;

    //A phone number
    private String phoneNumber;

    //A type of establishment_fragment
    private int type;

    //A location
    private double latitude;
    private double longitude;

//A distance
    private String distance = "0m";


    public Establishment () {
        super();
        idEstablishment = 0;
        name = "";
        address = "";
        urlImage = "";
        description = "";
        phoneNumber = "";
        type = 0;
        latitude = 0;
        longitude = 0;
    }

    /**
     *
     * @param id
     * @param n
     * @param url
     * @param d
     * @param p
     * @param t
     * @param lat
     * @param lon
     *
     * Constructor
     */
    public Establishment (int id, String n, String a, String url, String d, String p, int t, double lat, double lon) {
        idEstablishment = id;
        name = n;
        address = a;
        urlImage = url;
        description = d;
        phoneNumber = p;
        type = t;
        latitude = lat;
        longitude = lon;
    }

    public int getIdEstablishment() {
        return idEstablishment;
    }

    public void setIdEstablishment(int idEstablishment) {
        this.idEstablishment = idEstablishment;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getUrlImage() {
        return urlImage;
    }

    public void setUrlImage(String urlImage) {
        this.urlImage = urlImage;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

   public String getDistance() {
        return distance;
    }

    public void setDistance(String distance) {
        this.distance = distance;
    }
}

Manifest : 清单:

<activity
            android:name=".HomeActivity"
            android:label="Home"
            android:theme="@style/Theme.AppCompat.Light" >
            <action android:name="android.location.PROVIDERS_CHANGED" />

            <receiver android:name=".PositionReceiver">
                <intent-filter>
                    <action android:name="com.example.smartoo.POSITION_INTENT">
                    </action>
                </intent-filter>
            </receiver>

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

** ANSWER : ** **答案:**

public void updateEstablishmentList(ArrayList<Establishment> newlist) {
            establishmentsList = newlist;
            this.notifyDataSetChanged();
        }

You shouldn't put the BroadcastReceiver in the Adapter , it doesn't belong there. 您不应该将BroadcastReceiver放入Adapter ,它不属于Adapter Put it in the Activity or Fragment which contains the ListView . 将其放在包含ListViewActivityFragment中。 To pass a new location to the ListView you need to implement a method to set the location to a specific row in the Adapter : 要将新位置传递给ListView您需要实现一种方法来将该位置设置为Adapter的特定行:

Of course your class Establishment needs to contain a field to store the Location along with appropriate getters and setters: 当然,您的课程Establishment需要包含一个字段来存储Location以及适当的getter和setter:

public void setLocationAtPosition(int position, Location location) {
    Establishment e = (Establishment) getItem(position);
    e.setLocation(location);
    notifyDataSetChanged();
}

And in getView() of your Adapter : 在你的Adapter getView()中:

Establishment e = (Establishment) getItem(position);
if (e != null) {
    holder.Name.setText(e.getName());
    holder.Description.setText(e.getDescription());

    Location location = e.getLocation();
    double longitude = location.getLongitude();
    double latitude = location.getLatitude()
    holder.Distance.setText(longitude + "/" + latitude);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM