如何使用listView onItemClick

时间:2018-03-10 11:28:29

标签: java listview firebase arraylist firebase-realtime-database

我正在尝试创建基于Firebase实时数据库的购物列表应用程序。

public class testActivity extends AppCompatActivity {

//Firebase
private DatabaseReference mDatabase;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;

//Android Layout
private ListView productList;
private Button btnAdd;
private EditText etProduct;

//Array List
private ArrayList<String> productArrayList = new ArrayList<>();
private ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    //Firebase Reference
    String currentUserId = firebaseAuth.getInstance().getCurrentUser().getUid().toString();
    mDatabase = FirebaseDatabase.getInstance().getReference().child(currentUserId);

    //ListView adapter
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, productArrayList);

    //Layout
    btnAdd = (Button) findViewById(R.id.btnAddProduct);
    etProduct = (EditText) findViewById(R.id.etAddProduct);
    productList = (ListView) findViewById(R.id.testList);
    productList.setAdapter(adapter);

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mDatabase.push().setValue(etProduct.getText().toString());
        }
    });

    productList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
             ----------- STUCK HERE ------------
        }
    });

    mDatabase.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            String product = dataSnapshot.getValue().toString();
            productArrayList.add(product);
            adapter.notifyDataSetChanged();
            Toast.makeText(testActivity.this, product + " added!", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            String product = dataSnapshot.getValue().toString();
            productArrayList.remove(product);
            adapter.notifyDataSetChanged();
            Toast.makeText(testActivity.this, product + " removed!", Toast.LENGTH_SHORT).show();
        }
    });
}

那么,它做了什么 - 它需要当前登录的用户唯一ID,并将项目从编辑文本添加到列表视图,并添加到具有唯一键的数据库。因为它似乎可以保存到数据库并且如果我删除它或添加数据库就会做出反应。 我为列表视图创建了一个OnClickEventListener,但我不知道如何从数据库和列表视图中删除listView中当前单击的项。

Data structure in Firebase

提前谢谢。

0 个答案:

没有答案