• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Products List Buttons. Only The Top Button Works?

superbrands

Lurker
Feb 18, 2017
1
0
Hello,

I'm new to Android Programming. I have a problem.

I have created a products list grabbed from my online shop using JSON method.

My codes are,

LatestProductsActivity.java

Java:
package com.bukausahaonline.tokoonline;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

public class LatestProductsActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVLatestProducts;
    private AdapterProductList mAdapter;

    public final static String EXTRA_MESSAGE = "com.bukausahaonline.tokoonline.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_latest_products);
        //Make call to AsyncTask
        new AsyncFetch().execute();
    }

    /** Called when the user clicks the Send button */
    public void goToCategoriesPage(View view) {
        Intent intent = new Intent(this, CategoriesPageActivity.class);
        startActivity(intent);
    }

    public void goToLatestPage(View view) {
        Intent intent = new Intent(this, LatestProductsActivity.class);
        startActivity(intent);
    }

    public void goToFeaturedPage(View view) {
        Intent intent = new Intent(this, FeaturedProductsActivity.class);
        startActivity(intent);
    }

    public void goToSpecialsPage(View view) {
        Intent intent = new Intent(this, SpecialProductsActivity.class);
        startActivity(intent);
    }

    public void goToBestsellersPage(View view) {
        Intent intent = new Intent(this, BestsellerProductsActivity.class);
        startActivity(intent);
    }

    public void goToProductPage(View view) {
        Intent intent = new Intent(LatestProductsActivity.this, ProductActivity.class);
        //TextView productId = (TextView) findViewById(R.id.productId);
        Button productId = (Button) findViewById(R.id.textType);

        String product_id = productId.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, product_id);
        startActivity(intent);
        //Intent intent = new Intent(this, ProductActivity.class);
        //startActivity(intent);
    }

    private class AsyncFetch extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(LatestProductsActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL("http://tokoonline.bukausahaonline.com/index.php?route=api/v1/get_latest_products&api_key=y8ycRVy1UI54kQy1k0nwmHCjr8FffsKJXJcEbB2VcNSgm7520cxHxLEGn6vxzaBABJKp1PuTaWZGMxaeCcA0v2UgLVynjzL18pyj1j1iA0wf5YUx2SYSmG7RzQielSdtGjxWqrJxsCXV1nA81lWW8WnsPIUkb03qWVeV5fSbjK4YiVqCP81ZeiC8zvIoFWHSFxKnjEWpIdRZiEDbY0MkRX6wGpwYYSyK3OthUBQ6leeVAHGQXe7Ftqgwg35K6m7b");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }


        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataProductList> data=new ArrayList<>();

            pdLoading.dismiss();
            try {

                //JSONArray jArray = new JSONArray(result);
                JSONObject jsonObj = new JSONObject(result);
                JSONArray jArray = jsonObj.getJSONArray("products");

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataProductList productData = new DataProductList();
                    productData.productId= json_data.getInt("product_id");
                    productData.productImage= json_data.getString("thumb");
                    productData.productName= json_data.getString("name");
                    productData.catName= json_data.getString("product_id");
                    if (json_data.getString("special").equals("false")) {
                        productData.productSpecial = null;
                    } else {
                        productData.productSpecial = json_data.getString("special");
                    }
                    productData.price= json_data.getString("price");
                    data.add(productData);
                }

                // Setup and Handover data to recyclerview
                mRVLatestProducts = (RecyclerView)findViewById(R.id.productList);
                mAdapter = new AdapterProductList(LatestProductsActivity.this, data);
                mRVLatestProducts.setAdapter(mAdapter);
                mRVLatestProducts.setLayoutManager(new LinearLayoutManager(LatestProductsActivity.this));

            } catch (JSONException e) {
                Toast.makeText(LatestProductsActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }
}

AdapterProductList.java

Java:
package com.bukausahaonline.tokoonline;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.Collections;
import java.util.List;

public class AdapterProductList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataProductList> data= Collections.emptyList();
    DataProductList current;
    int currentPos=0;

    // create constructor to innitilize context and data sent from MainActivity
    public AdapterProductList(Context context, List<DataProductList> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // Inflate the layout when viewholder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.container_product_list, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    // Bind data
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in recyclerview to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        DataProductList current=data.get(position);
        myHolder.textProductName.setText(current.productName);
        myHolder.textProductSpecial.setText(current.productSpecial);
        myHolder.textType.setText(current.catName);
        myHolder.textPrice.setText(current.price);
        myHolder.textPrice.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

        // load image into imageview using glide
        Glide.with(context).load(current.productImage)
                .placeholder(R.mipmap.ic_img_error)
                .error(R.mipmap.ic_img_error)
                .into(myHolder.ivProduct);

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }


    class MyHolder extends RecyclerView.ViewHolder{

        TextView textProductName;
        ImageView ivProduct;
        TextView textProductSpecial;
        TextView textType;
        TextView textPrice;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textProductName= (TextView) itemView.findViewById(R.id.textProductName);
            ivProduct= (ImageView) itemView.findViewById(R.id.ivProduct);
            textProductSpecial = (TextView) itemView.findViewById(R.id.textProductSpecial);
            textType = (TextView) itemView.findViewById(R.id.textType);
            textPrice = (TextView) itemView.findViewById(R.id.textPrice);
        }

    }

}

DataProductList.java

Java:
package com.bukausahaonline.tokoonline;

public class DataProductList {

    public int productId;
    public String productImage;
    public String productName;
    public String catName;
    public String productSpecial;
    public String price;
}

activity_latest_products.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_latest_products"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.bukausahaonline.tokoonline.LatestProductsActivity">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="50dp"
        android:text="LATEST PRODUCTS"/>
    <HorizontalScrollView
        android:id="@+id/horizontalscrollView"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:scrollbars="none">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:text="@string/button_category"
                android:onClick="goToCategoriesPage"/>

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button1"
                android:layout_alignBottom="@+id/button1"
                android:layout_toRightOf="@+id/button1"
                android:text="@string/button_latest"
                android:onClick="goToLatestPage"/>

            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button2"
                android:layout_alignBottom="@+id/button2"
                android:layout_toRightOf="@+id/button2"
                android:text="@string/button_featured"
                android:onClick="goToFeaturedPage"/>

            <Button
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button3"
                android:layout_alignBottom="@+id/button3"
                android:layout_toRightOf="@+id/button3"
                android:text="@string/button_special"
                android:onClick="goToSpecialsPage"/>

            <Button
                android:id="@+id/button5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button4"
                android:layout_alignBottom="@+id/button4"
                android:layout_toRightOf="@+id/button4"
                android:text="@string/button_bestseller"
                android:onClick="goToBestsellersPage"/>

        </LinearLayout>
    </HorizontalScrollView>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/productList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:layout_marginTop="80dp"
        android:layout_weight="1"
        />

</RelativeLayout>

container_product_list.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_latest_products"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.bukausahaonline.tokoonline.LatestProductsActivity">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="50dp"
        android:text="LATEST PRODUCTS"/>
    <HorizontalScrollView
        android:id="@+id/horizontalscrollView"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:scrollbars="none">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:text="@string/button_category"
                android:onClick="goToCategoriesPage"/>

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button1"
                android:layout_alignBottom="@+id/button1"
                android:layout_toRightOf="@+id/button1"
                android:text="@string/button_latest"
                android:onClick="goToLatestPage"/>

            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button2"
                android:layout_alignBottom="@+id/button2"
                android:layout_toRightOf="@+id/button2"
                android:text="@string/button_featured"
                android:onClick="goToFeaturedPage"/>

            <Button
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button3"
                android:layout_alignBottom="@+id/button3"
                android:layout_toRightOf="@+id/button3"
                android:text="@string/button_special"
                android:onClick="goToSpecialsPage"/>

            <Button
                android:id="@+id/button5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button4"
                android:layout_alignBottom="@+id/button4"
                android:layout_toRightOf="@+id/button4"
                android:text="@string/button_bestseller"
                android:onClick="goToBestsellersPage"/>

        </LinearLayout>
    </HorizontalScrollView>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/productList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:layout_marginTop="80dp"
        android:layout_weight="1"
        />

</RelativeLayout>

And the result is:

latest-products-list.png


Now, the problem is if I click the Product 56 button, it will go to the Product 56 info page. But if I click the Product 55 button it will go to product 56 info page too. Also, if I click the Product 54 button it will go to the Product 56 info page too.

product-info-56.png


But, if I scroll the Product 55 to the top just like this image below:

latest-products-list-scrolled.png


If I click the Product 55 button then it will go to the Product 55 info page.

product-info-55.png


It seems that, the button must be on top to be able to work correctly.

FYI, the product info page is also grabbed from my online shop using JSON method.

Any help is very appreciated. Thank you!
 
Thanks for the code, but you've not shown the vital part, which is the button click listener. I assume that method goToProduct() is called by it.

Code:
[LIST=1]
[*]public void goToProductPage(View view) {
[*]        Intent intent = new Intent(LatestProductsActivity.this, ProductActivity.class);
[*]        //TextView productId = (TextView) findViewById(R.id.productId);
[*]        Button productId = (Button) findViewById(R.id.textType);
[*]

[*]        String product_id = productId.getText().toString();
[*]        intent.putExtra(EXTRA_MESSAGE, product_id);
[*]        startActivity(intent);
[*]        //Intent intent = new Intent(this, ProductActivity.class);
[*]        //startActivity(intent);
[*]    }
[/LIST]

Every time this method is called, it finds the same Button, which I assume is why you always show the same product details.
 
  • Like
Reactions: Unforgiven
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones