如何将数据从 Firebase 检索到 ListView(使用自定义数组适配器)

2023-12-21

我目前设计了一个地点浏览器应用程序,其中在列表视图中显示 3 个项目。当用户登录时,他会找到一个类别列表。单击某个类别后,将显示该类别下的地点列表。我已将该应用程序与 Firebase 关联。

现在,我想显示 2 项(placeTitle and placeDesc)从存储在 firebase 中的数据进入列表视图。我无法将数据加载到ListView.

购物活动:

public class ShoppingActivity extends AppCompatActivity {

    DatabaseReference databaseReference;
    Place shopping;
    ListView listView;
    ArrayList<Place> list;
    ArrayAdapter <Place> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.place_list);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        //For accessing firebase data and load into Listview
        list = new ArrayList<>();
        shopping = new Place();
        listView = findViewById(R.id.listView); //listview
        adapter = new ArrayAdapter<>(this, R.layout.custom_list_item, list);
        final PlaceAdapter placeAdapter = new PlaceAdapter(this, list, R.color.category_shopping);
        databaseReference = FirebaseDatabase.getInstance().getReference("PlaceDetails"); //database reference
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot ds: snapshot.getChildren()){

                    Place shopping = ds.getValue(Place.class);

                    if (shopping != null) {

                        list.add(new Place(shopping.getPlaceTitle(),shopping.getPlaceTitle()));
                    }
                }


                listView.setAdapter(placeAdapter);
            }

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

            }
        });


        //Create a new array list of Places
//        final ArrayList<Place> shopping = new ArrayList<>();


//        Place p = new Place("State Museum","Ambari Guwahati");
//        culture.add(p);

        //create a new object for Place and add all place details
//        shopping.add(new Place("Fancy Bazar Daily Market", "Fancy Bazar Guwahati"));
//        shopping.add(new Place("Pentaloons", "Sixmile Guwahati"));
//        shopping.add(new Place("Guwahati Central", "Zoo Road Guwahati"));
//        shopping.add(new Place("Eastrends (Hub)", "Bhangagarh Guwahati"));
//        shopping.add(new Place("City Centre", "G.S. Road Guwahati"));
//        shopping.add(new Place("Central Mall", "G.S. Road Guwahati"));



//        ArrayAdapter<Place> itemsAdapter = new ArrayAdapter<Place>(this, R.layout.custom_list_item, shopping);
//
//        PlaceAdapter placeAdapter = new PlaceAdapter(this, shopping, R.color.category_shopping);
//
//        ListView listView = findViewById(R.id.listView);
//
//        listView.setAdapter(placeAdapter);


        //Displaying the listview items
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(CultureActivity.this, "ListView Item is clicked", Toast.LENGTH_SHORT).show();

                //For opening a new view in google maps
                // Get the {@link Word} object at the given position the user clicked on
                Place place = list.get(position);

                // Create a Uri from an intent string. Use the result to create an Intent to open the place in Google Maps
                Uri gmmIntentUri = Uri.parse("geo:0,0?q=" + Uri.encode(place.getPlaceTitle()));


                //Uri gmmIntentUri = Uri.parse("geo:0,0?place");

                //The below Intent will request turn-by-turn navigation to the Place clicked
                //Uri gmmIntentUri = Uri.parse("google.navigation:q="+Uri.encode(place.getPlaceTitle()));

                // Create an Intent from gmmIntentUri. Set the action to ACTION_VIEW
                Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                // Make the Intent explicit by setting the Google Maps package
                mapIntent.setPackage("com.google.android.apps.maps");

                // Attempt to start an activity that can handle the Intent
                if (mapIntent.resolveActivity(getPackageManager()) != null) {
                    startActivity(mapIntent);

                }
            }
        });
    }
}

放置对象

package android.example.com.knowguwahaticity;

import android.content.Context;

public class Place {


    //Declare the state of the Place class
    //Place Title
    private String mPlaceTitle;

    //Place Desc
    private String mPlaceDesc;

    // Drawable resource ID
    private int mImageResourceId = NO_IMAGE_PROVIDED;

    //Drawable resource ID
    private int mPlaceResourceId;

    //Image visibility
    private static final int NO_IMAGE_PROVIDED = -1 ;


    //Construct the custom class Place


    public Place() {
    }

    public Place(String placeTitle, String placeDesc, int imageResourceId) {
        mPlaceTitle = placeTitle;
        mPlaceDesc = placeDesc;
        mImageResourceId = imageResourceId;
    }

    public Place(String placeTitle, String placeDesc) {
        mPlaceTitle = placeTitle;
        mPlaceDesc = placeDesc;
    }

    //declare the methods to access the states of the class
    //get the Title of the place
    public String getPlaceTitle() {
        return mPlaceTitle;
    }

    //get the Address of the place
    public String getPlaceDesc() {
        return mPlaceDesc;
    }

