如何通过Android应用程序更新Firebase上的数据?

时间:2016-11-02 07:35:57

标签: java android firebase firebase-realtime-database

我尝试在Firebase中保存数据但捕获异常。我是Firebase的新用户,并按照Firebase网站上的教程,我也被要求添加它提供的文件以添加到Android Project中。是否有必要为我的对象创建一个java类? (我不这么认为)

//code in onCreate

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = database.getReference("-KTahsvshhslisAhhjej");
onLocationchanged中的

代码

//I tested Location is received well, i am somewhere messing the syntax
try
{

            mDatabase.child("Alt").setValue(location.getLongitude());
            mDatabase.child("Lat").setValue(location.getLatitude());
            mDatabase.child("Long").setValue(location.getLatitude());
            mDatabase.child("speed").setValue(location.getSpeed());

        }
catch (Exception e)
{
Toast.makeText(getBaseContext(), "Unable to Transfer to Firebase", Toast.LENGTH_LONG).show();
        }

Firebase Database Snap

更新后的代码:仍然没有得到答案

// onCreate code after editing
FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference mDatabase = database.getReference("testing-739c9/-KTJZ7ScdMo0hxKLZr54");


//onLocationChange code after editing
  Map<String,Object> taskMap = new HashMap<String,Object>();
        taskMap.put("Alt", location.getAltitude());
        taskMap.put("Long", location.getLongitude());
        taskMap.put("Lat", location.getLatitude());

    try {
        mDatabase.updateChildren(taskMap);
    } catch (Exception e) {

    try {
        mDatabase.updateChildren(taskMap);

    } catch (Exception e) {

        Toast.makeText(getBaseContext(), "Unable to Transfer to Firebase", Toast.LENGTH_LONG).show();
    }
    }

1 个答案:

答案 0 :(得分:1)

您必须首先使用.push()方法生成密钥,请参阅firebase示例。使用.push()。getId()创建新节点并给出其id。创建节点后,您可以使用.setvalue()