如何从Firebase数据库读取数据,并使用ArrayAdapter在ListView中显示多个字段。

huangapple go评论165阅读模式
英文:

How to Read Data from Firebase Database and Display Multiple Fields in ListView with ArrayAdapter

问题

以下是你提供的代码部分的翻译:

  1. public class SearchModel {
  2. public String make;
  3. private String model;
  4. private String stock;
  5. public SearchModel() {}
  6. public String getMake() {
  7. return this.make;
  8. }
  9. public void setMake(String make) {
  10. this.make = make;
  11. }
  12. public String getModel() {
  13. return model;
  14. }
  15. public void setModel(String model) {
  16. this.model = model;
  17. }
  18. public String getStock() {
  19. return stock;
  20. }
  21. public void setStock(String stock) {
  22. this.stock = stock;
  23. }
  24. }
  1. public class MainActivity extends AppCompatActivity {
  2. private DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child("user1");
  3. private ListView mListView;
  4. private TextView tv_make;
  5. private TextView tv_model;
  6. private TextView tv_stock;
  7. private ArrayList<String> list = new ArrayList<>();
  8. private ArrayAdapter<String> adapter;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13. Toolbar toolbar = findViewById(R.id.toolbar);
  14. setSupportActionBar(toolbar);
  15. tv_make = (TextView) findViewById(R.id.tv_list_item_make);
  16. tv_model = (TextView) findViewById(R.id.tv_list_item_model);
  17. tv_stock = (TextView) findViewById(R.id.tv_list_item_stock);
  18. databaseReference.addChildEventListener(new ChildEventListener() {
  19. @Override
  20. public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  21. String value = snapshot.child("make").getValue(String.class);
  22. list.add(value);
  23. mListView = (ListView) findViewById(R.id.lv_searches);
  24. adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
  25. mListView.setAdapter(adapter);
  26. }
  27. @Override
  28. public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  29. }
  30. @Override
  31. public void onChildRemoved(@NonNull DataSnapshot snapshot) {
  32. }
  33. @Override
  34. public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  35. }
  36. @Override
  37. public void onCancelled(@NonNull DatabaseError error) {
  38. }
  39. });
  40. FloatingActionButton fab = findViewById(R.id.fab);
  41. fab.setOnClickListener(new View.OnClickListener() {
  42. @Override
  43. public void onClick(View view) {
  44. Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
  45. .setAction("Action", null).show();
  46. }
  47. });
  48. }
  49. }
  1. <!-- content.main.xml -->
  2. <ListView
  3. android:id="@+id/lv_searches"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent">
  6. </ListView>
  1. <!-- list_item.xml -->
  2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="100dp"
  5. xmlns:app="http://schemas.android.com/apk/res-auto"
  6. android:padding="10dp">
  7. <TextView
  8. android:id="@+id/tv_list_item_make"
  9. android:layout_width="wrap_content"
  10. android:layout_height="50dp"
  11. app:layout_constraintLeft_toLeftOf="parent"
  12. app:layout_constraintTop_toTopOf="parent" />
  13. <TextView
  14. android:id="@+id/tv_list_item_model"
  15. android:layout_width="wrap_content"
  16. android:layout_height="40dp"
  17. app:layout_constraintLeft_toLeftOf="parent"
  18. app:layout_constraintBottom_toBottomOf="parent" />
  19. <TextView
  20. android:id="@+id/tv_list_item_stock"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. app:layout_constraintRight_toRightOf="parent"
  24. app:layout_constraintTop_toTopOf="parent"
  25. app:layout_constraintBottom_toBottomOf="parent" />
  26. </androidx.constraintlayout.widget.ConstraintLayout>

以上是你提供的代码部分的翻译内容。如有问题请随时提问。

英文:

I have spent the better half of the day trying to figure out how to read data from my firebase database and display multiple fields in a ListView via an ArrayAdapter. After finally getting my ListView to display one piece of data in one textview, I am stuck trying to display two other fields.