    //get the image resource id of the image
    public int getImageResourceId() {
        return mImageResourceId;
    }

//    //get the map resource id of the image
//    public int getPlaceResourceId() {
//        return mPlaceResourceId;
//    }

    //check whether the object has an image
    public boolean hasImage(){
        return mImageResourceId != NO_IMAGE_PROVIDED;
    }
}

自定义列表视图 XML

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:minHeight="@dimen/list_item_height"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/place_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:src="@drawable/star"
        />

    <LinearLayout

        android:id="@+id/text_container"
        android:layout_width="0dp"
        android:layout_height="@dimen/list_item_height"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="16dp">

        <TextView
            android:id="@+id/title_text_view"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="@android:color/white"
            android:gravity="bottom"
            android:textSize="18sp"
            android:textStyle="bold"
            tools:text="Title" />

        <TextView
            android:id="@+id/desc_text_view"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="@android:color/white"
            android:gravity="top|bottom"
            android:textSize="14sp"
            tools:text="Description" />

    </LinearLayout>
</LinearLayout>

PlaceAdapter.java

package android.example.com.knowguwahaticity;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.Set;

public class PlaceAdapter extends ArrayAdapter<Place> {

    /** Resource ID for the background color for this list of words */
    private int mColorResourceId;
    private Context mContext;

    public PlaceAdapter(Activity context, ArrayList<Place> places, int colorResourceId) {
        super(context, 0, places);
        mColorResourceId = colorResourceId;

    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View listItemView = convertView;

        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.custom_list_item, parent, false);
        }

        //get the position of the object at this position of the list
        Place currentPlace = getItem(position);

        //Find the textview in the custom_list_item.xml with id textView1 (Title of the Place)
        TextView TitleTextView = listItemView.findViewById(R.id.title_text_view);
        TitleTextView.setText(currentPlace.getPlaceTitle());


        //Find the textview in the custom_list_item.xml with id textView2 (Desc of the place)
        TextView DescTextView = listItemView.findViewById(R.id.desc_text_view);
        DescTextView.setText(currentPlace.getPlaceDesc());

        // Find the ImageView in the list_item.xml layout with the ID list_item_icon
        ImageView iconView = (ImageView) listItemView.findViewById(R.id.place_image_view);
        // Get the image resource ID from the current Place object and
        // set the image to iconView
        if(currentPlace.hasImage()) {

            iconView.setImageResource(currentPlace.getImageResourceId());

            //set image view as visible
            iconView.setVisibility(View.VISIBLE);
        }
        else {
            //set image view as GONE
            iconView.setVisibility(View.GONE);
        }

        // Find the ImageView in the list_item.xml layout with the ID list_item_icon
//        ImageView mapView = (ImageView) listItemView.findViewById(R.id.place_map_view);
//        // Get the image resource ID from the current Place object and
//        // set the image to iconView
//        mapView.setImageResource(currentPlace.getPlaceResourceId());

        /*Set OnClickListener on the mapView to open the location in map app*/
//        mapView.setTag(position);
//        mapView.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View view) {
//                Toast.makeText(mContext, "ImageView clicked for the row = "+view.getTag().toString(), Toast.LENGTH_SHORT).show();
//            }
//        });

        // Set the theme color for the list item
        View textContainer = listItemView.findViewById(R.id.text_container);
        // Find the color that the resource ID maps to
        int color = ContextCompat.getColor(getContext(), mColorResourceId);
        // Set the background color of the text container View
        textContainer.setBackgroundColor(color);


        return listItemView;
    }
}

