如何将从 Google Place API 获取的信息存储到 Firebase?
Posted
技术标签:
【中文标题】如何将从 Google Place API 获取的信息存储到 Firebase?【英文标题】:How to put the Information get from Google Place API and store to Firebase? 【发布时间】:2019-03-25 17:23:15 【问题描述】:我正在遵循教程并将 google place api 实施到我的文件中。 但我想将其更改为 Firebase。也许保存到表格“位置”
任何人都可以指导我如何将其保存到 firebase。我参考的代码来自这里:https://github.com/delaroy/androidLocationGeofencing 提前感谢,如果信息不足,我会再次添加。
Screenshot 1 Screenshot 2
package com.example.edward.neweventmanagementsystem;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.edward.neweventmanagementsystem.provider.PlaceContract;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import static android.widget.Toast.LENGTH_SHORT;
public class ManageLocation extends AppCompatActivity implements
ConnectionCallbacks,
OnConnectionFailedListener
// Constants
public static final String TAG = ManageLocation.class.getSimpleName();
private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final int PLACE_PICKER_REQUEST = 1;
// Member variables
private PlaceListAdapter mAdapter;
private RecyclerView mRecyclerView;
private boolean mIsEnabled;
private GoogleApiClient mClient;
private Geofencing mGeofencing;
private DatabaseReference mDatabaseReference;
Context mContext;
PlaceBuffer mPlaces;
/**
* Called when the activity is starting
*
* @param savedInstanceState The Bundle that contains the data supplied in onSaveInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_location);
// Set up the recycler view
mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PlaceListAdapter(this, null);
mRecyclerView.setAdapter(mAdapter);
// Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch);
// mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled), false);
// onOffSwitch.setChecked(mIsEnabled);
// onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
// SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
// editor.putBoolean(getString(R.string.setting_enabled), isChecked);
// mIsEnabled = isChecked;
// editor.commit();
// if (isChecked) mGeofencing.registerAllGeofences();
// else mGeofencing.unRegisterAllGeofences();
//
//
// );
mClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, this)
.build();
mGeofencing = new Geofencing(this, mClient);
/***
* Called when the Google API Client is successfully connected
*
* @param connectionHint Bundle of data provided to clients by Google Play services
*/
@Override
public void onConnected(@Nullable Bundle connectionHint)
refreshPlacesData();
Log.i(TAG, "API Client Connection Successful!");
/***
* Called when the Google API Client is suspended
*
* @param cause cause The reason for the disconnection. Defined by constants CAUSE_*.
*/
@Override
public void onConnectionSuspended(int cause)
Log.i(TAG, "API Client Connection Suspended!");
/***
* Called when the Google API Client failed to connect to Google Play Services
*
* @param result A ConnectionResult that can be used for resolving the error
*/
@Override
public void onConnectionFailed(@NonNull ConnectionResult result)
Log.e(TAG, "API Client Connection Failed!");
public void refreshPlacesData()
Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
Cursor data = getContentResolver().query(
uri,
null,
null,
null,
null);
if (data == null || data.getCount() == 0) return;
List<String> guids = new ArrayList<String>();
while (data.moveToNext())
guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID)));
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient,
guids.toArray(new String[guids.size()]));
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>()
@Override
public void onResult(@NonNull PlaceBuffer places)
mAdapter.swapPlaces(places);
mGeofencing.updateGeofencesList(places);
if (mIsEnabled) mGeofencing.registerAllGeofences();
);
public void onAddPlaceButtonClicked(View view)
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_LONG).show();
return;
try
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Intent i = builder.build(this);
startActivityForResult(i, PLACE_PICKER_REQUEST);
catch (GooglePlayServicesRepairableException e)
Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
catch (GooglePlayServicesNotAvailableException e)
Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
catch (Exception e)
Log.e(TAG, String.format("PlacePicker Exception: %s", e.getMessage()));
/***
* Called when the Place Picker Activity returns back with a selected place (or after canceling)
*
* @param requestCode The request code passed when calling startActivityForResult
* @param resultCode The result code specified by the second activity
* @param data The Intent that carries the result data.
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK)
final Place place = PlacePicker.getPlace(this, data);
if (place == null)
Log.i(TAG, "No place selected");
return;
final String placeID = place.getId();
// Insert a new place into DB
// ContentValues contentValues = new ContentValues();
// contentValues.put(PlaceContract.PlaceEntry.COLUMN_PLACE_ID, placeID);
// getContentResolver().insert(PlaceContract.PlaceEntry.CONTENT_URI, contentValues);
//Place the data into Firebase
// Get live data information
refreshPlacesData();
public void onRingerPermissionsClicked(View view)
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
public void onLocationPermissionClicked(View view)
ActivityCompat.requestPermissions(ManageLocation.this,
new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
PERMISSIONS_REQUEST_FINE_LOCATION);
【问题讨论】:
【参考方案1】: private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK)
final Place place = PlacePicker.getPlace(this, data);
if (place == null)
Log.i(TAG, "No place selected");
return;
final String placeID = place.getId();
//Place the data into Firebase
insertPlcaeIdinDb(placeID);
// Get live data information
refreshPlacesData();
private void insertPlcaeIdinDb(String placeID)
mDatabase.child("yourBranchNameinDb").setValue(placeID );
了解什么是
FirebaseDatabase.getInstance().getReference()
您可以从 there 关注 Firebase for android 官方文档
【讨论】:
谢谢。现在可以插入数据库,但如果添加新位置,它总是替换旧记录。我已经更改了其中的一些内容 [屏幕截图 2],但我觉得还需要存储地名和地址,但不知道如何编码。另一个问题是,如果按照github.com/delaroy/AndroidLocationGeofencing中的代码更改为上面的代码,回收视图无法显示已添加的位置列表。 如果您有存储在数据库中的想法,请检查此答案是否已接受,我会尽力帮助您提供给您的链接,其中包含有关 firebase 的所有教程 @EdwardLiew 这是一项漫长的任务,您应该先尝试在 firebase 中创建分支 你需要这样的东西来存储地点 "places": "some name or Id": "place_name": "Ada Lovelace", "place_address": "ghopper", , "一些名称或 ID”: ... ,“一些名称或 ID”: ... 你也应该使用主分支“places”来更新或插入任何新记录以上是关于如何将从 Google Place API 获取的信息存储到 Firebase?的主要内容,如果未能解决你的问题,请参考以下文章
iOS Swift - Google Place API (Web) 以一种奇怪的格式返回 JSON
如何使用 Google Place API 进行 mapview 搜索地点