In my MainActivity class I used the android.R.layout.simple_list_item_1 in the Adapter constructor because I was told that the textViewResourceID argument must only contain one TextView. So to reiterate my problem: I can not figure out how to display multiple fields with an array adapter. This app currently only displays the make field. Thanks so much in advance, I only started android development about a week ago! Here is my code below:

SearchModel.java

  1. public class SearchModel {
  2. public String make;
  3. private String model;
  4. private String stock;
  5. public SearchModel() {}
  6. public String getMake() {
  7. return this.make;
  8. }
  9. public void setMake(String make) {
  10. this.make = make;
  11. }
  12. public String getModel() {
  13. return model;
  14. }
  15. public void setModel(String model) {
  16. this.model = model;
  17. }
  18. public String getStock() {
  19. return stock;
  20. }
  21. public void setStock(String stock) {
  22. this.stock = stock;
  23. }
  24. }

MainActivity.java

(I omitted the irrelevant bottom section of the class after onCreate())

  1. public class MainActivity extends AppCompatActivity {
  2. private DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(&quot;users&quot;).child(&quot;user1&quot;);
  3. private ListView mListView;
  4. private TextView tv_make;
  5. private TextView tv_model;
  6. private TextView tv_stock;
  7. private ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();
  8. private ArrayAdapter&lt;String&gt; adapter;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13. Toolbar toolbar = findViewById(R.id.toolbar);
  14. setSupportActionBar(toolbar);
  15. tv_make = (TextView) findViewById(R.id.tv_list_item_make);
  16. tv_model = (TextView) findViewById(R.id.tv_list_item_model);
  17. tv_stock = (TextView) findViewById(R.id.tv_list_item_stock);
  18. databaseReference.addChildEventListener(new ChildEventListener() {
  19. @Override
  20. public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  21. String value = snapshot.child(&quot;make&quot;).getValue(String.class);
  22. list.add(value);
  23. mListView = (ListView) findViewById(R.id.lv_searches);
  24. adapter = new ArrayAdapter&lt;&gt;(getApplicationContext(), android.R.layout.simple_list_item_1, list);
  25. mListView.setAdapter(adapter);
  26. }
  27. @Override
  28. public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  29. }
  30. @Override
  31. public void onChildRemoved(@NonNull DataSnapshot snapshot) {
  32. }
  33. @Override
  34. public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  35. }
  36. @Override
  37. public void onCancelled(@NonNull DatabaseError error) {
  38. }
  39. });
  40. FloatingActionButton fab = findViewById(R.id.fab);
  41. fab.setOnClickListener(new View.OnClickListener() {
  42. @Override
  43. public void onClick(View view) {
  44. Snackbar.make(view, &quot;Replace with your own action&quot;, Snackbar.LENGTH_LONG)
  45. .setAction(&quot;Action&quot;, null).show();
  46. }
  47. });
  48. }

Here is the ListView in content.main.xml:

  1. &lt;ListView
  2. android:id=&quot;@+id/lv_searches&quot;
  3. android:layout_width=&quot;match_parent&quot;
  4. android:layout_height=&quot;match_parent&quot;&gt;
  5. &lt;/ListView&gt;

And here is the list_item.xml which is supposed to sit inside my ListView. This is where I would like to display the three String values (make, model, stock) in an instance of SearchModel.java.

  1. &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
  2. android:layout_width=&quot;match_parent&quot;
  3. android:layout_height=&quot;100dp&quot;
  4. xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
  5. android:padding=&quot;10dp&quot;&gt;
  6. &lt;TextView
  7. android:id=&quot;@+id/tv_list_item_make&quot;
  8. android:layout_width=&quot;wrap_content&quot;
  9. android:layout_height=&quot;50dp&quot;
  10. app:layout_constraintLeft_toLeftOf=&quot;parent&quot;
  11. app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
  12. &lt;TextView
  13. android:id=&quot;@+id/tv_list_item_model&quot;
  14. android:layout_width=&quot;wrap_content&quot;
  15. android:layout_height=&quot;40dp&quot;
  16. app:layout_constraintLeft_toLeftOf=&quot;parent&quot;
  17. app:layout_constraintBottom_toBottomOf=&quot;parent&quot; /&gt;
  18. &lt;TextView
  19. android:id=&quot;@+id/tv_list_item_stock&quot;
  20. android:layout_width=&quot;wrap_content&quot;
  21. android:layout_height=&quot;wrap_content&quot;
  22. app:layout_constraintRight_toRightOf=&quot;parent&quot;
  23. app:layout_constraintTop_toTopOf=&quot;parent&quot;
  24. app:layout_constraintBottom_toBottomOf=&quot;parent&quot; /&gt;
  25. &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

