-1

BusinessForSaleActivity

public class BusinessForSaleActivity extends AppCompatActivity {

    DatabaseReference databaseLinks;
    ListView listViewBusinessForSale;
    Button readMore;
    ArrayList<BusinessForSale> list;
    //CardView cardView;

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

        listViewBusinessForSale = (ListView)findViewById(R.id.ListViewBusinessForSale);

        list = new ArrayList<>();

        databaseLinks = FirebaseDatabase.getInstance().getReference("BusinessList");

        databaseLinks.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                list.clear();
                try{
                    for(DataSnapshot businessSnapshot : dataSnapshot.getChildren()){
                        BusinessForSale b = businessSnapshot.getValue(BusinessForSale.class);

                        list.add(b);
                    }
                }
                catch (Exception ex){
                    Log.e("Error Descr:",ex.getMessage());
                }


                BusinessForSaleList adapter=new BusinessForSaleList(BusinessForSaleActivity.this,list);
                listViewBusinessForSale.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(BusinessForSaleActivity.this,"Something is wrong",Toast.LENGTH_SHORT).show();
            }
        });


    }
}

BusinessForSaleList================(Adapter class)============

public class BusinessForSaleList extends ArrayAdapter<BusinessForSale> {

        private Activity context;
        private List<BusinessForSale> businessForSaleList;

        public BusinessForSaleList(Activity context,List<BusinessForSale> businessForSaleList){
            //super(context,R.layout.list_layout,businessForSaleList);
            super(context,R.layout.list,businessForSaleList);
            this.context=context;
            this.businessForSaleList=businessForSaleList;
        }

        @NonNull
        @Override
        public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            LayoutInflater inflater=context.getLayoutInflater();

            View listViewItem=inflater.inflate(R.layout.list,null,true);

            ImageView imgBuiness=(ImageView)listViewItem.findViewById(R.id.imgViewBusiness);
            TextView txtTitle = (TextView)listViewItem.findViewById(R.id.txtViewTitle);
            TextView txtType = (TextView)listViewItem.findViewById(R.id.txtViewType);
            TextView txtDescr = (TextView)listViewItem.findViewById(R.id.txtViewDescr);
            Button btnReadMore = (Button)convertView.findViewById(R.id.buttonReadMore);

            BusinessForSale businessForSale = businessForSaleList.get(position);
            Picasso.get().load(businessForSale.getImage().toString()).into(imgBuiness);
            txtTitle.setText(businessForSale.getBusiness_Title());
            txtType.setText(businessForSale.getBusiness_Type());
            txtDescr.setText(businessForSale.getDescription());


            return listViewItem;
        }
    }

BusinessForSaleActivity.xml==============================================

<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BusinessForSaleActivity">

    <ListView
        android:id="@+id/ListViewBusinessForSale"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:footerDividersEnabled="false"
        />

</RelativeLayout>

List.xml================================================================

[<RelativeLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e0e0e0">

    <android.support.v7.widget.CardView
        android:id="@+id/cardBusinessForSale"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        app:cardCornerRadius="8dp"
        app:cardElevation="4dp">
        <LinearLayout
            android:id="@+id/L1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imgViewBusiness"
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:layout_margin="4dp"
                android:scaleType="centerCrop"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="16dp">
                <TextView
                    android:id="@+id/txtViewTitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="TextView"
                    android:layout_marginBottom="8dp"
                    android:textColor="#000"
                    android:textSize="18sp"/>
                <TextView
                    android:id="@+id/txtViewType"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="TextView"
                    android:textColor="#555" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                android:orientation="vertical">
                <TextView
                    android:id="@+id/txtViewDescr"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="TextView"
                    android:maxLines="3"
                    android:textSize="14sp" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp">
                <Button
                    android:id="@+id/buttonReadMore"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:theme="@style/PrimaryFlatButton"
                    android:text="Read More" />

                <Button
                    android:id="@+id/buttonAddToFvrt"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:theme="@style/PrimaryFlatButton"
                    android:text="Add to Favorites" />
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>



</RelativeLayout>][1]

