Use Recyclerview in fragments with data from a BD

0

I am new to programming, I have a project in which I have been trying for a long time to "inflate" a recyclerview in fragments with Sql data. I appreciate your help ... I will try to detail as best as possible: I work with an activity of a library "materialviewpager" is this:

The main activity selects the class for each fragment in this way:

  @Override
        public Fragment getItem(int position) {
            switch (position % 7) {
                //case 0:
                //    return RecyclerViewFragment.newInstance();
                //case 1:
                //    return RecyclerViewFragment.newInstance();
                //case 2:
                //    return WebViewFragment.newInstance();
                default:
                    return RecyclerViewFragment.newInstance();
            }
        }

and the Recyclerviewfragment is built as follows:

public class RecyclerViewFragment extends Fragment {

private static final boolean GRID_LAYOUT = false;
private static final int ITEM_COUNT = 100;

@BindView(R.id.recyclerView)
RecyclerView mRecyclerView;

public static RecyclerViewFragment newInstance() {
    return new RecyclerViewFragment();
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_recyclerview, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ButterKnife.bind(this, view);

    final List<Object> items = new ArrayList<>();

    for (int i = 0; i < ITEM_COUNT; ++i) {
        items.add(new Object());
    }


    //setup materialviewpager

    if (GRID_LAYOUT) {
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
    } else {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    }
    mRecyclerView.setHasFixedSize(true);

    //Use this now
    mRecyclerView.addItemDecoration(new MaterialViewPagerHeaderDecorator());
    mRecyclerView.setAdapter(new TestRecyclerViewAdapter(items));
}

}

this class calls this adapter:

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

List<Object> contents;

static final int TYPE_HEADER = 0;
static final int TYPE_CELL = 1;

public TestRecyclerViewAdapter(List<Object> contents) {
    this.contents = contents;
}

@Override
public int getItemViewType(int position) {
    switch (position) {
        case 0:
            return TYPE_HEADER;
        default:
            return TYPE_CELL;
    }
}

@Override
public int getItemCount() {
    return contents.size();
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = null;

    switch (viewType) {
        case TYPE_HEADER: {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item_card_big, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }
        case TYPE_CELL: {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item_card_small, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }
    }
    return null;
}


@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (getItemViewType(position)) {
        case TYPE_HEADER:
            break;
        case TYPE_CELL:
            break;
    }
}

}

I have used a recyclerview before with data from a mysql database without problem but in this type of activity, I have tried several ways and I can not. This is the class that I have used without problem:

public class ConsutarListausuarioImagenFragment extends Fragment
    implements Response.Listener<JSONObject>,Response.ErrorListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

RecyclerView recyclerUsuarios;
ArrayList<Usuario> listaUsuarios;

ProgressDialog dialog;

// RequestQueue request;     JsonObjectRequest jsonObjectRequest;

public ConsutarListausuarioImagenFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment ConsutarListausuarioImagenFragment.
 */
// TODO: Rename and change types and number of parameters
public static ConsutarListausuarioImagenFragment newInstance(String param1, String param2) {
    ConsutarListausuarioImagenFragment fragment = new ConsutarListausuarioImagenFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View vista= inflater.inflate(R.layout.fragment_consutar_listausuario_imagen, container, false);;

    listaUsuarios=new ArrayList<>();

    recyclerUsuarios = (RecyclerView) vista.findViewById(R.id.idRecyclerImagen);
    recyclerUsuarios.setLayoutManager(new LinearLayoutManager(this.getContext()));
    recyclerUsuarios.setHasFixedSize(true);

   // request= Volley.newRequestQueue(getContext());

    cargarWebService();

    return vista;
}

private void cargarWebService() {

    dialog=new ProgressDialog(getContext());
    dialog.setMessage("Consultando Imagenes");
    dialog.show();

    String ip=getString(R.string.ip);

    String url=ip+"/ejemploBDRemota/wsJSONConsultarListaImagenes.php";
    jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null,this,this);
   // request.add(jsonObjectRequest);
    VolleySingleton.getIntanciaVolley(getContext()).addToRequestQueue(jsonObjectRequest);
}

@Override
public void onResponse(JSONObject response) {
    Usuario usuario=null;

    JSONArray json=response.optJSONArray("usuario");

    try {

        for (int i=0;i<json.length();i++){
            usuario=new Usuario();
            JSONObject jsonObject=null;
            jsonObject=json.getJSONObject(i);

            usuario.setDocumento(jsonObject.optInt("documento"));
            usuario.setNombre(jsonObject.optString("nombre"));
            usuario.setProfesion(jsonObject.optString("profesion"));
            usuario.setDato(jsonObject.optString("imagen"));
            listaUsuarios.add(usuario);
        }
        dialog.hide();
        UsuariosImagenAdapter adapter=new UsuariosImagenAdapter(listaUsuarios);
        recyclerUsuarios.setAdapter(adapter);

    } catch (JSONException e) {
        e.printStackTrace();
        Toast.makeText(getContext(), "No se ha podido establecer conexión con el servidor" +
                " "+response, Toast.LENGTH_LONG).show();
        dialog.hide();
    }
}

@Override
public void onErrorResponse(VolleyError error) {

}

and call this adapter:

public class UsuariosImagenAdapter extends RecyclerView.Adapter<UsuariosImagenAdapter.UsuariosHolder>{

List<Usuario> listaUsuarios;

public UsuariosImagenAdapter(List<Usuario> listaUsuarios) {
    this.listaUsuarios = listaUsuarios;
}

@Override
public UsuariosHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View vista= LayoutInflater.from(parent.getContext()).inflate(R.layout.usuarios_list_image,parent,false);
    RecyclerView.LayoutParams layoutParams=new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    vista.setLayoutParams(layoutParams);
    return new UsuariosHolder(vista);
}

@Override
public void onBindViewHolder(UsuariosHolder holder, int position) {
    holder.txtDocumento.setText(listaUsuarios.get(position).getDocumento().toString());
    holder.txtNombre.setText(listaUsuarios.get(position).getNombre().toString());
    holder.txtProfesion.setText(listaUsuarios.get(position).getProfesion().toString());

    if (listaUsuarios.get(position).getImagen()!=null){
        holder.imagen.setImageBitmap(listaUsuarios.get(position).getImagen());
    }else{
        holder.imagen.setImageResource(R.drawable.img_base);
    }
}

@Override
public int getItemCount() {
    return listaUsuarios.size();
}

public class UsuariosHolder extends RecyclerView.ViewHolder{

    TextView txtDocumento,txtNombre,txtProfesion;
    ImageView imagen;

    public UsuariosHolder(View itemView) {
        super(itemView);
        txtDocumento= (TextView) itemView.findViewById(R.id.idDocumento);
        txtNombre= (TextView) itemView.findViewById(R.id.idNombre);
        txtProfesion= (TextView) itemView.findViewById(R.id.idProfesion);
        imagen=(ImageView) itemView.findViewById(R.id.idImagen);
    }
}

}

I do not know how to make this adapter work with the fragment of "materialviewpager" and manage to fill the recyclerview with data from mysql using the Recyclerviewfragment and the testrecyclerviewadapter which are the ones that come by default. Thank you in advance.

    
asked by IGr135 30.08.2018 в 04:00
source

0 answers