This is my firebase database layout: 如何从Firebase数据库读取数据,并使用ArrayAdapter在ListView中显示多个字段。

答案1

得分: 0

以下是翻译好的部分:

  1. public class CustomAdapter extends BaseAdapter {
  2. private static ArrayList<SearchModel> searchArrayList;
  3. private LayoutInflater mInflater;
  4. private Context mContext;
  5. private int lastPosition;
  6. /**
  7. * Holds elements in a view
  8. */
  9. static class ViewHolder {
  10. TextView make;
  11. TextView model;
  12. TextView stock;
  13. }
  14. public CustomAdapter(Context context, ArrayList<SearchModel> results) {
  15. searchArrayList = results;
  16. mContext = context;
  17. mInflater = LayoutInflater.from(context);
  18. }
  19. @Override
  20. public int getCount() {
  21. return searchArrayList.size();
  22. }
  23. @Override
  24. public Object getItem(int position) {
  25. return searchArrayList.get(position);
  26. }
  27. @Override
  28. public long getItemId(int position) {
  29. return position;
  30. }
  31. @Override
  32. public View getView(int position, View convertView, ViewGroup parent) {
  33. String make = searchArrayList.get(position).getMake();
  34. String model = searchArrayList.get(position).getModel();
  35. String stock = searchArrayList.get(position).getStock();
  36. final View result;
  37. ViewHolder holder;
  38. if (convertView == null) {
  39. LayoutInflater inflater = LayoutInflater.from(mContext);
  40. convertView = inflater.inflate(R.layout.list_item, parent, false);
  41. holder = new ViewHolder();
  42. holder.make = (TextView) convertView.findViewById(R.id.tv_list_item_make);
  43. holder.model = (TextView) convertView.findViewById(R.id.tv_list_item_model);
  44. holder.stock = (TextView) convertView.findViewById(R.id.tv_list_item_stock);
  45. result = convertView;
  46. convertView.setTag(holder);
  47. } else {
  48. holder = (ViewHolder) convertView.getTag();
  49. result = convertView;
  50. }
  51. Animation animation = AnimationUtils.loadAnimation(mContext,
  52. (position > lastPosition) ? R.anim.load_down_anim : R.anim.load_up_anim);
  53. result.startAnimation(animation);
  54. lastPosition = position;
  55. holder.make.setText(make);
  56. holder.model.setText(model);
  57. holder.stock.setText(stock);
  58. return convertView;
  59. }
  60. }
  1. protected void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.activity_main);
  4. Toolbar toolbar = findViewById(R.id.toolbar);
  5. setSupportActionBar(toolbar);
  6. databaseReference.addChildEventListener(new ChildEventListener() {
  7. @Override
  8. public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  9. String make = snapshot.child("make").getValue(String.class);
  10. String model = snapshot.child("model").getValue(String.class);
  11. String stock = snapshot.child("stock").getValue(Long.class).toString();
  12. SearchModel searchModel = new SearchModel(make, model, stock);
  13. searchList.add(searchModel);
  14. CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), searchList);
  15. mListView = (ListView) findViewById(R.id.lv_searches);
  16. mListView.setAdapter(customAdapter);
  17. }
  18. @Override
  19. public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  20. }
  21. @Override
  22. public void onChildRemoved(@NonNull DataSnapshot snapshot) {
  23. }
  24. @Override
  25. public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  26. }
  27. @Override
  28. public void onCancelled(@NonNull DatabaseError error) {
  29. }
  30. });
  31. }
英文:

after two days of being stuck I was able to answer my own question! Hopefully this will help future beginners stuck trying to display a custom view within an ArrayAdapter. Basically, I created a custom ArrayAdapter class which could hold three TextViews inside of it.

