0

I have a ListView where I displayed data from a database using mysql and json but by doing some research I found the RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets and that with the RecyclerView I can have a result like this. So how I can correct my code? How can I extract an image from a database and fetch it into the RecyclerView

enter image description here

Here's how I've done it in ListView

private void showarticles(String json){
        JSONObject jsonObject = null;
        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
        try {
            JSONArray result = new JSONArray(json);

            for(int i = 0; i<result.length(); i++){
                JSONObject jo = result.getJSONObject(i);
                String name = jo.getString("Nom");
                String ref = jo.getString("Description");
                HashMap<String,String> articles= new HashMap<>();
                articles.put("name",name);
                articles.put("ref",ref);
                list.add(articles);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        adapter = new SimpleAdapter(
                getActivity(), list, R.layout.list_row2,
                new String[]{"name","ref"},
                new int[]{R.id.name, R.id.description});

        listView.setAdapter(adapter);
    }
    private void getJSON() {
        class GetJSON extends AsyncTask<Void, Void, String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(getActivity(), "Téléchargement", "Veuillez patientez...", false, false);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                showarticles(s);
            }
            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequest(URL);
                return s;
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();
    }

Update

public class recyclerFragment extends Fragment {
private RecyclerView mRecyclerView;
ListAdapter adapter;
private String JSON_STRING;
public static final String URL = "http://aaaa.com/Back/getArticles.php";
private MyAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.recycler_fragment, container, false);
    mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_list);
    mRecyclerView.addItemDecoration(new SpacesItemDecoration(10));
    mLayoutManager = new GridLayoutManager(getActivity(), 2);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new MyAdapter(null);
    mRecyclerView.setAdapter(mAdapter);
    getJSON();
return rootview;
}
private void showarticles(String json){
        JSONObject jsonObject = null;
        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
        try {
            JSONArray result = new JSONArray(json);

            for(int i = 0; i<result.length(); i++){
                JSONObject jo = result.getJSONObject(i);
                String name = jo.getString("Nom");
                String ref = jo.getString("Description");
                HashMap<String,String> articles= new HashMap<>();
                articles.put("name",name);
                articles.put("ref",ref);
                list.add(articles);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    mAdapter = new SimpleAdapter(
            getActivity(), list, R.layout.list_row2,
            new String[]{"name","ref"},
            new int[]{R.id.nom, R.id.email2});

    mRecyclerView.setAdapter(mAdapter);
}
private void getJSON() {
    class GetJSON extends AsyncTask<Void, Void, String> {
        ProgressDialog loading;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(getActivity(), "Téléchargement", "Veuillez patientez...", false, false);
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            JSON_STRING = s;
            showEmployee(s);
        }
        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            String s = rh.sendGetRequest(URL);
            return s;
        }
    }
    GetJSON gj = new GetJSON();
    gj.execute();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent(getActivity().getApplicationContext(), ViewProduit.class);
    HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
    String tid = map.get("ref").toString();
    intent.putExtra("ref", tid);
    startActivity(intent);
}

}

Error:(31, 27) error: cannot find symbol variable myArrayList
Error:(76, 13) error: cannot find symbol variable myArrayList
Error:(77, 20) error: cannot find symbol variable myArrayList
Error:(41, 45) error: cannot find symbol class SpacesItemDecoration
Error:(44, 20) error: constructor MyAdapter in class MyAdapter cannot be applied to given types;
required: no arguments
found: <null>
reason: actual and formal argument lists differ in length
Error:(74, 20) error: incompatible types: SimpleAdapter cannot be converted to MyAdapter
Error:(106, 5) error: method does not override or implement a method from a supertype
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Lara Fab
  • 33
  • 7
  • 1
    Possible duplicate of [Using the recyclerview with a database](http://stackoverflow.com/questions/26517855/using-the-recyclerview-with-a-database) – Janki Gadhiya May 20 '16 at 09:56

1 Answers1

0

You need to have a RecyclerView in your layout first.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="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="@color/black">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

Now if you're in an Activity, lets initialize your RecyclerView along with the LayoutManager. In your case you need to have a GridLayoutManager

// Declare them first
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

Initialize the items inside your onCreate function and set the Adapter here.

mRecyclerView = (RecyclerView) findViewById(R.id.my_list);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(10));
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter();
mRecyclerView.setAdapter(mAdapter);

Now get your ArrayList prepared to pass it in the Adapter and then call notifyDataSetChanged() to populate the RecyclerView with the items you want to show.