您将看到“黑屏”,因为类中的属性名称确实not与数据库中的属性名称匹配。看,你有一个名为mPlaceTitle在你的Place类,而在数据库中被称为placeTitle这是not正确的。要解决这个问题,您只需更改类中所有属性的名称以匹配数据库中的名称,这些名称根据Java 命名约定 https://www.oracle.com/technetwork/java/codeconventions-135099.html关于变量。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将数据从 Firebase 检索到 ListView(使用自定义数组适配器) 的相关文章

  • Java 8 中函数式接口的使用

    这是来自的后续问题Java 8 中的 双冒号 运算符 https stackoverflow com questions 20001427 double colon operator in java 8其中 Java 允许您使用以下方式引用
  • Java 数组的最大维数

    出于好奇 在 Java 中数组可以有多少维 爪哇language不限制维数 但是JavaVM规范将维度数限制为 255 例如 以下代码将无法编译 class Main public static void main String args
  • 计算日期之间的天数差异

    在我的代码中 日期之间的差异是错误的 因为它应该是 38 天而不是 8 天 我该如何修复 package random04diferencadata import java text ParseException import java t
  • 如何在 Android NDK 中创建新的 NativeWindow 而无需 Android 操作系统源代码?

    我想编译一个 Android OpenGL 控制台应用程序 您可以直接从控制台启动 Android x86 运行 或者从 Android x86 GUI 内的 Android 终端应用程序运行 这个帖子 如何在 Android NDK 中创
  • 如何以编程方式启动 ssh 服务器 android,以及如何获取连接到设备的用户名和密码

    我正在开发像这样的应用程序sshdroid 我想在 Android 操作系统上打开 ssh 连接 并且我想从电脑连接应用程序 我使用了 JSCH lib 但是这个lib用于将android连接到pc 我的要求是pc到android 任何人都
  • Cloudfoundry:如何组合两个运行时

    cloundfoundry 有没有办法结合两个运行时环境 我正在将 NodeJS 应用程序部署到 IBM Bluemix 现在 我还希望能够执行独立的 jar 文件 但应用程序失败 APP 0 bin sh 1 java not found
  • Android Studio IDE 上的“文本/设计”选项卡缺少新的 Android 项目

    如何在创建新项目期间自动创建的 Activity main xml 文件的 src main res layout 文件夹中启用文本 设计选项卡 如果我右键单击并在所述文件夹上创建 xml 文件 则设计 文本选项卡存在 有什么建议吗 谢谢
  • Vimeo 视频在 Android 6 设备上停止播放

    我正在尝试在我的应用程序中播放 Vimeo 的视频 问题是在 Android 6 设备上 视频会在一定时间后停止播放 在 API 较低的设备上一切正常 时间取决于质量 对于下面提供的网址的视频 播放一定分钟 1 到 3 视频质量有多低 播放
  • Android - 如何更改 TimePicker 中的文本颜色?

    我正在使用 TimePicker 到 LinearLayout 中 背景颜色 黑色 但是 我看不到 TimePicker 中的数字 并且我需要在布局中将背景颜色设置为黑色 如何更改 TimePicker 中的 textColor 我已经尝试
  • 如何通过 Inno Setup for NetBeans 使用自定义 .iss 文件

    我将 Inno Setup 5 与 NetBeans 8 一起使用 并且我已经能够创建一个安装程序来安装该应用程序C users username local appname 但是我希望将其安装在C Programfiles 我如何在 Ne
  • 为什么java中的for-each循环中需要声明变量

    for 每个循环的通常形式是这样的 for Foo bar bars bar doThings 但如果我想保留 bar 直到循环结束 我可以not使用 foreach 循环 Foo bar null Syntax error on toke
  • 哪个集合更适合存储多维数组中的数据?

    我有一个multi dimensional array of string 我愿意将其转换为某种集合类型 以便我可以根据自己的意愿添加 删除和插入元素 在数组中 我无法删除特定位置的元素 我需要这样的集合 我可以在其中删除特定位置的数据 也
  • Android - 9 补丁

    我正在尝试使用 9 块图片创建一个新的微调器背景 我尝试了很多方法来获得完美的图像 但都失败了 s Here is my 9 patch 当我用Draw 9 patch模拟时 内容看起来不错 但是带有箭头的部分没有显示 或者当它显示时 这部
  • 直接使用从密钥库加载的 SecretKey 时,密钥用户未经过身份验证

    我正在尝试使用 Cipher 和在 KeyStore 中加载的 SecretKey 来加密数据 但总是收到此错误 导致 android security KeyStoreException 关键用户未经过身份验证 我尝试自己创建 Secre
  • FCM onMessageReceived 应用程序运行时返回空白消息和标题

    正如您在标题中所写 当应用程序关闭时 它运行良好 并且onMessageReceived获取消息正文和标题 但如果应用程序处于前台模式 运行模式 则可以发送通知 但没有消息和标题 请问该怎么办 代码 Override public void
  • 安卓的限制

    我需要构建一个应用程序 该应用程序拍摄相机图像并将其上传到网络 在网络上进行一些处理并返回真 假 我在这方面遇到了一些问题 希望得到澄清 1 我的应用程序有什么方法可以知道 Android 相机捕获的图像吗 我从这里明白了什么 Androi
  • 在android中跟踪FTP上传数据?

    我有一个运行 Android 的 FTP 系统 但我希望能够在上传时跟踪字节 这样我就可以在上传过程中更新进度条 安卓可以实现这个功能吗 现在 我正在使用org apache common net ftp我正在使用的代码如下 另外 我在 A
  • Android:解析 XML 数据的最佳解析器 [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我正在开发一个应用程序 其中我第一次要解析来自远程服务器的 xml 文件中的数据 但我无法选择哪个解析器是有效的或最适合解析的 因为我知道主要有
  • Android:如何检测手机设置中的语言已更改

    我如何检测我的手机语言是否已更改 例如 Facebook 应用程序将向我们宣布 please wait we preparing your language i used myString Locale getDefault getDisp
  • 当ScrollView滚动到底部时加载更多数据

    我有一个带有动态加载内容的滚动视图 有时可能会有很多内容 所以我想在用户滚动到底部时加载更多内容 我搜索了合适的方法 发现了两种 onScrollChanged and getScrollY 但我不知道如何将它用于我的目的 请给我一些建议

随机推荐