列表视图仅显示一个项目

时间:2017-11-09 06:03:03

标签: android listview firebase firebase-realtime-database

我正在制作Android ListView以显示Firebase数据库中的对象,但我添加了这些项目,但ListView中只显示了一个项目。我使用ArrayAdapter,所有代码都在下面。只显示第一项而不是所有提供的数据

示例JSON文件在这里:

{
  "items" : {
    "item0" : {
      "description" : "its an apple",
      "name" : "apples",
      "price" : 10,
      "productID" : 0,
      "quantity" : 5,
      "type" : "fruit"
    },
    "item1" :  {
      "description" : "its an orange",
      "name" : "oranges",
      "price" : 10,
      "productID" : 1,
      "quantity" : 15,
      "type" : "fruit"
      },
      "item2" :  {
      "description" : "bagle",
      "name" : "bagles",
      "price" : 9,
      "productID" : 2,
      "quantity" : 7,
      "type" : "food"
      }
  },

  "users" : {
    "dummy" : "keep this entry. without this, the other entries won't appear on the database"
  }
}

http://paste.ubuntu.com/25916653/

activity_main_app_page.xml

<android.support.design.widget.CoordinatorLayout    
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.ub.akshay.nitkart.MainAppPage">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <ListView
        android:id="@+id/shoppingList"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="8dp"
        android:paddingBottom="120dp"
        android:clipToPadding="false"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbarStyle="outsideOverlay" />

    <ProgressBar
        android:id="@+id/mainPageProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/cartMainPage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        app:backgroundTint="@android:color/background_light"
        app:srcCompat="@drawable/ic_shopping_cart_black_24dp" />


</android.support.design.widget.CoordinatorLayout>`

MainActivity.java

package com.ub.tom.smith;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class MainAppPage extends AppCompatActivity {

    public final String TAG = MainAppPage.class.getSimpleName();
    ListView shoppingItemView;
    ShoppingListAdapter adapter;
    ProgressBar progressBar;
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("items");
    private Boolean exit = false;
    private ArrayList<ShoppingItem> shoppingItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_app_page);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("NITKart");
        setSupportActionBar(toolbar);

        FloatingActionButton shoppingCart = (FloatingActionButton)    
        findViewById(R.id.cartMainPage);
        shoppingCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(),   
                ShoppingCartWindow.class));
            }
        });

        progressBar = (ProgressBar)   
        findViewById(R.id.mainPageProgressBar);
        shoppingItemView = (ListView) findViewById(R.id.shoppingList);

        myRef.addValueEventListener(new ValueEventListener() {
            // This listener is only for database with reference of key 
            "items"
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and           
                 again
                // whenever data at this location is updated.

                // Now the Shopping List gets updated whenever the data 
                shoppingItems = getAllItems(dataSnapshot);
                adapter = new ShoppingListAdapter(getApplicationContext(), 
                shoppingItems);
                progressBar.setVisibility(View.GONE);
                shoppingItemView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });

        shoppingItemView.setOnItemClickListener(new  
        AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,  
            int i, long l) {
                Intent productIntent = new Intent(MainAppPage.this,  
                IndividualProduct.class);
                productIntent.putExtra("product", shoppingItems.get(i));
                startActivity(productIntent);
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is 
        getMenuInflater().inflate(R.menu.menu_main_app_page, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.logoutItem) {
            FirebaseAuth.getInstance().signOut();
            startActivity(new Intent(getApplicationContext(), 
            OpenScreen.class));
            finish();
        }

        return super.onOptionsItemSelected(item);
    }

    // For exiting the application
    @Override
    public void onBackPressed() {
        if (exit) {
            finish();
        } else {
            Snackbar.make(findViewById(R.id.main_content), "Press back  
            again to exit", Snackbar.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 2000);
        }
    }

    public static ArrayList<ShoppingItem> getAllItems(DataSnapshot 
     dataSnapshot){

        ArrayList<ShoppingItem> items  = new ArrayList<ShoppingItem>();

        for (DataSnapshot item : dataSnapshot.getChildren()) {

            items.add(new ShoppingItem(

           Integer.valueOf(item.child("productID").getValue().toString()),
                    item.child("name").getValue().toString(),
                    item.child("type").getValue().toString(),
                    item.child("description").getValue().toString(),

           Integer.valueOf(item.child("price").getValue().toString()),

           Integer.valueOf(item.child("quantity").getValue().toString())
            ));

        }

        return items;
    }

}

2 个答案:

答案 0 :(得分:0)

你可以查看与shoppingItems列表大小相同的ShoppingListAdapter setSize()

答案 1 :(得分:0)

onDataChange()方法中,尝试添加runOnUiThread。在新的Runnable中包含适配器代码。