Home > Back-end >  Firebase store data offline
Firebase store data offline

Time:06-01

I'm trying to store the data I get from JSON string so I can use the app offline but I keep getting this error :

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 ']'

My question is, did I write the code wrong? Cause the path seems good. I tried to remove " - " but I get the same error. This is the class where I wrote the code:

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);
        }
    }
}             

CodePudding user response:

Instead of this:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/");

should use this:

FirebaseDatabase database = FirebaseDatabase.getInstance("https://my-application-fe439-default-rtdb.europe-west1.firebasedatabase.app/");
DatabaseReference myRef = database.getReference();

Also see the documentation on connecting to the Realtime Database, which says:

To get a reference to a database other than a us-central1 default database, you must pass the database URL to getInstance().

  • Related