So here you go with your custom Adapter

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

    public MyAdapter() {
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        // Declare the items in each row 
        private TextView myTextView;

        public ViewHolder(final View itemView) {
            super(itemView);

            // Initialize the items here
            myTextView = (TextView) itemView.findViewById(R.id.my_textview);
        }

        public void bindView(int pos) {
            // Set the items here with specific array elements you have
            String text = myArrayList.get(pos);
            myTextView.setText(text);
        }
    }

    // Now define the viewholder for Normal list item
    public class NormalViewHolder extends ViewHolder {
        public NormalViewHolder(View itemView) {
            super(itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO: Here's what you want to do when your list item is clicked
                }
            });
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v;

        v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent, false);

        NormalViewHolder vh = new NormalViewHolder(v);

        return vh;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        try {
            if (holder instanceof NormalViewHolder) {
                NormalViewHolder vh = (NormalViewHolder) holder;
                vh.bindView(position);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        if (myArrayList != null)
            return myArrayList.size();
        else return 0;
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }
}

Declare myArrayList as global and populate myArrayList with the elements you want and customize the bindView as you want. When you are done with populating the myArrayList call notifyDatasetChanged() on your Adapter like mAdapter.notifyDataSetChanged().

Update

So here's I'm taking your updated code and modifying as much as possible. The code might have errors, but I think after you get it modified you can do the rest by yourself.

public class recyclerFragment extends Fragment {
    private RecyclerView mRecyclerView;
    private MyAdapter mAdapter;
    private String JSON_STRING;
    public static final String URL = "http://aaaa.com/Back/getArticles.php";
    private RecyclerView.LayoutManager mLayoutManager;

    // Declare the list globally
    ArrayList<HashMap<String,String>> list;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.recycler_fragment, container, false);
        mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_list);

        // Initialize the list here 
        list = new ArrayList<HashMap<String, String>>();

        // Initialize other items
        mRecyclerView.addItemDecoration(new SpacesItemDecoration(10));
        mLayoutManager = new GridLayoutManager(getActivity(), 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mAdapter);
        getJSON();

        return rootview;
    }

    private void showarticles(String json){
            JSONObject jsonObject = null;

            try {
                JSONArray result = new JSONArray(json);

                for(int i = 0; i<result.length(); i++){
                    JSONObject jo = result.getJSONObject(i);
                    String name = jo.getString("Nom");
                    String ref = jo.getString("Description");
                    HashMap<String,String> articles= new HashMap<>();
                    articles.put("name",name);
                    articles.put("ref",ref);
                    list.add(articles);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        // Here you can call notifyDataSetChanged in your Adapter. As you've the dataset ready now. 
        mAdapter.notifyDataSetChanged();
    }

    private void getJSON() {
        class GetJSON extends AsyncTask<Void, Void, String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(getActivity(), "Téléchargement", "Veuillez patientez...", false, false);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                showEmployee(s);
            }
            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequest(URL);
                return s;
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();
    }

    // Here you write your custom Adapter class 
    public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        public MyAdapter() {
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            // Declare the items in each row 
            private Button myButton;

            public ViewHolder(final View itemView) {
                super(itemView);

                // Initialize the items here
                myButton = (TextView) itemView.findViewById(R.id.my_button);
            }

            public void bindView(int pos) {
                // Set the items here with specific array elements you have

                myButton.setOnClickListener(new View.OnClickListener()     {
                    @Override
                    public void onClick(View v) {
                        // Here's what you want to do when your list item is clicked
                        Intent intent = new Intent(getActivity().getApplicationContext(), ViewProduit.class);
                        HashMap<String, String> map = (HashMap) parent.getItemAtPosition(pos);
                        String tid = map.get("ref").toString();
                        intent.putExtra("ref", tid);
                        startActivity(intent);

                    }
                });
            }
        }

        // Now define the viewholder for Normal list item
        public class NormalViewHolder extends ViewHolder {
            public NormalViewHolder(View itemView) {
                super(itemView);
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View v;

            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent, false);

            NormalViewHolder vh = new NormalViewHolder(v);

            return vh;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            try {
                if (holder instanceof NormalViewHolder) {
                    NormalViewHolder vh = (NormalViewHolder) holder;
                    vh.bindView(position);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount() {
            if (list != null)
                return list.size();
            else return 0;
        }

        @Override
        public int getItemViewType(int position) {
            return super.getItemViewType(position);
        }
    }
}
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
  • thanks I tried to use this code with mine but I feel a bit lost :( I updated my post can you help me to correct it – Lara Fab May 20 '16 at 11:35
  • Sorry I had a mistake in my example. The line should be `mAdapter = new MyAdapter();` as `MyAdapter` takes no argument. And from your logcat, I've seen that you're trying to use `myArrayList`. Listen, I just've added `myArrayList` for my example. You need to have your own `ArrayList` to serve your purpose which is `list` in your case. I'm updating my answer again though. See if that helps. – Reaz Murshed May 20 '16 at 12:51