How can I pass data from an activity to a GoogleMap.InfoWindowAdapter?

0

Hi, I'm new to programming on android and I'm stuck at this point. The idea of this application is that when you open the infowindow of a bookmark, it shows information from a database, I have been seeing other similar questions and I know that you can not pass the information by an intent but if you can through a method but I do not know how to do it because the information I want to appear in the infowindow is extracted from a database through a JSON. I hope you can help me, thanks in advance.

MainActivity.java

public class MainActivity extends AppCompatActivity {
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";

GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
String regid;

ImageButton btnVoyMap;

private static final String TAG = "MainActivity";

private BroadcastReceiver mRegistrationBroadcastReceiver;

private TextView mInformationTextView;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> emergenciaList;

// url to get all products list
private static String url_all_emergencias = "http://bomberosemergencias.pe.hu/get_all_emergencias.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "emergencia";

private static final String TAG_HORA = "hora";
private static final String TAG_UBICACION = "ubicacion";
private static final String TAG_TIPO = "tipo";
private static final String TAG_ESTADO = "estado";
private static final String TAG_MAQUINAS = "maquinas";


JSONArray products = null;

ListView lista;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnVoyMap = (ImageButton) findViewById(R.id.btnmap);

    // Hashmap para el ListView
    emergenciaList = new ArrayList<>();

    // Cargar los productos en el Background Thread
    new LoadAllProducts().execute();
    lista = (ListView) findViewById(R.id.listAllProducts);

    ActionBar actionBar = getSupportActionBar();
    assert actionBar != null;
    actionBar.setDisplayHomeAsUpEnabled(true);


            // Check device for Play Services APK.
            if (checkPlayServices()) {
                gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                regid = getRegistrationId(getApplicationContext());

                if (regid.isEmpty()) {

                    new RegisterApp(getApplicationContext(), gcm, getAppVersion(getApplicationContext())).execute();
                }

            } else {
                Log.i(TAG, "No valid Google Play Services APK found.");
            }


}//fin onCreate

class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Antes de empezar el background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Cargando...Por favor espere...");
        pDialog.setIcon(R.drawable.ic_launcher);
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * obteniendo todos los productos
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List params = new ArrayList();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_emergencias, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                //Log.i("ramiro", "produtos.length" + products.length());
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable

                    String hora = c.getString(TAG_HORA);
                    String ubicacion = c.getString(TAG_UBICACION);
                    String tipo = c.getString(TAG_TIPO);
                    String estado = c.getString(TAG_ESTADO);
                    String maquinas = c.getString(TAG_MAQUINAS);


                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<>();

                    // adding each child node to HashMap key => value

                    map.put(TAG_HORA, hora);
                    map.put(TAG_UBICACION, ubicacion);
                    map.put(TAG_TIPO, tipo);
                    map.put(TAG_ESTADO, estado);
                    map.put(TAG_MAQUINAS, maquinas);

                    emergenciaList.add(map);
                }

            }

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


        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        MainActivity.this,
                        emergenciaList,
                        R.layout.single_post,


                        new String[] {

                                TAG_HORA,
                                TAG_UBICACION,
                                TAG_TIPO,
                                TAG_ESTADO,
                                TAG_MAQUINAS,
                        },
                        new int[] {

                                R.id.single_post_tv_hora,
                                R.id.single_post_tv_ubicacion,
                                R.id.single_post_tv_tipo,
                                R.id.single_post_tv_estado,
                                R.id.single_post_tv_maquinas,

                        });
                // updating listview
                //setListAdapter(adapter);
                lista.setAdapter(adapter);
                Toast.makeText(getBaseContext(), "EMERGENCIAS ACTUALIZADAS",
                        Toast.LENGTH_SHORT).show();

            }
        });


    }
}






private void refresh() {
    finish();
    Intent myIntent = new Intent(this, MainActivity.class);
    startActivity(myIntent);

       }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}


