Firebase 离线存储数据
Firebase store data offline
我正在尝试存储从 JSON 字符串中获取的数据,以便我可以离线使用该应用程序,但我一直收到此错误:
Caused by: com.google.firebase.database.DatabaseException: Invalid Firebase Database path: https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/. Firebase Database paths must not contain '.', '#', '$', '[', or ']'
我的问题是,我是不是代码写错了?因为这条路看起来不错。我试图删除“ - ”但我得到了同样的错误。这是我写代码的class:
public class NutritionPlan1 extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> resultList;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nutrition_plan1);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(NutritionPlan1.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://api.spoonacular.com/recipes/complexSearch?diet=vegetarian&addRecipeNutrition=true&apiKey=d22842b0ca9148839497a0022902ae97";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray results = jsonObj.getJSONArray("results");
// looping through All items
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
String title = c.getString("title");
String healthScore = c.getString("healthScore");
String servings = c.getString("servings");
String pricePerServing = c.getString("pricePerServing");
String readyInMinutes = c.getString("readyInMinutes");
// tmp hash map for single contact
HashMap<String, String> result = new HashMap<>();
// adding each child node to HashMap key => value
result.put("title",title);
result.put("pricePerServing","Cost: " + pricePerServing);
result.put("servings","Servings: " + servings);
result.put("healthScore","Health Score: " +healthScore);
result.put("readyInMinutes","Time to cook: " +readyInMinutes +"minutes" );
// adding contact to contact list
resultList.add(result);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(NutritionPlan1.this, resultList,
R.layout.list_nutrition_plans, new String[]{ "title","pricePerServing","servings","healthScore","readyInMinutes"},
new int[]{R.id.title, R.id.pricePerServing,R.id.servings,R.id.healthscore,R.id.readyInMinutes});
lv.setAdapter(adapter);
}
}
}
而不是这个:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/");
应该使用这个:
FirebaseDatabase database = FirebaseDatabase.getInstance("https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/");
DatabaseReference myRef = database.getReference();
另请参阅 connecting to the Realtime Database 上的文档,其中说:
To get a reference to a database other than a us-central1
default database, you must pass the database URL to getInstance()
.
我正在尝试存储从 JSON 字符串中获取的数据,以便我可以离线使用该应用程序,但我一直收到此错误:
Caused by: com.google.firebase.database.DatabaseException: Invalid Firebase Database path: https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/. Firebase Database paths must not contain '.', '#', '$', '[', or ']'
我的问题是,我是不是代码写错了?因为这条路看起来不错。我试图删除“ - ”但我得到了同样的错误。这是我写代码的class:
public class NutritionPlan1 extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> resultList;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nutrition_plan1);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(NutritionPlan1.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://api.spoonacular.com/recipes/complexSearch?diet=vegetarian&addRecipeNutrition=true&apiKey=d22842b0ca9148839497a0022902ae97";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray results = jsonObj.getJSONArray("results");
// looping through All items
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
String title = c.getString("title");
String healthScore = c.getString("healthScore");
String servings = c.getString("servings");
String pricePerServing = c.getString("pricePerServing");
String readyInMinutes = c.getString("readyInMinutes");
// tmp hash map for single contact
HashMap<String, String> result = new HashMap<>();
// adding each child node to HashMap key => value
result.put("title",title);
result.put("pricePerServing","Cost: " + pricePerServing);
result.put("servings","Servings: " + servings);
result.put("healthScore","Health Score: " +healthScore);
result.put("readyInMinutes","Time to cook: " +readyInMinutes +"minutes" );
// adding contact to contact list
resultList.add(result);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(NutritionPlan1.this, resultList,
R.layout.list_nutrition_plans, new String[]{ "title","pricePerServing","servings","healthScore","readyInMinutes"},
new int[]{R.id.title, R.id.pricePerServing,R.id.servings,R.id.healthscore,R.id.readyInMinutes});
lv.setAdapter(adapter);
}
}
}
而不是这个:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/");
应该使用这个:
FirebaseDatabase database = FirebaseDatabase.getInstance("https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/");
DatabaseReference myRef = database.getReference();
另请参阅 connecting to the Realtime Database 上的文档,其中说:
To get a reference to a database other than a
us-central1
default database, you must pass the database URL togetInstance()
.