简体   繁体   中英

How can I get the data for each item in the listView using firebase?

I have made an app that gets data from the Firebase and I want when I click on the listView it shows me the data for each item but the problem is that when I click on an item in the listView , the displayInformation file opens but displays the last data uploaded to the firebase and does not display the data for each item in the ListView .

This is Firebase data:

{
  "List" : {
    "-Mmi2obH5ji14w82qUhR" : {
      "age" : 22,
      "description" : "blah",
      "firstName" : "John",
      "lastName" : "Michael"
    },
    "-MmiDkIXb_vLqET8BmKX" : {
      "age" : 24,
      "description" : "blah",
      "firstName" : "Leonardo",
      "lastName" : ""
    },
    "-MmnL1PYbcyW9VJPytr3" : {
      "age" : 19,
      "description" : "blah",
      "firstName" : "Mohamed",
      "lastName" : ""
    }
  }
}

These are My codes:

this is code for MainActivity :

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int LIST_APP_LOADER = 0;

    ArrayList<Informatin> listItem;
    ListView listView;
    listAppAdapter adapter;

    DatabaseReference reference;

    private String firstName;
    private String lastName;
    private String age;
    private String description;

    ArrayList<Informatin> mInformation;

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

        listItem = new ArrayList<>();
        listView = findViewById(R.id.list);

        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent(MainActivity.this, DisplayInformations.class);
            intent.putExtra("firstName", firstName);
            intent.putExtra("lastName", lastName);
            intent.putExtra("age", age);
            intent.putExtra("description", description);

            startActivity(intent);
        });

        LoaderManager.getInstance(this).initLoader(LIST_APP_LOADER, null, this);

        mInformation = new ArrayList<>();

        adapter = new listAppAdapter(this, mInformation);
        listView.setAdapter(adapter);

        reference = FirebaseDatabase.getInstance().getReference("List");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mInformation.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    firstName = snapshot.child("firstName").getValue().toString();
                    lastName = snapshot.child("lastName").getValue().toString();
                    age = snapshot.child("age").getValue().toString();
                    description = snapshot.child("description").getValue().toString();

                    Informatin informatin = new Informatin(firstName, lastName, description, age);
                    mInformation.add(informatin);

                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_main_screen, menu);

        return true;
    }

    @NonNull
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return null;
    }

    @Override
    public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onLoaderReset(@NonNull Loader<Cursor> loader) {
        return null;
    }
}
this codes for `displayInformation` :

public class DisplayInformations extends AppCompatActivity implements LoaderManager.LoaderCallbacks {

private Uri mCurrentPersonUri;

private TextView mNameDisplay;
private TextView mAgeDisplay;
private TextView mDescriptionDisplay;
private ImageView mImageTopBar;
private Toolbar mToolbar;

private String firstName;
private String lastName;
private String age;
private String description;

private static final int EXISTING_LIST_APP_LOADER = 0;

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

    Intent intent = getIntent();
    firstName = intent.getStringExtra("firstName");
    lastName = intent.getStringExtra("lastName");
    age = intent.getStringExtra("age");
    description = intent.getStringExtra("description");
    mCurrentPersonUri = intent.getData();

    loadListDetails();

    mNameDisplay = findViewById(R.id.name_display);
    mAgeDisplay = findViewById(R.id.age_display);
    mDescriptionDisplay = findViewById(R.id.description_display);
    mImageTopBar = findViewById(R.id.image_top_bar);

    mToolbar = findViewById(R.id.main_toolbar);
    LoaderManager.getInstance(this).initLoader(EXISTING_LIST_APP_LOADER, null, this);
}

private void loadListDetails() {
            String name = firstName + " " + lastName;

            int ageInt = Integer.parseInt(age);
            setTitle(name);
            mNameDisplay.setText(name);
            if (age.equals("1")) {
                String ageDisplay = getString(R.string.age) + ": " + getString(R.string.one_year);
                mAgeDisplay.setText(ageDisplay);
            } else if (age.equals("2")) {
                String ageDisplay = getString(R.string.age) + ": " + getString(R.string.two_year);
                mAgeDisplay.setText(ageDisplay);
            } else if (ageInt >= 3 && ageInt <= 10) {
                String ageDisplay = getString(R.string.age) + ": " + age + getString(R.string.years);
                mAgeDisplay.setText(ageDisplay);
            } else if (ageInt >= 11) {
                String ageDisplay = getString(R.string.age) + ": " + age + getString(R.string.year);
                mAgeDisplay.setText(ageDisplay);
            }
            mDescriptionDisplay.setText(description);
        }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.menu_display_informations, menu);
    return true;
}

@NonNull
@Override
public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
    return null;
}

@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) {
    if (cursor == null || cursor.getCount() < 1) {
        return;
    }
    if (cursor.moveToFirst()) {

        loadListDetails();

        setSupportActionBar(mToolbar);

    }
}

@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
    mNameDisplay.setText("");
    mAgeDisplay.setText("");
    mDescriptionDisplay.setText("");
}

}

Data is loaded from Firebase asynchronous. This means that it takes some time until it becomes available in your app. Setting those variables as global doesn't solve the problem. What you need to do, is to get data from the adapter as an object of type Informatin and then add it to your Intent object. Assuming you already have getters for each field, please use the following lines of code:

listView.setOnItemClickListener((parent, view, position, id) -> {
    Informatin informatin = (Informatin) parent.getAdapter().getItem(position);
    Intent intent = new Intent(MainActivity.this, DisplayInformations.class);
    intent.putExtra("firstName", informatin.getFirstName());
    intent.putExtra("lastName", informatin.getLastName());
    intent.putExtra("age", informatin.getAge());
    intent.putExtra("description", informatin.getDescription());
    startActivity(intent);
});

Or you can add the entire Informatin object to the Intent, and not each field separately. To get it back, simply use Intent#getSerializableExtra() method.

Please also note that your age field in the database is a number and not a String. So please change:

private String age;

Into:

private long age;

And:

age = snapshot.child("age").getValue().toString();

Into:

age = snapshot.child("age").getValue(Long.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM