Android Studio,Problemas com RecyclerView
Criei uma tela de busca com Recycleview, e ao efetuar a busca ele traz o resultado armazenado no banco. Até ai tudo bem. Porém se existir no banco 2 nomes iguais como por exemplo: se existir vinte pessoas com o nome "Carlos", ele só me traz uma pessoa. Aqui abaixo segue a classe adapter e o recycle. Estou usando a tela de fragment. Outro detalhe, se eu repetir a mesma busca, ele inseri na lista abaixo o mesmo item da busca anterior, ou seja, fica 2 itens duplicados com os mesmos valores no recycleview. Eu não sei se o erro ta dentro do método onResponse ou se ta no PHP. Deve ser uma besteira. Quem puder ajudar, agradeço.
Classe Adapter:
public class CursosAdapterImgUrl extends RecyclerView.Adapter<CursosAdapterImgUrl.CursosHolder> {
List<Curso>listaCursos;
RequestQueue request;
Context context;
public CursosAdapterImgUrl(List<Curso> listaCursos, Context context) {
this.listaCursos = listaCursos;
this.context = context;
request = Volley.newRequestQueue(context);
}
@NonNull
@Override
public CursosHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View vista = LayoutInflater.from(parent.getContext()).inflate(R.layout.lista_cursos_img, parent, false);
RecyclerView.LayoutParams layoutParams =
new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
vista.setLayoutParams(layoutParams);
return new CursosHolder(vista);
}
@Override
public void onBindViewHolder(@NonNull CursosHolder holder, int position) {
// holder.txtCodigo.setText(listaCursos.get(position).getCodigo().toString());
holder.txtNome.setText(listaCursos.get(position).getNome().toString());
holder.txtProfessor.setText(listaCursos.get(position).getProfessor().toString());
holder.txtCategoria.setText(listaCursos.get(position).getCategoria().toString());
if(listaCursos.get(position).getUrlImagem()!=null){
carregarImagemWEBService(listaCursos.get(position).getUrlImagem(),holder);
}else{
holder.idImagem.setImageResource(R.drawable.sem_foto);
}
}
private void carregarImagemWEBService(String urlImagem, final CursosHolder holder) {
String caminhoImage = "http://192.168.0.12/webservices/" +urlImagem;
caminhoImage = caminhoImage.replace(" ", "%20");
ImageRequest imageReq = new ImageRequest(caminhoImage, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
holder.idImagem.setImageBitmap(response);
}
}, 0, 0, ImageView.ScaleType.CENTER, null, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Erro ao carregar a imagem",Toast.LENGTH_SHORT).show();
}
});
request.add(imageReq);
}
@Override
public int getItemCount() {
return listaCursos.size();
}
public class CursosHolder extends RecyclerView.ViewHolder {
TextView txtNome,txtCodigo,txtProfessor, txtCategoria;
ImageView idImagem;
public CursosHolder(View itemView) {
super(itemView);
txtNome= (TextView) itemView.findViewById(R.id.nomeCurso);
//txtCodigo= (TextView) itemView.findViewById(R.id.txtCodigo);
txtProfessor= (TextView) itemView.findViewById(R.id.Professor);
txtCategoria= (TextView) itemView.findViewById(R.id.Categoria);
idImagem= itemView.findViewById(R.id.idImagem);
}
}
}
Classe do Recicleview:
public class consultarListaNome 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;
EditText campoNome;
Button botaoConsultar;
RecyclerView recyclerCursos;
ArrayList<Curso> listaCursos;
ProgressDialog progresso;
RequestQueue request;
JsonObjectRequest jsonObjectReq;
ImageView imgFoto;
private OnFragmentInteractionListener mListener;
public consultarListaNome() {
// 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 consultarListaNome.
*/// TODO: Rename and change types and number of parameters
public static consultarListaNome newInstance(String param1, String param2) {
consultarListaNome fragment = new consultarListaNome();
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) {
// Inflate the layout for this fragment
View vista = inflater.inflate(R.layout.fragment_consultar_lista_nome, container, false);
listaCursos=new ArrayList<>();
recyclerCursos= (RecyclerView) vista.findViewById(R.id.idRecyclerNome); // se der problema, mude aqui
recyclerCursos.setLayoutManager(new LinearLayoutManager(this.getContext()));
recyclerCursos.setHasFixedSize(true);
campoNome = (EditText) vista.findViewById(R.id.campoNome);
botaoConsultar = (Button) vista.findViewById(R.id.btnConsultar);
request= Volley.newRequestQueue(getContext());
botaoConsultar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
carregarWEBService();
}
});
return vista;
}
private void carregarWEBService() {
progresso = new ProgressDialog(getContext());
progresso.setMessage("Buscando...");
progresso.show();
String url = "http://192.168.0.12/webservices/consultarCursoNome.php?nome="+ campoNome.getText().toString();
jsonObjectReq = new JsonObjectRequest(Request.Method.GET, url, null, this, this);
request.add(jsonObjectReq);
}
@Override
public void onErrorResponse(VolleyError error) {
progresso.hide();
Toast.makeText(getContext(), "Não foi possível listar os cursos " +error.toString() , Toast.LENGTH_SHORT).show();
Log.i("ERROR", error.toString());
}
@Override
public void onResponse(JSONObject response) {
progresso.hide();
Curso curso = null;
JSONArray json = response.optJSONArray("curso"); // nome da tabela curso
try {
for(int i=0; i<json.length();i++){
curso = new Curso();
JSONObject jsonObject = null;
jsonObject = json.getJSONObject(i);
curso.setNome(jsonObject.optString("nome"));
curso.setProfessor(jsonObject.optString("professor"));
curso.setCategoria(jsonObject.optString("categoria"));
curso.setUrlImagem(jsonObject.optString("url_imagem"));
listaCursos.add(curso);
}
progresso.hide();
CursosAdapterImgUrl adapter = new CursosAdapterImgUrl(listaCursos,getContext());
recyclerCursos.setAdapter(adapter);
}catch (JSONException e){
e.printStackTrace();
progresso.hide();
Toast.makeText(getContext(), "Não foi possível listar os cursos " +response , Toast.LENGTH_SHORT).show();
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Código do PHP:
<?PHP
include "conexao.php";
$json=array();
if(isset($_GET["nome"])){
$nome=$_GET["nome"];
$consulta="select * from curso where nome= '{$nome}'"; // busca pelo nome
$resultado=mysqli_query($conexao,$consulta);
if($registro=mysqli_fetch_array($resultado)){
$result["codigo"]=$registro['codigo'];
$result["nome"]=$registro['nome'];
$result["categoria"]=$registro['categoria'];
$result["professor"]=$registro['professor'];
$result["url_imagem"]=$registro['url_imagem'];
$json['curso'][]=$result;
}else{
$resultar["codigo"]=0;
$resultar["nome"]='nao registrado';
$resultar["categoria"]='nao registrado';
$resultar["professor"]='nao registrado';
$result["url_imagem"]=$registro['url_imagem'];
$json['curso'][]=$resultar;
}
mysqli_close($conexao);
echo json_encode($json);
}
else{
$resultar["codigo"]=0;
$resultar["nome"]='nao registrado';
$resultar["categoria"]='nao registrado';
$resultar["professor"]='nao registrado';
$result["url_imagem"]=$registro['url_imagem'];
$json['curso'][]=$resultar;
echo json_encode($json);
}
?>Discussão (0)
Carregando comentários...