0

I am populating name of hospitals from my firebase database into a listview with the help of FirebaselistAdapter. Now i want to get the key say Achimota hospital when Achimota hospital name is clicked from the listview.

Have tried this Retrieving the Firebase key from onItemClick in FirebaseListAdapter and several ones here but still not gotten a solution.

Hospital_main.java

`

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Hospital_main extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<LocationSettingsResult> {

    protected GoogleApiClient mGoogleApiClient;
    protected LocationRequest locationRequest;
    int REQUEST_CHECK_SETTINGS = 100;

    TextView currentLocation;

    // GPSTracker class
    GPSTracker gps;

    public ListView mlistView;
    private ProgressDialog mProgressDialog;
    private DatabaseReference myRef;
    public double currentLat,currentLon;

    public TextView distanceLength;
    public double distance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hospital_main);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mlistView = (ListView) findViewById(R.id.listViewHospital);

        //distanceLength = (TextView) findViewById(R.id.currentLocation3) ;

        gps = new GPSTracker(Hospital_main.this);

        if (gps.canGetLocation()){

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            currentLat = latitude;
            currentLon = longitude;


            BackgroundOperation bg = new BackgroundOperation();
            bg.execute();

        }else {

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            mGoogleApiClient.connect();

            locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);


        }


    }



    class BackgroundOperation extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            mProgressDialog = new ProgressDialog(Hospital_main.this);

            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();

        }

        @Override
        protected String doInBackground(String... params) {
            FirebaseDatabase database = FirebaseDatabase.getInstance();
            myRef = database.getReference("Hospitals");

            return null;
        }

        @Override
        protected void onPostExecute(String result) {


            final FirebaseListAdapter<FacilityDetails> firebaseListAdapter = new FirebaseListAdapter<FacilityDetails>(
                    Hospital_main.this,
                    FacilityDetails.class,
                    R.layout.list_row,
                    myRef
            ) {


                @Override
                protected void populateView(View v, FacilityDetails model, int position) {


                    TextView textView = (TextView) v.findViewById(R.id.title);
                    TextView textView1 = (TextView) v.findViewById(R.id.subtitle);

                    String d = null;
                    if (model.name.length() < 24){
                        d = " ";
                    }else {
                        d = "..";
                    }

                    textView.setText(model.name.substring(0,Math.min(model.name.length(),24))+d);
                    textView1.setText(model.description.substring(0,Math.min(model.description.length(),120))+" ...");

                    TextView textView2 = (TextView) v.findViewById(R.id.duration);

                    /** Callculating the location **/
                    Location mylocation = new Location("");
                    Location dest_location = new Location("");
                    String lat = Double.toString(model.latitude);
                    String lon = Double.toString(model.longitude);
                    dest_location.setLatitude(Double.parseDouble(lat));
                    dest_location.setLongitude(Double.parseDouble(lon));
                    Double my_locLat = currentLat;
                    Double my_locLng = currentLon;
                    mylocation.setLatitude(my_locLat);
                    mylocation.setLongitude(my_locLng);
                    distance = round((mylocation.distanceTo(dest_location))/1000,2);//in meters


                    String calDistance = Double.toString(distance)+"Km";

                    textView2.setText(calDistance);

                    if ( mProgressDialog!=null && mProgressDialog.isShowing() ){
                        mProgressDialog.dismiss();
                    }

                }
            };


            mlistView.setAdapter(firebaseListAdapter);

            if (mlistView.isEnabled()){
                mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                       DatabaseReference itemRef = firebaseListAdapter.getRef(position);
                    String Topic = itemRef.getKey();

                        Toast toast = Toast.makeText(getApplicationContext(), "Topic: "+Topic, Toast.LENGTH_SHORT);
                        toast.show();
                    }
                });
            }


        }

        @Override
        protected void onProgressUpdate(Void... values) {
            if ( mProgressDialog!=null && mProgressDialog.isShowing() ){
                mProgressDialog.dismiss();
            }
        }


    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);
        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(
                        mGoogleApiClient,
                        builder.build()
                );

        result.setResultCallback(this);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
        final Status status = locationSettingsResult.getStatus();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:

                // NO need to show the dialog;

                break;

            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                //  Location settings are not satisfied. Show the user a dialog

                try {
                    // Show the dialog by calling startResolutionForResult(), and check the result
                    // in onActivityResult().

                    status.startResolutionForResult(Hospital_main.this, REQUEST_CHECK_SETTINGS);

                } catch (IntentSender.SendIntentException e) {

                    //failed to show
                }
                break;

            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                // Location settings are unavailable so not possible to show any dialog now
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CHECK_SETTINGS) {

            if (resultCode == RESULT_OK) {

                Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
            } else {

                Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
            }

        }
    }



    public static double round(double value, int places) {
        if (places < 0) throw new IllegalArgumentException();

        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(places, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

}

FacilityDetails.java

public class FacilityDetails {

    public String name;
    public String description;
    public double latitude;
    public double longitude;


}

Firebase Database

"Achimota hospital" : {
    "contact" : "0302-400553",
    "description" : "Achimota Hospital in Achimota, Accra provides services in Health & Medical Centers and Hospitals. ",
    "distance" : 2.74,
    "insurance" : "NHIS",
    "latitude" : 5.6294907,
    "location" : "5.6294907,-0.2192158",
    "longitude" : -0.2192158,
    "name" : "Achimota Hospital",
    "service" : "General"
  },
  "Dangbe West District Hospital" : {
    "contact" : "0244-274807",
    "description" : "The Dangme East District hospital is one of the ten (10) district hospitals in the Greater Accra Region of Ghana. It covers Big Ada and Ada Kasseh. Ada Foah.",
    "distance" : 1,
    "insurance" : "NHIS",
    "latitude" : 5.87958,
    "location" : "5.879580,-0.094806",
    "longitude" : -0.094806,
    "name" : "Dangbe West District Hospital",
    "service" : "General"
  },

`

