Not getting updated Adapter position of for CardView in Android. - android

I have set up recyclerview for same Api data on two fragments.After clicking on one of Card, a new Detail fragment for same Card is open on Another Fragment.The cardview contain images.After clicking one of image I need to get information of that CardView position.But as I click on one of card in First Fragment and I move to same card position in Second Fragment but I swipe to other cards and click on Image of other CardView still I am getting information for same Card which was clicked first.
This is code for Adapter
class public class StatusInfoAdapter extends RecyclerView.Adapter<StatusInfoAdapter.ViewHolder> {
private FragmentManager fm;
private FragmentTransaction tx;
private ArrayList<StatusEntry> entries;
private int finalPos,tempPos;
Context context;
String People, id,Id;
SnackBarAlert alertMsg=new SnackBarAlert();
private String myToken;
public StatusInfoAdapter(ArrayList<StatusEntry> entries, Context context) {
this.entries = entries;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.status_info_card, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder,int position) {
StatusEntry entry = entries.get(position);
tempPos = holder.getAdapterPosition();
finalPos = tempPos + 1;
holder.id.setText(entry.getid());
holder.Idno.setText(entry.getidno());
holder.fname.setText(entry.getFname());
holder.lname.setText(entry.getLname());
holder.people.setText(entry.getPeople());
noOfPeople = entries.get(position).getPeople();
fid = entries.get(position).getFyraid();
Id = entries.get(position).getid();
}
#Override
public int getItemCount() {
return entries.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView fname;
public TextView lname;
public TextView people;
public TextView d;
TextView Idno;
ImageView cancelEntry;
public ViewHolder(View v) {
super(v);
SharedPreferences preferences=context.getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
fname = (TextView) v.findViewById(R.id.fname);
lname = (TextView) v.findViewById(R.id.lname);
people = (TextView) v.findViewById(R.id.adults);
fyra_id = (TextView) v.findViewById(R.id.fyraid);
Idno = (TextView) v.findViewById(R.id.Id);
cancelEntry = (ImageView) v.findViewById(R.id.cancel);
cancelEntry.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
final AppCompatActivity activity = (AppCompatActivity) v.getContext();
final Dialog dialog=new Dialog(activity);
dialog.setContentView(R.layout.cancel_reason);
dialog.show();
Button yes = (Button) dialog.findViewById(R.id.yes);
Button no = (Button) dialog.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
removeFromQueue();
alertMsg.infoMessage(v,"Removed from List");
entries.remove(tempPos);
notifyItemRemoved(tempPos);
ChooseTab chooseTab1=new ChooseTab();
fm=activity.getSupportFragmentManager();
CurrentStatus currentStatus=new CurrentStatus();
tx=fm.beginTransaction();
tx.detach(currentStatus);
tx.attach(currentStatus);
tx.replace(R.id.frame,chooseTab1);
tx.commit();
}
});
}
});
}
}
This is code for setting RecyclerView
JsonArrayRequest request=new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try{
for(int i=0;i<response.length();i++)
{
JSONObject object=response.getJSONObject(i);
final StatusEntry entry=new StatusEntry();
String id=object.getString("fid");
Idno=object.getString("idno");
JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String first_name=response.getString("firstname");
String last_name=response.getString("lastname");
String id=response.getString("id");
entry.setFname(first_name);
entry.setLname(last_name);
entry.setid(id);
entry.setidNo(Idno);
adapter.notifyDataSetChanged();
progressDialog.hide();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
};
AppController.getInstance().addToRequestQueue(foodie_request,foodie_data);
String no_of_people=object.getString("no_people");
entry.setPeople(no_of_people);
progressDialog.dismiss();
entries.add(entry);
adapter = new StatusInfoAdapter(entries, getActivity().getApplicationContext());
recyclerView.setAdapter(adapter);
}
}catch(JSONException e)
{
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
};
AppController.getInstance().addToRequestQueue(request,foo_request);
}
I am getting the same Idno for all CardView after swiping to other cards.How to resolve this ?

pass the model of list in the constructor of the fragment at time of begin transaction and receive it by creating same model in another fragment from constructor

Related

I can't setProgress(0) of ALL Seekbars in RecyclerView when clicking a button (Android)

