添加第二个数据库微调器并将其显示在TextView

时间:2018-06-04 07:25:09

标签: android firebase firebase-realtime-database spinner

我想创建一个应用程序,您可以通过firebase数据库添加前名和姓氏。使用按钮可以添加名字,它存储在数据库中,使用微调器可以选择它。

代码:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemSelectedListener {

DatabaseReference db;
FirebaseHelper helper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    Spinner sp = (Spinner) findViewById(R.id.spinner);

    //SETUP FB
    db = FirebaseDatabase.getInstance().getReference();
    helper = new FirebaseHelper(db);

    sp.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,helper.retrieve()));

    Button fab = (Button) findViewById(R.id.btnAdd1);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            displayInputDialog();
        }
    });

 (...)

//DISPLAY INPUT DILAOG
private void displayInputDialog()
{
    Dialog d=new Dialog(this);
    d.setTitle("Firebase database");
    d.setContentView(R.layout.input_dialog);

    final EditText nameTxt = (EditText) d.findViewById(R.id.nameEditText);
    Button saveBtn = (Button) d.findViewById(R.id.saveBtn);

    //SAVE
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //GET DATA
            String name = nameTxt.getText().toString();

            //set data
            FirstWord s = new FirstWord();
            s.setName(name);

            //SAVE
            if(name != null && name.length()>0) {
                if(helper.save(s)) {
                    nameTxt.setText("");
                }
            }else {
                Toast.makeText(MainActivity.this, "Name Cannot Be Empty", Toast.LENGTH_SHORT).show();
            }
        }
    });
    d.show();
}

Firebasehelper类:

public class FirebaseHelper {

DatabaseReference db;
Boolean saved = null;


public FirebaseHelper (DatabaseReference db) {
    this.db = db;
}

public Boolean save(FirstWord firstWord) {
    if(firstWord == null) {
        saved = false;
    } else {
        try {
            db.child("FirstWord").push().setValue(firstWord);
            saved = true;
        } catch (DatabaseException e) {
            e.printStackTrace();
            saved = false;
        }
    }

    return saved;
}

//READ

public ArrayList<String> retrieve() {

    final ArrayList<String> spacecrafts = new ArrayList<>();

    db.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            fetchData(dataSnapshot, spacecrafts);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            fetchData(dataSnapshot, spacecrafts);
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return spacecrafts;
}

private void fetchData (DataSnapshot snapshot, ArrayList<String> spacecrafts) {
    spacecrafts.clear();
    for(DataSnapshot ds:snapshot.getChildren()) {
        String name = ds.getValue(FirstWord.class).getName();
        spacecrafts.add(name);
    }

}
}

我还有Firstname.class来获取和设置名称。

我可以添加名称,数据库显示名称,使用微调器我可以选择它。

现在我有两个问题。

  • 如何添加第二个微调器和另一个数据库条目?当我添加第二个微调器时,使相同的displayInputDialog方法(称之为displayInputDialog2,当然还要更改所有变量)并创建两个新类(secondname.class和firebasehelper2.class),微调器始终显示firstname数据库或secondname数据库。 所以我添加了一个名字,数据库添加一个条目,两个微调器都显示它。比我添加第二个名称,数据库正在添加两个条目,两个微调器都显示两个条目(两个相同的名称)

以下是数据库条目

&#13;
&#13;
{
  "FirstName" : {
    "-LE5yfrJR8CwMLxROhAr" : {
      "name" : "Hi"
    },
    "-LE61Zklt9LJbbaltoYE" : {
      "name" : "Hello "
    },
    "-LE6MGTBmPk7y57J9c03" : {
      "name" : "Hey "
    }
  },
  "SecondName" : {
    "-LE6-tJx6lxNpsLYjUSk" : {
      "name" : "log ",
      "name2" : "log "
    },
  }
}
&#13;
&#13;
&#13;

  • 如何将微调器entrie添加到TextView?

喜欢这里:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    final TextView viewn = (TextView)findViewById(R.id.show2);

    switch(parent.getId()) {          
        case R.id.spinner2:
            String itemSecond = parent.getItemAtPosition(position).toString();

            Toast.makeText(parent.getContext(), "Selected: " + itemSecond, Toast.LENGTH_SHORT).show();

            viewn.setText(itemSecond);
    }

提前谢谢! 非常抱歉长文本和所有代码。

问候

0 个答案:

没有答案