I want to redirect to new Activity on "ReadMore" button click. I am fetching firebase data into a listview using list.xml layout.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sandy
  • 3
  • 1
  • 1
    use onclickListener on readMoreButton https://developer.android.com/reference/android/view/View.OnClickListener – Bunny Oct 22 '18 at 08:54
  • If you want at some point to try [Cloud Firestore](https://firebase.google.com/docs/firestore/), **[this](https://stackoverflow.com/questions/50592325/is-there-a-way-to-paginate-queries-by-combining-query-cursors-using-firestorerec/50692959)** is a recommended way in which you can load items in smaller chunks using an `ArrayAdapter` on button click. – Alex Mamo Oct 24 '18 at 09:16

1 Answers1

-1

When you're using a list and need to handle click on an item or an element contained by it, the common way is to set a listener in the getView() method or onBind() method, depending on the adepter you're using.

In this case, in your "getView()" method, after referenced your button you need to set a listener on it that retrieve the position of the item that contains it and open the relative activity (or the unique activity setting up the correct value). You can do it by retrieving the parent position of its parent, but it's sounds so complicated.

The best and common way is to assign to the button a tag that is the position assigned to its parent by the getView() method in this way:

 @NonNull
 @Override
 public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater=context.getLayoutInflater();
    View listViewItem=inflater.inflate(R.layout.list,null,true);
    ...
    Button btnReadMore = (Button)convertView.findViewById(R.id.buttonReadMore);
    btnReadMore.setTag(position + "");
}

After that, every button contains the position of the item in the list. Now, assign the listener to the button and retrieve the correct position:

btnReadMore.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view,....){
    Button btnReadMore = (Button) view; //This cast is unless, it's here only for more understanding
    String positionString = btnReadMore.getTag();
    int position = Integer.parseInt(positionString);
    BusinessForSale correctItem = BusinessForSaleList.get(position);
    //here start activity you need.
}});

Hope this help! :D

  • "I want to redirect to new Activity on "ReadMore" button click. I am fetching firebase data into a listview using list.xml layout." This is what the question states at the end. – PradyumanDixit Oct 22 '18 at 09:20
  • Please, we are a community. Do not behave like a child because I downvote your answer, even downvoting mine. Your was incorrect and useless. – Devster - Angelo Cimino Oct 22 '18 at 09:25
  • The question doesn't very clean but if you are a developer, you can easy understand what user want asks. – Devster - Angelo Cimino Oct 22 '18 at 09:26
  • Maybe you're right, but from 15 years of coding, I have learned that answering and thinking about only what's given in the question is the most precise thing to do. – PradyumanDixit Oct 22 '18 at 09:33
  • I did NOT downvote your answer and neither did I know, you did. – PradyumanDixit Oct 22 '18 at 09:33
  • I just commented on your answer because I felt that I should delete mine. – PradyumanDixit Oct 22 '18 at 09:36
  • I not said you haven't experience.. sorry if you think it.. I just said that in developer mind the question can be clean despite it was unclean. And if you didn't downvoted my answer, please sorry me. I think that was you. – Devster - Angelo Cimino Oct 22 '18 at 09:52
  • No problem @Cyan I didn't mean that you said I don't have experience, Don't worry, mis-communications are common when you're typing things. Cheers! – PradyumanDixit Oct 22 '18 at 09:54
  • @CyanDeveloper-AngeloCimino : I am getting exception at Line Button btnReadMore = (Button)convertView.findViewById(R.id.buttonReadMore); Exception: Can not find local variable 'Last NonConfigurationInstances'. IF I AM USING LISTVIEWITEM instead of CONVERTVIEW, Its woking. – sandy Oct 25 '18 at 11:20
  • @sandy yes, your code has mistake.. if you look, you have instantiate a "item" named **listViewItem** but you're trying access to button by **convertView**. The right thing is to reuse the convert view correctly and reference only it. Make instead this: `if(convertView == null) convertView = inflater.inflate(R.layout.list,null,true); //then, access always to convertView reference` – Devster - Angelo Cimino Oct 29 '18 at 18:15
  • @CyanDeveloper-AngeloCimino thanks, man. It was really helpful. – sandy Nov 01 '18 at 00:22