I have a RecyclerView of questions (which are saved and retrieved from database) and seekbars (which I save in database).
Link to image
After clicking on SUBMIT EXTRA QUESTIONS there is a dialog which appears
Link to image
I want after clicking on Okay the progress of ALL seekbars to be 0.
I tried to do this submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
holder.seekBar.setProgress(0);
But It changes only the progress of the last seekbar. Does anyone have any idea?
public class ExtraQuestionAdapter extends RecyclerView.Adapter<ExtraQuestionAdapter.ExtraQuestionViewHolder> {
private Context mCntx;
private List<ExtraQuestion> extraQuestionList;
private OnExtraAnswerListener onExtraAnswerListener;
private Button btn_submit_extra_questions;
private View rootView;
ArrayList<Integer> answersArray;
private Integer[] array = {};
String getId;
SessionManager sessionManager;
private Dialog dialog;
public ExtraQuestionAdapter(Context mCntx, List<ExtraQuestion> extraQuestionList, OnExtraAnswerListener onExtraAnswerListener) {
this.mCntx = mCntx;
this.extraQuestionList = extraQuestionList;
this.onExtraAnswerListener = onExtraAnswerListener;
}
#NonNull
#Override
public ExtraQuestionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCntx);
View view = inflater.inflate(R.layout.extra_question_layout, parent, false);
sessionManager = new SessionManager(mCntx);
HashMap<String, String> user = sessionManager.getUserDetail();
mCntx = parent.getContext();
rootView = ((Activity) mCntx).getWindow().getDecorView().findViewById(android.R.id.content);
//set the size of the array with answers to be equal to the size of the array with questions
array = new Integer[extraQuestionList.size()];
//initialise the array with answers with 0
for (int i = 0; i < extraQuestionList.size(); i++) {
array[i] = 0;
}
getId = user.get(sessionManager.ID);
btn_submit_extra_questions = rootView.findViewById(R.id.btn_submit_extra_questions);
ExtraQuestionViewHolder extraQuestionViewHolder = new ExtraQuestionViewHolder(view, onExtraAnswerListener);
return extraQuestionViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExtraQuestionViewHolder holder, int position) {
ExtraQuestion extraQuestion = extraQuestionList.get(position);
holder.title.setText(extraQuestion.getExtra_question());
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
array[holder.getAdapterPosition()] = seekBar.getProgress();
}
});
btn_submit_extra_questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(mCntx);
dialog.setContentView(R.layout.dialog_submit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog.getWindow().setBackgroundDrawable(mCntx.getDrawable(R.drawable.dialog_background));
}
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button finalSubmit = dialog.findViewById(R.id.btn_submit);
Button cancelSubmit = dialog.findViewById(R.id.btn_cancel);
ImageView info = dialog.findViewById(R.id.info);
TextView termsConditions = dialog.findViewById(R.id.textView3);
// Cancel button in the dialog
cancelSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//Okay button in the dialog
finalSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//fill the arraylist of answers with the array of answers
answersArray = new ArrayList<>(Arrays.asList(array));
ArrayList<Integer> FAnswerArray = new ArrayList<>();
ArrayList<Integer> FQuestionArray = new ArrayList<>();
if (!answersArray.isEmpty()) {
for (int i = 0; i < answersArray.size(); i++) {
FAnswerArray.add(answersArray.get(i));
FQuestionArray.add(i + 1);
}
}
JSONArray jsonArrayQuestion = new JSONArray();
for (Integer question : FQuestionArray) {
jsonArrayQuestion.put(question);
}
JSONArray jsonArrayAnswer = new JSONArray();
for (Integer answer : FAnswerArray) {
jsonArrayAnswer.put(answer);
}
dialog.dismiss();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(System.currentTimeMillis());
submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
}
});
//Info button in the dialog
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
//Terms and conditions in the dialog
termsConditions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
dialog.show();
}
});
}
private void submitExpenseData(String extra_questions_id, String users_id, String extra_answer, String timeStamp_date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.EXTRA_ANSWERS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//we get the successful in String response
Log.e("response", response);
try {
JSONObject jsonObject = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = jsonObject.getString("success");
if (success.equals("1")) {
sessionManager.saveAnswersOfTheDay(extra_questions_id, users_id, extra_answer, timeStamp_date);
Toast.makeText(mCntx.getApplicationContext(), R.string.successQuestionsOfTheDay, Toast.LENGTH_SHORT).show();
}
if (success.equals("alreadySubmitted")) {
Toast.makeText(mCntx.getApplicationContext(), R.string.submit_extra_questions_once_a_day, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(mCntx.getApplicationContext(), "Error! " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("sellresponseerror", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("extra_questions_id", extra_questions_id);
params.put("users_id", users_id);
params.put("extra_answer", extra_answer);
params.put("timeStamp_date", timeStamp_date);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mCntx);
requestQueue.add(stringRequest);
}
#Override
public int getItemCount() {
return extraQuestionList.size();
}
public class ExtraQuestionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
SeekBar seekBar;
OnExtraAnswerListener onExtraAnswerListener;
public ExtraQuestionViewHolder(#NonNull View itemView, OnExtraAnswerListener onExtraAnswerListener) {
super(itemView);
title = itemView.findViewById(R.id.textViewTitle);
seekBar = itemView.findViewById(R.id.seekBar);
this.onExtraAnswerListener = onExtraAnswerListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExtraAnswerListener.onExtraAnswerClick(getAdapterPosition());
}
}
public interface OnExtraAnswerListener {
void onExtraAnswerClick(int position);
}
}

RecyclerView work with localhost but dont show items with online server

Hi everyone My problem is weird. I have an app that works with volley and mysql. When I launch the app using xampp it works fine. The list is saved in the adapter and adapter works well in the recycler view. But when I change the url to my mysql database hosted on my website, the recycler view does not show the data. The JSON data is correctly received and saved correctly in the Arraylist (check it with Toast messages). I have the same problem in real devices
Android Studio will not throw me any error or warning running
Rubros
public class Rubros {
String nombre;
String rubro_id;
public Rubros(String nombre, String rubro_id) {
this.nombre = nombre;
this.rubro_id = rubro_id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRubro_id() {
return rubro_id;
}
public void setRubro_id(String rubro_id) {
this.rubro_id = rubro_id;
}
}
ListaRubros.class
public class ListaRubros extends AppCompatActivity {
RecyclerView rv_rubros;
RubroAdapter adapter;
List <Rubros> listarubros;
String categoria;
String categoria_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_rubros);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Buscamos la categoria
Bundle bundle = getIntent().getExtras();
categoria = bundle.getString("categoria");
setTitle(categoria);
categoria_id = bundle.getString("categoria_id");
//Declaramos variable textview
listarubros= new ArrayList<>();
//cargamos la lista de rubros
rv_rubros = (RecyclerView) findViewById(R.id.rv_rubros);
//Preparamos el adapter
rv_rubros.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv_rubros.setLayoutManager(llm);
//guardamos la lista en adapter
cargarRubros(categoria_id);
adapter = new RubroAdapter(listarubros);
rv_rubros.setAdapter(adapter);
//agregamos el onClick Listener
adapter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String rubro=listarubros.get(rv_rubros.getChildAdapterPosition(view)).getNombre();
String rubro_id=listarubros.get(rv_rubros.getChildAdapterPosition(view)).getRubro_id();
Intent intent = new Intent(ListaRubros.this,ListaNegocios.class);
intent.putExtra("rubro",rubro);
intent.putExtra("rubro_id",rubro_id);
startActivity(intent);
}
});
}
public void cargarRubros(String categoria){
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://10.0.3.2/listin/plantilla/sql/vistarubros_categoria_id.php?cc="+categoria; //Creamos la url
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
response = response.replace("][",",");
if (response.length()>0){
try {
JSONArray ja = new JSONArray(response);
for(int i=0;i<ja.length();i+=2){
try {
Rubros rubro = new Rubros(ja.getString(i),ja.getString(i+1));
listarubros.add(rubro);
Toast.makeText(getApplicationContext(),listarubros.get(0).getNombre(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
}
}
RubrosAdapter
public class RubroAdapter extends RecyclerView.Adapter<RubroAdapter.DatosRubroViewHolder>
implements View.OnClickListener{
List<Rubros> listarubros;
private View.OnClickListener listener;
public RubroAdapter(List<Rubros> listarubros) {
this.listarubros = listarubros;
}
#NonNull
#Override
public RubroAdapter.DatosRubroViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.vista_rv_rubros,parent,false);
v.setOnClickListener(this);
DatosRubroViewHolder holder = new DatosRubroViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(#NonNull RubroAdapter.DatosRubroViewHolder holder, int position) {
holder.rubro.setText(listarubros.get(position).getNombre());
holder.rubro_id.setText(listarubros.get(position).getRubro_id());
}
#Override
public int getItemCount() {
return listarubros.size();
}
public void setOnClickListener(View.OnClickListener listener){
this.listener=listener;
}
#Override
public void onClick(View view) {
if(listener!=null){
listener.onClick(view);
}
}
public static class DatosRubroViewHolder extends RecyclerView.ViewHolder{
TextView rubro;
TextView rubro_id;
public DatosRubroViewHolder(View itemView){
super(itemView);
rubro = (TextView) itemView.findViewById(R.id.tv_rubro);
rubro_id = (TextView) itemView.findViewById(R.id.tv_rubro_id);
}
}
}
EDIT
I already solved the problem. I had forgotten to add adapter.notifyDataSetChanged (); after saving the data in the arraylist

how to checked items from recyclerview to show on another activity recyclerview on button click

Hi I am new android developer i have stuck in my project. Problem is i want to user select items by checked box and after they click on view items button then open a another activity in which shows all those selected items in recyclerview in that recyclerview item name, price, and quantity.
This is my code
OderItems Activity, OderitemAdapter and OrderItemModel.
OderItems Activity
`public class OrderItems extends AppCompatActivity` {
public static final String KEY_ADSID="adsId";
public RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.order_item_recyclerview);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(OrderItems.this,ViewOrder.class));
}
});
parseOrder();
}
public void parseOrder()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.url_ORDERLISTING,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("Response",jsonObject.toString());
if (jsonObject.optString("status").equalsIgnoreCase("1"))
{
// String no_task= jsonObject.getString("error_msg");
Toast.makeText(OrderItems.this,"No Order List List !",Toast.LENGTH_LONG).show();
// txt_noTask.setText("No Task Is Available");
// progressDialog.dismiss();
}
if (jsonObject.optString("status").equalsIgnoreCase("0") || jsonObject.optString("message").equalsIgnoreCase("Success"))
{
// Toast.makeText(getActivity(),jsonObject.toString(),Toast.LENGTH_LONG).show();
JSONArray jsonArray= jsonObject.getJSONArray("ItemList");
ArrayList<OrderItemModel> list =new ArrayList<>();
for (int i=0;i<jsonArray.length();i++)
{
// TodayTaskModel todayTask = new TodayTaskModel();
OrderItemModel orderitemmodel = new OrderItemModel();
JSONObject jsonObj= jsonArray.getJSONObject(i);
String product_Name =jsonObj.getString("productName");
String product_Price =jsonObj.getString("productPrice");
String package_img =jsonObj.getString("productImg");
// For Set data
orderitemmodel.setProductName(product_Name);
orderitemmodel.setProductPrice(product_Price);
orderitemmodel.setProductImg(package_img);
list.add(orderitemmodel);
}
// Setup and Handover data to recyclerview
OrderItemAdapter adapter=new OrderItemAdapter(getApplicationContext(),list);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setHasFixedSize(true);
}
} catch (JSONException e) {
e.printStackTrace();
}
//pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OrderItems.this,"Server is not Responding !!! ", Toast.LENGTH_LONG).show();
// Toast.makeText(SpamActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ADSID,"101");
return params;
}
};
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
OderitemAdapter
public class OrderItemAdapter extends RecyclerView.Adapter<OrderItemAdapter.ViewHolder> {
ArrayList<OrderItemModel> orderItemList;
Context context;
SqlHandler sqlHandler;
static double summ;
public OrderItemAdapter(Context c, ArrayList<OrderItemModel> orderItemList)
{
this.context=c;
this.orderItemList=orderItemList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.order_item_layout, parent, false);
sqlHandler = new SqlHandler(context);
return new OrderItemAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int i) {
final OrderItemModel position=orderItemList.get(i);
holder.txt_ProductName.setText(position.getProductName());
holder.txt_ProductPrice.setText(position.getProductPrice());
holder.urlProductImg=position.getProductImg();
holder.strRate = position.getProductPrice();
holder.strQuantity=position.getProductQty();
if (holder.urlProductImg.isEmpty()) { //url.isEmpty()
Picasso.with(context)
.load(R.drawable.localbizlist)
.placeholder(R.drawable.localbizlist)
.error(R.drawable.localbizlist)
.into(holder.img_product);
}else{
Picasso.with(context)
.load(orderItemList.get(i).getProductImg())
.placeholder(R.drawable.localbizlist)
.error(R.drawable.localbizlist)
.into(holder.img_product); //this is your ImageView
}
}
#Override
public int getItemCount() {
return orderItemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
CheckBox chkOrder;
ImageView img_product;
TextView txt_ProductName,txt_ProductPrice;
Spinner itemSpinner;
String urlProductImg,strRate,strQuantity,strProductName;
public ViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
img_product=(ImageView)itemView.findViewById(R.id.img_product);
txt_ProductName=(TextView)itemView.findViewById(R.id.productName);
txt_ProductPrice=(TextView)itemView.findViewById(R.id.productPrice);
chkOrder=(CheckBox)itemView.findViewById(R.id.chk_order_status);
itemSpinner = (Spinner)itemView.findViewById(R.id.item_spinner);
List<String> itemQuuantity=new ArrayList<String>();
itemQuuantity.add("1");
itemQuuantity.add("2");
itemQuuantity.add("3");
itemQuuantity.add("4");
itemQuuantity.add("5");
ArrayAdapter<String> itemAdapter=new ArrayAdapter<String>(context,android.R.layout.simple_spinner_dropdown_item,itemQuuantity);
itemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
itemSpinner.setAdapter(itemAdapter);
chkOrder.setOnClickListener(this);
}
#Override
public void onClick(View view) {
context = view.getContext();
double TotalBill=0.00;
if (view.getId()==chkOrder.getId())
{
if (chkOrder.isChecked())
{
double spQuantity = Double.parseDouble(itemSpinner.getSelectedItem().toString());
double itemRate = Double.parseDouble(strRate);
double itemPrice = (spQuantity * itemRate);
TotalBill+=itemPrice;
String strQuatity=Double.toString(spQuantity);
String strTotalBill = Double.toString(TotalBill);
String strProductName= String.valueOf(txt_ProductName.getText());
String strProductPrice=String.valueOf(txt_ProductPrice.getText());
Toast.makeText(context,"Checked Item Bill"+TotalBill,Toast.LENGTH_LONG).show();
String query = "INSERT INTO ORDER_ITEMS(product_name,product_quantity,product_price) values ('"
+ strProductName + "','" + strProductPrice + "','"+strQuatity+"')";
sqlHandler.executeQuery(query);
SumOrderBill(TotalBill);
Toast.makeText(context,"Record Save",Toast.LENGTH_LONG).show();
// showlist();
// strIDCheckBoxStatus=String.valueOf(chkOrder.getId());
}else
{
//saveInSp("Checked",false);
double spQuantity = Double.parseDouble(itemSpinner.getSelectedItem().toString());
double itemRate = Double.parseDouble(strRate);
double itemPrice = (spQuantity * itemRate);
TotalBill+=itemPrice;
String strIdProductName= String.valueOf(txt_ProductName.getText());
Toast.makeText(context,"UNCHECKED Item Bill"+TotalBill,Toast.LENGTH_LONG).show();
MinOrderBill(TotalBill);
String delQuery = "DELETE FROM PHONE_CONTACTS WHERE slno='"+strIdProductName+"' ";
sqlHandler.executeQuery(delQuery);
// showlist();
}
}
}
public void SumOrderBill(double ftotal)
{
summ+=ftotal;
String total2 = String.valueOf(summ);
Toast.makeText(context, "Total Bill"+total2,Toast.LENGTH_LONG).show();
// SharedPreferences myPrefsLogin=context.getSharedPreferences("biling", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = myPrefsLogin.edit();
// editor.putString("Total", total2);
// editor.commit();
}
public void MinOrderBill(double ftotal)
{
summ-=ftotal;
String total2 = String.valueOf(summ);
Toast.makeText(context, "Detection"+summ,Toast.LENGTH_LONG).show();
// SharedPreferences myPrefsLogin=context.getSharedPreferences("biling", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = myPrefsLogin.edit();
// editor.putString("Total", total2);
// editor.commit();
}
}
}
public class OrderItemModel {
private String status;
private String message;
private String productId;
private String productName;
private String productType;
private String productQty;
private String productImg;
private String productPrice;
public OrderItemModel()
{
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProductQty() {
return productQty;
}
public void setProductQty(String productQty) {
this.productQty = productQty;
}
public String getProductImg() {
return productImg;
}
public void setProductImg(String productImg) {
this.productImg = productImg;
}
}
Please help me for ViewOrder Activity
Here I am posting my code. After selecting checkbox user click on save button and onClick of that, another activity is open with only selected items(As you want),
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rView);
context = this;
numberlist = new ArrayList<Number>();
for (int i = 0; i < 50; i++) {
Number number = new Number(String.valueOf(i), false);
number.setSelected(false);
numberlist.add(number);
}
customAdapter = new CustomAdapter(context, R.layout.list_item, numberlist);
recyclerView.setAdapter(customAdapter);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numberlist= customAdapter.onItemSelected();
customAdapter.setList(numberlist);
}
});
Here is my adapter's code:
public class CustomAdapter extends BaseAdapter {
private ArrayList<Number> numList;
Context context;
int textViewResourceId;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<Number> numberlist) {
this.numList = new ArrayList<Number>();
this.numList.addAll(numberlist);
this.context=context;
this.textViewResourceId=textViewResourceId;
}
#Override
public int getCount() {
return numList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
convertView=LayoutInflater.from(context).inflate(textViewResourceId,null);
holder = new ViewHolder();
convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Number number = (Number) cb.getTag();
number.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Number number = numList.get(position);
holder.name.setText(number.getName());
holder.name.setChecked(number.isSelected());
holder.name.setTag(number);
if(number.isSelect()){
holder.name.setVisibility(View.GONE);
}
else {
holder.name.setVisibility(View.VISIBLE);
}
return convertView;
}
public ArrayList<Number> onItemSelected() {
StringBuffer text = new StringBuffer();
ArrayList<Number> numberArrayList=new ArrayList<Number>();
text.append("following are selected...\n");
for (int i = 0; i < numList.size(); i++) {
Number item = numList.get(i);
if (item.isSelected()) {
numList.get(i).setSelect(true);
numberArrayList.add(numList.get(i));
text.append("\n" + item.getName());
}
}
Log.e("Text ", text.toString());
return numberArrayList;
}
public void setList(ArrayList<Number> list){
numList.clear();
numList.addAll(list);
notifyDataSetChanged();
}
}