I want to return the key Achimota hospital when that item is clicked on the listview. Any help appreciated.

Emmanuel Gamor
  • 69
  • 1
  • 10
  • Your code is quite different from what I've provided in [my answer to the question you linked](https://stackoverflow.com/a/39855001/209103). You'll need to call `adapter.getItem(position);` somewhere to look up the item that the user clicked on. – Frank van Puffelen Jun 24 '17 at 17:39
  • @FrankvanPuffelen tried using `FacilityDetails item = firebaseListAdapter.getItem(position);` but its still not working. i rather get something like `com.example.user.myhealthapp.FacilityDetails`.. please help. Thanks in advance. – Emmanuel Gamor Jun 24 '17 at 19:24
  • Please update your question with the latest code. I highly recommend constructing an [MCVE](http://stackoverflow.com/help/mcve) as it is the most likely way we'll be able to help – Frank van Puffelen Jun 24 '17 at 19:25
  • @FrankvanPuffelen MCVE been constructed as requested. – Emmanuel Gamor Jun 24 '17 at 22:48
  • Thanks. Now what is the problem when you run this code? Are there any errors? – Frank van Puffelen Jun 24 '17 at 23:54
  • There is no error when i run this codes. But `OnItemClickListener` it returns `com.example.user.myhealthapp.FacilityDetails` instead of the item key say `Achimota hospital`. i want to get the item key of the clicked item so i can use it at a different activity to get data from the firebase database. – Emmanuel Gamor Jun 25 '17 at 11:16
  • Are you looking for `firebaseListAdapter.getRef(position).getKey()`? Also see: https://stackoverflow.com/questions/32997219/how-to-get-obj-key-from-firebaselistadapter-on-item-click-firebaseui – Frank van Puffelen Jun 25 '17 at 14:26
  • Thanks @FrankvanPuffelen your answer here (https://stackoverflow.com/questions/32997219/how-to-get-obj-key-from-firebaselistadapter-on-item-click-firebaseui) explains it better for me. – Emmanuel Gamor Jun 25 '17 at 15:44

0 Answers0