RecycleView Parsable

  • Replies:1
  • OpenNot stickiedUnanswered
  • Forum posts: 1

Jul 13, 2016 3:33:23 PM via Website

Since I schedule some time in C ++ and C # and now started a work in java android android studio. I have two small problems that I believe are easy to solve, the first is that I am getting data from a MySQL database using PHP, this bank there are 14 entries, my application is getting these 14 entries, but repeating the last all Recycle List View, i.e the last value passed by JSON is repeated by the amount of select results. The other problem is that I am trying to use the Parcelable class to send data from a selected item in the recycle view the other activity, but without success, I think we have to create an array that stores these values during the Json as well the position of each item in the list but googled a lot and did not get success, your help will have great value to me! Below is my code. Thanks in advance.

Home Activity (my MainActivity):

public class home_activity  extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

private final String TAG = "home_activity";

private List data = new ArrayList<>();

private RecyclerView mRVConsulta;
private AdapterConsulta mAdapter;
private ProgressDialog progress;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

progress = new ProgressDialog(home_activity.this, R.style.AppTheme_Dark_Dialog);
progress.setIndeterminate(true);
progress.setMessage("loading...");
progress.show();





DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

mRVConsulta = (RecyclerView) findViewById(R.id.mRVConsulta);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mRVConsulta.setLayoutManager(layoutManager);


data = new ArrayList<>();
mAdapter = new AdapterConsulta(data,this);
mRVConsulta.setAdapter(mAdapter);
mRVConsulta.addItemDecoration(new DividerItemDecoration(home_activity.this, LinearLayoutManager.VERTICAL));

RequerimentServer();

}

@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
    return true;
}

return super.onOptionsItemSelected(item);

}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();

if (id == R.id.nav_historicoConsultas) {
    // Handle the camera action


} else if (id == R.id.nav_wer) {

} else if (id == R.id.nav_wer2) {

} else if (id == R.id.nav_wer3) {

} else if (id == R.id.nav_wer4) {

} else if (id == R.id.nav_wer5) {

}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;

}

private void RequerimentServer() {
String url = Config.URL_LISTA_PRODUCTS;
Map params2 = new HashMap();
params2.put(Config.KEY_ID, Config.idProduct);

CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params2, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        Log.d("Response: >", response.toString() + "<");

        JSONObject objeto = response;

        JSONArray array = null;
        try {
            array = objeto.getJSONArray("result");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        getData(array);


    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError response) {
        Log.d("Response:  >", response.toString() + "<");
    }
});

RequestQueue requestQueue = Volley.newRequestQueue(home_activity.this);
requestQueue.add(jsObjRequest);

}

protected void getData(JSONArray array) {
Log.d("Array adapter: >", array.toString() + "<");

        for(int i = 0; i<array.length(); i++)
        {
            product_lista lista = new product_lista();
            JSONObject json_data = null;

                try
                {
                    json_data = array.getJSONObject(i);


                    String dataEntrada = json_data.getString("data");
                    SimpleDateFormat dataFormato = new SimpleDateFormat("dd/MM/yyyy");
                    Date convertedDate = new Date();
                    try {
                        convertedDate = dataFormato.parse(dataEntrada);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String dataFinal = dataFormato.format(convertedDate);

                    lista.setdata(dataFinal);
                    lista.setPreço (json_data.getString("preco"));

                    if (json_data.isNull("detalhes"))
                    {
                        lista.setDetalhes ("Sem detalhes");
                    } else
                    {
                        lista.setDetalhes(json_data.getString("detalhes"));
                    }

                    if (json_data.isNull("comentarios"))
                    {
                        lista.setComentarios ( "Sem comentarios");
                    }
                    else
                    {
                        lista.setComentarios (json_data.getString("comentarios"));
                    }

                    lista.setProduto(json_data.getString("produto"));

                    lista.setProduto_id(json_data.getInt("pk_Produto"));



                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            mAdapter.notifyItemRangeChanged(0, mAdapter.getItemCount());
            data.add(lista);
           }


    progress.dismiss();

}

}

Adapter:

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

private Context mContext;

private List data;

product_lista current;
int currentPos = 0;
private LayoutInflater inflater;

public AdapterConsulta(List data, Context context){
super();
this.mContext=context;
this.data=data;

}

private boolean isPositionItem(int position) {
return position != getItemCount() - 1;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.container_consultas, parent, false);
return new MyHolder(v);

}

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

     final product_lista lista = data.get(position);
    ((MyHolder) holder).textData.setText(lista.getdata());
    ((MyHolder) holder).textProduct.setText(lista.getProduct());

    ((MyHolder) holder).textPreco.setText(lista.getPreco());
    ((MyHolder) holder).textData.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimaryDark));
    if (lista.getComentarios().trim().equals("0")) {
        ((MyHolder) holder).ivIcone.setImageResource(R.drawable.0);
    } else {
        ((MyHolder) holder).ivIcone.setImageResource(R.drawable.1);
    }

}

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

class MyHolder extends RecyclerView.ViewHolder implements OnClickListener {
TextView textData;
ImageView ivIcone;
TextView textPreco;
TextView textProduto;

 public MyHolder(final View itemView) {
     super(itemView);
     itemView.setOnClickListener(this);
     textData= (TextView) itemView.findViewById(R.id.textData);
     textProduto= (TextView) itemView.findViewById(R.id.textProduto);
     ivIcone= (ImageView) itemView.findViewById(R.id.ivConsulta);
     textPreco = (TextView) itemView.findViewById(R.id.textPreco);


 }



 @Override
 public void onClick(View v) {
     Intent intent = new Intent(mContext, detalhes_consulta_activity.class);
     intent.putExtra("EXTRA_DATA", consulta_lista.getdata());
     intent.putExtra("EXTRA_PRECO, consulta_lista.getPreco());
     intent.putExtra("EXTRA_DETALHES", consulta_lista.getDetalhes());
     intent.putExtra("EXTRA_COMENTARIOS", consulta_lista.getComentarios());
     intent.putExtra("EXTRA_PRODUTO", consulta_lista.getProduto());

     intent.putExtra("EXTRA_ID", consulta_lista.getConsulta_id());
     mContext.startActivity(intent);

 }

}
}

My Parceble Class:

public class product_lista implements Parcelable{

private static String mdata;
private static String mpreco;
private static String mdetalhes;
private static String mcomentarios;
private static String mproduto;
private static int Produto_id;

public static String getdata() {
return mdata;
}

public void setdataConsulta(String mdata) {
this.mdata = mdata;
}

public static String getPreco() {
return mpreco;
}

public void setPreco(String mpreco) {
this.mpreco = mpreco;
}

public static String getDetalhes() {
return mdetalhes;
}

public void setDetalhes(String mdetalhes) {
this.mdetalhes = mdetalhes;
}

public static String getComentarios() {
return mcomentarios;
}

public void setCoentarios(String mcomentarios) {
this.mcomentarios = mcomentarios;
}

public static String getProduto() {
return mproduto;
}

public void setProduto(String mProduto) {
this.mproduto = mproduto;
}

public static int getProduto_id() {
return produto_id;
}

public void setProduto_id(int produto_id) {
this.produto_id = produto_id;
}

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mdata);
dest.writeString(this.mpreco);
dest.writeString(this.mdetalhes);
dest.writeString(this.mcomentarios);
dest.writeString(this.mproduto);
dest.writeInt(this.produto_id);

}

public consulta_lista() {
}

protected consulta_lista(Parcel in) {
this.mdata = in.readString();
this.mpreco= in.readString();
this.mdetalhes = in.readString();
this.mcomentarios = in.readString();
this.mproduto = in.readString();
this.produto_id = in.readInt();
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public consulta_lista createFromParcel(Parcel source) {
return new consulta_lista(source);
}

public consulta_lista[] newArray(int size) {
    return new consulta_lista[size];
}

};
}

My Activity with details:

public class detalhes_activity extends AppCompatActivity{

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

String detalhes = getIntent().getStringExtra("EXTRA_DETALHES");
TextView detalhes = (TextView) findViewById(R.id.detalhes);
detalhes.setText(detalhes);

String comentarios = getIntent().getStringExtra("EXTRA_COMENTARIOS");
TextView coemntarios = (TextView) findViewById(R.id.coementarios);
comentarios.setText(comentarios);

}
}

  • Forum posts: 208

Jul 18, 2016 2:24:32 PM via Website

What is length of array in which you are putting the array.