I am in no means an expert and will not be able to explain this as well as others, so instead, I will paste a link to the two video tutorials that I followed and had success with.

Android Beginner Tutorial #8 - Custom ListView Adapter For Displaying Multiple Columns
https://www.youtube.com/watch?v=E6vE8fqQPTE&amp;t=392s

Android Beginner Tutorial #9 - Custom ListView Adapter [With Loading Animation]
https://www.youtube.com/watch?v=SApBLHIpH8A

Here is my updated code below:

CustomAdapter.java

  1. public class CustomAdapter extends BaseAdapter {
  2. private static ArrayList&lt;SearchModel&gt; searchArrayList;
  3. private LayoutInflater mInflater;
  4. private Context mContext;
  5. private int lastPosition;
  6. /**
  7. * Holds elements in a view
  8. */
  9. static class ViewHolder {
  10. TextView make;
  11. TextView model;
  12. TextView stock;
  13. }
  14. public CustomAdapter(Context context, ArrayList&lt;SearchModel&gt; results) {
  15. searchArrayList = results;
  16. mContext = context;
  17. mInflater = LayoutInflater.from(context);
  18. }
  19. @Override
  20. public int getCount() {
  21. return searchArrayList.size();
  22. }
  23. @Override
  24. public Object getItem(int position) {
  25. return searchArrayList.get(position);
  26. }
  27. @Override
  28. public long getItemId(int position) {
  29. return position;
  30. }
  31. @Override
  32. public View getView(int position, View convertView, ViewGroup parent) {
  33. String make = searchArrayList.get(position).getMake();
  34. String model = searchArrayList.get(position).getModel();
  35. String stock = searchArrayList.get(position).getStock();
  36. final View result;
  37. ViewHolder holder;
  38. if (convertView == null) {
  39. LayoutInflater inflater = LayoutInflater.from(mContext);
  40. convertView = inflater.inflate(R.layout.list_item, parent, false);
  41. holder = new ViewHolder();
  42. holder.make = (TextView) convertView.findViewById(R.id.tv_list_item_make);
  43. holder.model = (TextView) convertView.findViewById(R.id.tv_list_item_model);
  44. holder.stock = (TextView) convertView.findViewById(R.id.tv_list_item_stock);
  45. result = convertView;
  46. convertView.setTag(holder);
  47. } else {
  48. holder = (ViewHolder) convertView.getTag();
  49. result = convertView;
  50. }
  51. Animation animation = AnimationUtils.loadAnimation(mContext,
  52. (position &gt; lastPosition) ? R.anim.load_down_anim : R.anim.load_up_anim);
  53. result.startAnimation(animation);
  54. lastPosition = position;
  55. holder.make.setText(make);
  56. holder.model.setText(model);
  57. holder.stock.setText(stock);
  58. return convertView;
  59. }
  60. }

MainActivity.java (Only the onCreate method)

  1. protected void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.activity_main);
  4. Toolbar toolbar = findViewById(R.id.toolbar);
  5. setSupportActionBar(toolbar);
  6. databaseReference.addChildEventListener(new ChildEventListener() {
  7. @Override
  8. public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  9. String make = snapshot.child(&quot;make&quot;).getValue(String.class);
  10. String model = snapshot.child(&quot;model&quot;).getValue(String.class);
  11. String stock = snapshot.child(&quot;stock&quot;).getValue(Long.class).toString();
  12. SearchModel searchModel = new SearchModel(make, model, stock);
  13. searchList.add(searchModel);
  14. CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), searchList);
  15. mListView = (ListView) findViewById(R.id.lv_searches);
  16. mListView.setAdapter(customAdapter);
  17. }
  18. @Override
  19. public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  20. }
  21. @Override
  22. public void onChildRemoved(@NonNull DataSnapshot snapshot) {
  23. }
  24. @Override
  25. public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
  26. }
  27. @Override
  28. public void onCancelled(@NonNull DatabaseError error) {
  29. }
  30. });

huangapple
  • 本文由 发表于 2020年9月21日 00:24:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63981173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定