private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.i(TAG, "This device is not supported.");
            finish();
        }
        return false;
    }
    return true;
}

/**
 * Gets the current registration ID for application on GCM service.
 * <p>
 * If result is empty, the app needs to register.
 *
 * @return registration ID, or empty string if there is no existing
 *         registration ID.
 */
private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.i(TAG, "Registration not found.");
        return "";
    }
    // Check if app was updated; if so, it must clear the registration ID
    // since the existing regID is not guaranteed to work with the new
    // app version.
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(getApplicationContext());
    if (registeredVersion != currentVersion) {
        Log.i(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

/**
 * @return Application's {@code SharedPreferences}.
 */
private SharedPreferences getGCMPreferences(Context context) {
    // This sample app persists the registration ID in shared preferences, but
    // how you store the regID in your app is up to you.
    return getSharedPreferences(MainActivity.class.getSimpleName(),
            Context.MODE_PRIVATE);
}

/**
 * @return Application's version code from the {@code PackageManager}.
 */
private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
                .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        // should never happen
        throw new RuntimeException("Could not get package name: " + e);
    }
}

public void onClickMapa (View view){

    Intent i = new Intent(this, MapsActivity.class);
    startActivity(i);

}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()){
        case R.id.AcercaDe:
            Toast.makeText(this, "DESARROLLADO POR ARQMAS-JMQC-2016",
                    Toast.LENGTH_LONG).show();
            break;


        case R.id.actualizar:
            refresh();

        case R.id.Salir:
            finish();

    }
    return false;
}
}

CustomInfoWindowAdapter.java

public class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

String tipo, hora, ubicacion, estado;

private static final String TAG = "CustomInfoWindowAdapter";
private LayoutInflater inflater;



public CustomInfoWindowAdapter(LayoutInflater inflater){
    this.inflater = inflater;
}

public View getInfoWindow(Marker arg0) {
    return null;

}



@Override
public View getInfoContents(final Marker m) {

    //Carga layout personalizado.
    View v = inflater.inflate(R.layout.infowindow_layout, null);

    String[] info = m.getTitle().split("&");
    String url = m.getSnippet();


    ((TextView)v.findViewById(R.id.tipo)).setText("Accidente vehicular");
    ((TextView)v.findViewById(R.id.hora)).setText("2017-10-14 04:16:38");
    ((TextView)v.findViewById(R.id.ubicacion)).setText("Arevalo");
    ((TextView)v.findViewById(R.id.estado)).setText("atendiendo");
    return v;
}




}

MapsActivity.class

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);

}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    final LatLng arequipa = new LatLng(-16.409896, -71.534169);
    Marker marcador = mMap.addMarker(new MarkerOptions()
            .position(arequipa)
            .title("")
    );

    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(arequipa, 17));
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    mMap.setInfoWindowAdapter(new 
   CustomInfoWindowAdapter(LayoutInflater.from(this)));
    marcador.showInfoWindow();


}


}
    
asked by JULIOM 18.10.2017 в 07:48
source

1 answer

0

If you want to be able to send information to your CustomInfoWindowAdapter to show it, you can do it in the following way.

When you create the Marker, in your Tag property, you can pass an array of string where you can pass all the information you want.

Then, in the getInfoContents method of the CustomInfoWindowAdapter class, you pick up that array of strings and get the information.

You can do:

string[] arr = new string[3];
arr[0] = "titulo";
arr[1] = "info1";
arr[2] = "info2";

Marker m = new Marker(...);
m.setTag(arr);

and collect this information in getInfoContents

String[] arr = (String[])m.getTag();

Now you have the information to show what you want:

((TextView)v.findViewById(R.id.tipo)).setText(arr[0]);
((TextView)v.findViewById(R.id.hora)).setText(arr[1]);
((TextView)v.findViewById(R.id.ubicacion)).setText(arr[2]);
    
answered by 18.10.2017 в 08:11