I want to display data from Json in recyclerview in Android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want display Review text and its Rating in another activity.
Here is my AddReview class
public class AddReview extends AppCompatActivity implements ServerRequests.AddReviewreponse {
private Button submit;
EditText addReview;
RatingBar ratingBar;
Toolbar toolbar;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_review);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setAddReviewreponse(this);
addReview=(EditText)findViewById(R.id.reviewBox);
ratingBar=(RatingBar) findViewById(R.id.ratingBar);
submit=(Button)findViewById(R.id.submit);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add Review");
// toolbar.setNavigationIcon(R.drawable.back_30);
/* toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});*/
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String ReviewTxt = addReview.getText().toString();
float rating = ratingBar.getRating();
JSONObject obj = jsonParser.makeAddReviewJson(1,1,ReviewTxt,rating);
Log.e("final Json", obj.toString());
serverRequests.addReview(obj);
} catch (Exception e) {
}
/* Reviews.displayName.setText(RegisterActivity.name.getText().toString());
Reviews.displayReview.setText("Your Review : "+addReview.getText().toString());
Reviews.displayStars.setRating(ratingBar.getRating());*/
/* Reviews.displayStars.setText("Your Rating : " + ratingBar.getRating());
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
Reviews.displayDate.setText(currentDateTimeString);*/
AlertDialog alertDialog = new AlertDialog.Builder(AddReview.this).create();
alertDialog.setTitle("Review Submitted!");
alertDialog.setMessage("Thanks for your valueable review!");
alertDialog.setIcon(R.drawable.star_48);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
// startActivity(new Intent(getApplicationContext(), Reviews.class));
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
#Override
public void onAddReviewReposne(JSONObject object) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is the Review class where I want to display the review and its ratings
public class Reviews extends AppCompatActivity implements ServerRequests.GetReviewResponse {
public static TextView displayReview, displayDate, displayName;
public static RatingBar displayStars;
Button addReviewBtn;
android.support.v7.widget.Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviews);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view1);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// mAdapter = new ReviewAdapter(getDataSet(jsonObject));
mRecyclerView.setAdapter(mAdapter);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top1);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Reviews");
/*displayReview = (TextView) findViewById(R.id.review);
displayStars = (RatingBar) findViewById(R.id.rating);
displayDate = (TextView)findViewById(R.id.displayDate);
displayName = (TextView)findViewById(R.id.displayName);*/
addReviewBtn = (Button)findViewById(R.id.addReviewBtn);
addReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddReview.class));
}
});
ServerRequests serverRequests=new ServerRequests(getApplicationContext());
serverRequests.setReviewResponse(this);
serverRequests.getReviews("one");
}
private ArrayList<Review> getDataSet(JSONArray array) {
ArrayList results = new ArrayList<Review>();
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
Review obj = new Review(object.getInt("reviewId"),object.getInt("userId"),object.getString("Name"),object.getString("Review"),object.getLong("rating"));
results.add(i,obj);
}
catch (Exception e){
e.printStackTrace();
}
}
return results;
}
#Override
public void onGetReviewResponse(JSONArray jsonObject) {
mAdapter = new ReviewAdapter(getDataSet(jsonObject));
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is the ReviewAdapter
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<Review> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public static TextView name,review;
public static RatingBar rating;
public DataObjectHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
review = (TextView) itemView.findViewById(R.id.review);
rating = (RatingBar) itemView.findViewById(R.id.rating);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public ReviewAdapter(ArrayList<Review> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_review, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.name.setText(mDataset.get(position).getName());
holder.review.setText(mDataset.get(position).getReview());
holder.rating.setRating(mDataset.get(position).getRating());
}
public void addItem(Review dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
This is the Pojo class of Review
public class Review {
private String name,review;
private float rating;
private int reviewId,userId;
public Review (int ReviewId, int UserId, String Name, String Review, float Rating){
reviewId = ReviewId;
userId = UserId;
name = Name;
review = Review;
rating = Rating;
}
public int getReviewId() {
return reviewId;
}
public void setReviewId(int reviewId) {
this.reviewId = reviewId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
}
This is the ServerRequests for add and get Review
//------------For add review------------------------------
public void setAddReviewreponse(AddReviewreponse addreviewreponse) {
this.addreviewreponse = addreviewreponse;
}
private AddReviewreponse addreviewreponse;
public interface AddReviewreponse {
void onAddReviewReposne(JSONObject object);
}
public void addReview(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.ADD_REVIEW, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (addreviewreponse != null) {
addreviewreponse.onAddReviewReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
//------------For get review------------------------------
public void setReviewResponse(GetReviewResponse reviewResponse) {
this.getReviewResponse = reviewResponse;
}
public GetReviewResponse getReviewResponse;
public interface GetReviewResponse {
void onGetReviewResponse(JSONArray jsonObject);
}
public void getReviews(final String id) {
StringRequest request = new StringRequest(Request.Method.GET, Services.GET_REVIEW,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
Log.e("Server response", response);
if (array.length() > 0) {
if (getReviewResponse != null) {
getReviewResponse.onGetReviewResponse(array);
}
} else {
Log.e("Error is occured", "asd");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//send error repsonse back to user
Log.e("Error: ", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("courseId", id);
return params;
}
};
queue.add(request);
}
This is JSONParser class for AddReview
//--------For Add review---------------------------------
public JSONObject makeAddReviewJson(int studentID, int courseID, String reviewTxt, float rating) throws JSONException {
JSONObject object = new JSONObject();
object.put("studentId", studentID);
object.put("courseId", courseID);
object.put("review", reviewTxt);
object.put("ratings", rating);
return object;
}
This is the JSON response I am getting after posting the Review
E/final Json: {"studentId":1,"courseId":1,"review":"Hellooooo","ratings":3}
E/Json response: {"success":true,"msg":"Your review has been added successfully","data":{"reviewsId":18}}
private ArrayList<Review> getDataSet(JSONArray array) {
ArrayList results = new ArrayList<Review>();
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
Review obj = new Review(object.getInt("studentId"),object.getInt("courseId"),object.getString("Review"),object.getLong("rating"));
results.add(i,obj);
}
catch (Exception e){
e.printStackTrace();
}
}
return results;
}
try to change your getDataSet function with above code and check with debug point if you get any problem in some line. feel free to ask further will help you
EDIT:
You need to change your Pojo class of Review also. Because in JSON response you are not getting userId and reviewId. Hope you understand

Fragment is not refreshing after button clicked in adapter-listview

I have five tabs they are 1.home 2.menu 3.cart 4.account 5.more.Here cart tab consist of list view which is having the remove button in it,when i click on that remove button it must refresh the fragment itself so that it can load new data from the Json
MainActivity.class
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Session cartsession=new Session(getApplicationContext());
if (cartsession.isLoggedIn()){
if (position==2){
((Cart) pageAdapter.getItem(position)).cartdata();
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
}
TabAdapter.class
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Cart.Java
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
SharedPreferences loginPreferences;
SharedPreferences.Editor loginPrefsEditor;
TextView cartstatus,cartempty;
LinearLayout linearlay;
RelativeLayout cartvisible;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartstatus = (TextView) cartfrag.findViewById(R.id.cartstatus);
cartempty = (TextView) cartfrag.findViewById(R.id.cartempty);
linearlay = (LinearLayout) cartfrag.findViewById(R.id.linearlay);
cartvisible = (RelativeLayout) cartfrag.findViewById(R.id.cartvisible);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged = new Session(getActivity());
if (cartlogged.isLoggedIn()) {
cartitems.clear();
cartdata();
} else {
cartstatus.setText("Please Login");
}
return cartfrag;
}
void cartdata() {
cartitems.clear();
SharedPreferences customerid = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid = customerid.getString("customerid", "");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("empty")) {
cartstatus.setVisibility(View.GONE);
cartempty.setText("Your Cart is Empty");
} else {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
linearlay.setVisibility(View.VISIBLE);
cartvisible.setVisibility(View.GONE);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
JSONObject subobj = response.getJSONObject("details");
String subtext = subobj.getString("subtotal");
loginPrefsEditor.putString("Price", subtext);
loginPrefsEditor.commit();
subtotal.setText(subtext);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
}
CartAdapter.class
public class CartAdapter extends BaseAdapter {
Context context;
TextView quantity, basenamecart, cartprice;
ImageButton delete;
private List<JSONParser> cartitems;
LayoutInflater inflater;
String removequantity, removeitemprice,removebasename;
public CartAdapter(Context context, List<JSONParser> cartitems) {
this.context = context;
this.cartitems = cartitems;
}
#Override
public int getCount() {
return cartitems.size();
}
#Override
public Object getItem(int position) {
return cartitems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart();
}
});
}
return convertView;
}
private void removecart(){
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}
}
You need to remove the concerned object from the list cartitems and then call the notifyDataSetChanged() method to notify the any dependent views to refresh itself.
Documentation here
Also, this is not the correct way to implement a BaseAdapter and handle changes in it. Maybe this will help : http://androidadapternotifiydatasetchanged.blogspot.in/
Also, try using the new RecyclerView in order to implement such things. It is available in the support library and definitely a good way to display collections and also makes it easy to add remove items with default animations too. Please read through it. A starting point http://developer.android.com/training/material/lists-cards.html
see added line and updated line.
add make sure only remove item from list if removed successfully from server.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
final int pos =position; // added line
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart(pos); //updated line
}
});
}
return convertView;
}
public void updateCartitems(List<JSONParser> newCartitems) {
cartitems.clear();
cartitems.addAll(newCartitems);
this.notifyDataSetChanged();
}
private void removecart(int pos){ // updated line
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
cartitems.remove(pos); //added line
updateCartitems(cartitems);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}

Categories

Resources