Retrofit : Do not have field Id - android

When I try to have Json result, I have all field that I want but without id field. I don't understand this I give you the json result :
[{"id":8671,"dateEvenement":"2017-08-14T16:49:34.404+02:00","type":"Competition","activitePlannings":[{"id":8675,"nomActivite":"Base-ball","idActivite":8654},{"id":8674,"nomActivite":"Balle de Hockey","idActivite":8653},{"id":8676,"nomActivite":"Course d'obstacles","idActivite":8655}],"groupe":{"id":8667,"nomGroupe":"Benjamin","groupeActivites":[{"id":8673,"nomGroupe":"Benjamin","idGroupe":8667,"nomActivite":"Balle de Hockey","idActivite":8653}]},"utilisateurPlannings":[{"id":8679,"nomUtilisateur":"Colart","prenomUtilisateur":"Pierre","type":"RESPONSABLE","datePlanning":"2017-08-14T16:49:34.404+02:00","idDisponibilite":0,"typePlanning":"Competition","nomGroupe":"Benjamin","planningId":8671,"utilisateurId":8651}],"Disponibilites":[],"validate":false}]
And I have this class with setter and getter for sure :
public class Planning {
private int id;
private String dateEvenement;
private Groupe groupe;
private String type;
private List<ActivitePlanning> activitePlannings;
private List<UtilisateurPlanning> utilisateurPlannings;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public Planning() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return dateEvenement;
}
public void setDate(String date) {
Date date2 = null;
try {
date2 = format.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
this.dateEvenement = sdf.format(date2.getTime());
}
public ejplanningandroid.ejplanningandroid.Models.Groupe getGroupe() {
return groupe;
}
public void setGroupe(ejplanningandroid.ejplanningandroid.Models.Groupe groupe) {
this.groupe = groupe;
}
public List<UtilisateurPlanning> getUtilisateurPlannings() {
return utilisateurPlannings;
}
public void setUtilisateurPlannings(List<UtilisateurPlanning> utilisateurPlannings) {
this.utilisateurPlannings = utilisateurPlannings;
}
public List<ActivitePlanning> getActivitePlannings() {
return activitePlannings;
}
public void setActivitePlannings(List<ActivitePlanning> activitePlannings) {
this.activitePlannings = activitePlannings;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
I set my Planning Object with this class :
#Override
public View getView(int position, View view, ViewGroup parent) {
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.rowplanning,parent, false);
}
PlanningViewHolder planningViewHolder = (PlanningViewHolder)view.getTag();
if(planningViewHolder==null){
planningViewHolder= new PlanningViewHolder();
planningViewHolder.Date = (TextView)view.findViewById(R.id.Date);
planningViewHolder.NomActivite =(TextView)view.findViewById(R.id.Activite);
planningViewHolder.NomGroupe = (TextView)view.findViewById(R.id.NomGroupe);
planningViewHolder.Type = (TextView)view.findViewById(R.id.Type);
planningViewHolder.Utilisateur = (TextView)view.findViewById(R.id.Utilisateur);
view.setTag(planningViewHolder);
}
Planning planning = getItem(position);
planningViewHolder.Type.setText("Type : "+planning.getType());
planningViewHolder.NomGroupe.setText("Groupe : "+planning.getGroupe().getNomGroupe());
String nomActivite = setStringFromArrayActivite(planning.getActivitePlannings());
planningViewHolder.NomActivite.setText("Activités : "+nomActivite);
planningViewHolder.Date.setText(planning.getDate());
String nomUtilisateur =setStringFromArrayUtilisateur(planning.getUtilisateurPlannings());
planningViewHolder.Utilisateur.setText("Moniteurs : "+nomUtilisateur);
return view;
}
My Asynctask :
public class PlanningCandidatureTask extends AsyncTask<String,Void,List<Planning>> {
#Override
protected List<Planning> doInBackground(String... params) {
try {
InterfaceService interfaceService = new RestAdapter.Builder()
.setEndpoint(InterfaceService.path).build()
.create(InterfaceService.class);
String login = params[0];
String pass = params[1];
List<Planning> PlanningList = interfaceService.getPlanningByValidation(login, pass);
return PlanningList;
}catch (RetrofitError retrofitError){
return null;
}
}
}
But when want to see if i have an id, this field have a 0 value. I have try to change type to String but it does not work ...
EDITED :
public class CandidatureFragment extends Fragment {
private ListView mListView;
private View view;
private List<Planning> listPlanning = new ArrayList<Planning>();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.candidature_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listViewPlanning2);
PlanningCandidatureTask planningTask =
(PlanningCandidatureTask) new PlanningCandidatureTask()
.execute(((MainActivity) getActivity()).getUtilisateur().getLogin(),
((MainActivity) getActivity()).getUtilisateur().getMotDepasse());
try {
if(planningTask.get() != null) {
for (int i = 0; i < planningTask.get().size(); i++) {
Planning planning=new Planning();
Log.i("Test",planningTask.get().get(i).getGroupe()+"");
planning.setDate(planningTask.get().get(i).getDate());
planning.setType(planningTask.get().get(i).getType());
planning.setGroupe(planningTask.get().get(i).getGroupe());
planning.setActivitePlannings(planningTask.get().get(i).getActivitePlannings());
planning.setUtilisateurPlannings(planningTask.get().get(i).getUtilisateurPlannings());
listPlanning.add(planning);
}
PlanningAdapter adapter = new PlanningAdapter(view.getContext(),listPlanning);
mListView.setAdapter(adapter);
}else
{
Toast.makeText(view.getContext(), "ERREUR DE CONNECTION", Toast.LENGTH_SHORT).show();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
final PlanningAdapter adapter = new PlanningAdapter(view.getContext(),listPlanning);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(container.getContext());
builder.setTitle("Validation");
builder.setMessage("Voulez vous vraiment ajouter une candidature à ce planning ?")
.setCancelable(false).setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Planning selectedFromList = (Planning) parent.getAdapter().getItem(position);
/*PostTask postTask =
(PostTask) new PostTask()
.execute(((MainActivity) getActivity()).getUtilisateur().getLogin(),
((MainActivity) getActivity()).getUtilisateur().getMotDepasse(),
"none","0");*/
dialog.cancel();
Toast.makeText(view.getContext(), "item selectionnné : "+selectedFromList.getId(), Toast.LENGTH_LONG).show();
}
}).setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
});
return view;
}
Get retrofit ::
#GET("/planning/unvalidate/")
List<Planning> getPlanningByValidation(#Query("login") String login, #Query("password") String password);
public class PlanningViewHolder {
public TextView Date;
public TextView NomGroupe;
public TextView Type;
public TextView NomActivite;
public TextView Utilisateur;
}

Related

recycle view not showing

I'm not able to see the recycle view, not sure where It has gone wrong. It would be great if you can help me.
Fragment
public class CallDurationFragment extends Fragment {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ArrayList<CallHistroy> callList = new ArrayList<>();
ArrayList<CallHistroy> callListTemp = new ArrayList<>();
ArrayList<CallHistroy> callObject = new ArrayList<>();
ArrayList<CallHistroy> callListText = new ArrayList<>();
private CallDurationFragment.OnFragmentInteractionListener mListener;
private RecyclerView rvCall;
private RecyclerView.Adapter callAdaptor;
private RecyclerView.LayoutManager eLayoutManager;
private EditText phoneNumber;
private static final int DIALOG_DATE_PICKER = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_callduration_list, container, false);
phoneNumber = (EditText) getActivity().findViewById(editTextSearchKeyPhoneNo);
Context context = getActivity();
rvCall = (RecyclerView) rootView.findViewById(R.id.rvCallDuration);
rvCall.setHasFixedSize(true);
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
phoneNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
callListTemp = getAllCallRecords();
for(int i = 0 ; i < callListTemp.size() ; i++)
if(callListTemp.get(i).getPhoneNumber().contains(s.toString()) )
callListText.add(callListTemp.get(i));
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
return rootView;
}
public ArrayList<CallHistroy> getAllCallRecords(){
DatabaseReference ref = database.getReference();
ref.child("Call").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
callObject.clear();
HashMap<String,Object> call = null;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while(items.hasNext()){
DataSnapshot item = items.next();
Log.e("Listener",item.toString() );
call =(HashMap<String, Object>) item.getValue();
callObject.add(new CallHistroy(call.get("phoneNumber").toString(),call.get("mode").toString(),call.get("duration").toString(), call.get("date").toString(),item.getKey()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return callObject;
}
public ArrayList<CallHistroy> calculateIncomingOutgoing(){
if(callListText.size() > 0){
callList = callListText;
}else {
callList = getAllCallRecords();
}
ArrayList<CallHistroy> callHistroyIncomingOutgoing = new ArrayList<>();
if(callList.size() > 0){
if(callList.get(0).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), "0", callList.get(0).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), callList.get(0).getDuration(), "0"));
}
}
for( int i = 1 ; i < callList.size() ; i++){
boolean setValue = false;
for (int j = 0; j < callHistroyIncomingOutgoing.size() ;j++){
if( callHistroyIncomingOutgoing.get(j).getPhoneNumber().equals(callList.get(i).getPhoneNumber())){
setValue = true;
int incoming = Integer.parseInt(callHistroyIncomingOutgoing.get(j).getIncomingDuration());
int outgoing = Integer.parseInt( callHistroyIncomingOutgoing.get(j).getOutgoingDuration());
int duration = Integer.parseInt( callList.get(i).getDuration());
if(callList.get(i).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming), String.valueOf(outgoing + duration));
}else{
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming + duration), String.valueOf(outgoing));
}
}
}
if(!setValue) {
if(callList.get(i).getMode() == "Outgoing") {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), "0", callList.get(i).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), callList.get(i).getDuration(), "0"));
}
}
}
return callHistroyIncomingOutgoing;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CallListFragment.OnFragmentInteractionListener) {
mListener = (CallDurationFragment.OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onDestroyView(){
super.onDestroyView();
}
#Override
public void onDestroy(){
super.onDestroy();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Adaptor
RecyclerView.Adapter<CallDurationAdapter.ViewHolder> {
private List<CallHistroy> mCalls;
private Context mContext;
public CallDurationAdapter(Context context, List<CallHistroy> calls) {
mCalls = calls;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public CallDurationAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View callDurationView = inflater.inflate(R.layout.item_call_duration_details, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(callDurationView);
return viewHolder;
}
#Override
public void onBindViewHolder(CallDurationAdapter.ViewHolder viewHolder, final int position) {
// Get the data model based on position
final CallHistroy ch = mCalls.get(position);
// Set item views based on your views and data model
viewHolder._phoneNoTextView.setText(ch.getPhoneNumber());
viewHolder._incomingTextView.setText(ch.getIncomingDuration());
viewHolder._outgoingTextView.setText(ch.getOutgoingDuration());
final String key = ch.getKey();
}
#Override
public int getItemCount() {
return mCalls.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView _phoneNoTextView;
public TextView _incomingTextView;
public TextView _outgoingTextView;
public ViewHolder(View itemView) {
super(itemView);
_phoneNoTextView = (TextView) itemView.findViewById(R.id.rvs_duration_phone_no);
_incomingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_outing_total_call);
_outgoingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_incoming_total_call);
}
}
}
Activity
public class CallDurationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_duration);
CallDurationFragment newFragment = new CallDurationFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recordFragmentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void refreshCallDuration(View v) {
Intent intent = new Intent(this, CallDurationActivity.class);
startActivity(intent);
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
}
protected void onDestroy() {
super.onDestroy();
}
public void onBackCallDuration(View v) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Object
public class CallHistroy implements Comparable<CallHistroy> {
String phoneNumber;
String mode;
String duration;
String date;
String key;
String incomingDuration;
String outgoingDuration;
int totalIncoming;
int totalOutgoing;
public CallHistroy(String _phontNumber, String _incomingDuration, String _outgoingDuration ){
setPhoneNumber( _phontNumber );
setIncomingDuration( _incomingDuration );
setOutgoingDuration( _outgoingDuration );
}
public CallHistroy(String _date, int _totalIncoming, int _totalOutgoing ){
setDate(_date);
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateCall(int _totalIncoming, int _totalOutgoing){
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateDuration(String _incomingDuration, String _outgoingDuration){
setOutgoingDuration( _incomingDuration );
setIncomingDuration( _outgoingDuration );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date, String _key ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
setKey( _key );
}
public String getIncomingDuration() {
return incomingDuration;
}
public String getOutgoingDuration() {
return outgoingDuration;
}
public int getTotalIncoming() {
return totalIncoming;
}
public int getTotalOutgoing() {
return totalOutgoing;
}
public void setIncomingDuration(String incomingDuration) {
this.incomingDuration = incomingDuration;
}
public void setOutgoingDuration(String outgoingDuration) {
this.outgoingDuration = outgoingDuration;
}
public void setTotalIncoming(int totalIncoming) {
this.totalIncoming = totalIncoming;
}
public void setTotalOutgoing(int totalOutgoing) {
this.totalOutgoing = totalOutgoing;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getDate() {
return date;
}
public String getMode() {
return mode;
}
public String getDuration() {
return duration;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setDate(String date) {
this.date = date;
}
public void setDuration(String duration) {
this.duration = duration;
}
public void setMode(String mode) {
this.mode = mode;
}
#Override
public int compareTo(#NonNull CallHistroy callHistroyObject) {
String[] part = callHistroyObject.date.split("/");
String[] part1 = date.split("/");
int date = Integer.parseInt(part[0]);
int month = Integer.parseInt(part[1]);
String _year = part[2];
int year = Integer.parseInt(_year.substring(0,4));
int date1 = Integer.parseInt(part1[0]);
int month1 = Integer.parseInt(part1[1]);
String _year1 = part1[2];
int year1 = Integer.parseInt(_year1.substring(0,4));
if(year > year1)
return -1;
else if(month > month1)
return -1;
else if(date >date1)
return -1;
else
return 0;
}
}
You're setting your layout manager before it's created
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
should be
eLayoutManager = new LinearLayoutManager(getActivity());
rvCall.setLayoutManager(eLayoutManager);

ListVew Repeating same row from MySql database in Android

I had an ListVew where I have to show the orders List from Database.I have Multiple orders in Mysql Database but only one order is continuously repeating in ListVew.Any help regarding this is Appreciated.
Here is my Adapter Class
public class OrderApprovalAdapter extends ArrayAdapter
{
List list1 = new ArrayList();
Context context;
public OrderApprovalAdapter(#NonNull Context context, #NonNull int Resource)
{
super(context, Resource);
this.context = context;
}
#Override
public void add(#Nullable Object object)
{
super.add(object);
list1.add(object);
}
#Override
public int getCount()
{
return list1.size();
}
#Override
public Object getItem(int position)
{
return list1.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final OrderApprovalAdapter.ContactHolder contactHolder;
View row;
row = convertView;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.order_approval_format, parent, false);
contactHolder = new ContactHolder();
contactHolder.date = (TextView) row.findViewById(R.id.invoice_date);
contactHolder.orderid = (TextView) row.findViewById(R.id.invoice_no);
contactHolder.shopname = (TextView) row.findViewById(R.id.shop_name);
contactHolder.ownername = (TextView) row.findViewById(R.id.owner_name);
contactHolder.mobile=(TextView) row.findViewById(R.id.mobile_noo);
contactHolder.location=(TextView)row.findViewById(R.id.location);
contactHolder.itemscount=(TextView)row.findViewById(R.id.items);
contactHolder.amount=(TextView)row.findViewById(R.id.total);
contactHolder.Approval=(Button)row.findViewById(R.id.Approve_btn);
contactHolder.Decline=(Button)row.findViewById(R.id.decline_btn);
row.setTag(contactHolder);
} else
{
contactHolder = (ContactHolder) row.getTag();
}
final OrderApprovalDetails contacts = (OrderApprovalDetails) this.getItem(position);
contactHolder.date.setText(contacts.getDate());
contactHolder.orderid.setText(contacts.getOrderid());
contactHolder.shopname.setText(contacts.getShopname());
contactHolder.ownername.setText(contacts.getOwnername());
contactHolder.mobile.setText(contacts.getMobile());
contactHolder.location.setText(contacts.getLocation());
contactHolder.itemscount.setText(contacts.getItemscount());
contactHolder.amount.setText(contacts.getAmount());
contactHolder.Approval.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Approved", Toast.LENGTH_SHORT).show();
}
});
contactHolder.Decline.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Decline", Toast.LENGTH_SHORT).show();
}
});
return row;
}
static class ContactHolder
{
TextView date,orderid,shopname,ownername,mobile,location,itemscount,amount;
Button Approval,Decline;
}
}
Retriving Data From Database
class OrdersListBackgroundTask extends AsyncTask<Void,Void,String>
{
#Override
protected void onPreExecute()
{
OrdersList_url="http://10.0.2.2/accounts/OrderForm2.php";
}
#Override
protected String doInBackground(Void... params)
{
try {
URL url=new URL(OrdersList_url);
HttpURLConnection httpURLConnection=
(HttpURLConnection)url.openConnection();
InputStream is= httpURLConnection.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
StringBuilder sb=new StringBuilder();
while ((JSON_STRING4=br.readLine())!=null)
{
sb.append(JSON_STRING4+ "");
}
br.close();
is.close();
httpURLConnection.disconnect();
return sb.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
//TextView tv=(TextView)findViewById(R.id.tv);
//tv.setText(result);
json_string4=result;
}
}
Sending Through intent to Next Page
public void Orders_List(View v)//Button click
{
if (json_string4==null)
{
Toast.makeText(this, "Get Orders First", Toast.LENGTH_SHORT).show();
}else
{
Intent i1=new Intent(this,OrdersList.class);
i1.putExtra("json_data4",json_string4);
startActivity(i1);
}
}
Usage in MainActivity
json_string4=getIntent().getExtras().getString("json_data4");
listView_Orders=(ListView)findViewById(R.id.listViewOrderlist);
listView_Orders.setItemsCanFocus(true);
search_filter=(EditText)findViewById(R.id.search_et);
orderApprovalAdapter=new
OrderApprovalAdapter(this,R.layout.order_approval_format);
listView_Orders.setAdapter(orderApprovalAdapter);
//listView_Orders.setTextFilterEnabled(true);
try
{
jsonObject=new JSONObject(json_string4);
jsonArray=jsonObject.getJSONArray("orders");
int count=0;
for (int i=0;i<jsonArray.length();i++)
{
JSONObject jo=jsonArray.getJSONObject(i);
date=jo.getString("date");
orderid=jo.getString("orderid");
shopname=jo.getString("shopname");
ownername=jo.getString("ownername");
mobile=jo.getString("mobile");
location=jo.getString("location");
items=jo.getString("items_count");
amount=jo.getString("amount");
OrderApprovalDetails orderApprovalDetails=new OrderApprovalDetails(date,orderid,shopname,ownername,mobile,location,items,amount,Approve,Decline);
orderApprovalAdapter.add(orderApprovalDetails);
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
OrderApprovalDetails Class
public class OrderApprovalDetails
{
public static String
date,orderid,shopname,ownername,mobile,location,itemscount,amount;
public static Button Approval,Decline;
public OrderApprovalDetails(String date,String orderid,String shopname,String ownername,String mobile,String location,String itemscount,String amount,Button Approval,Button Decline)
{
this.setDate(date);
this.setOrderid(orderid);
this.setShopname(shopname);
this.setOwnername(ownername);
this.setMobile(mobile);
this.setLocation(location);
this.setItemscount(itemscount);
this.setAmount(amount);
this.setApproval(Approval);
this.setDecline(Decline);
}
public String getDate()
{
return date;
}
public static Button getApproval() {
return Approval;
}
public static void setApproval(Button approval) {
Approval = approval;
}
public static Button getDecline() {
return Decline;
}
public static void setDecline(Button decline) {
Decline = decline;
}
public void setDate(String date) {
this.date = date;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
public String getShopname() {
return shopname;
}
public void setShopname(String shopname) {
this.shopname = shopname;
}
public String getOwnername() {
return ownername;
}
public void setOwnername(String ownername) {
this.ownername = ownername;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getItemscount() {
return itemscount;
}
public void setItemscount(String itemscount) {
this.itemscount = itemscount;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Don't know where I did Mistake,Please Help me to findout that,Thanks in Advance.
You class members should never be declared static as you have done here -
public class OrderApprovalDetails
{
public static String date,orderid,shopname,ownername,mobile,location,itemscount,amount;
change this to
public class OrderApprovalDetails
{
public String date,orderid,shopname,ownername,mobile,location,itemscount,amount;

Recyclerview sort by time ascending

I have a recyclerview that display news.
News is composed by name_news,image_news,time_news.
I am getting the data from mysqldatabse.
This is my adapter class:
public class PostAdapter2 extends RecyclerView.Adapter<PostAdapter2.ViewHolder>{
public Context c;
public FragmentManager mContext;
public ArrayList<News_data> original_items = new ArrayList<>();
public ArrayList<News_data> filtered_items = new ArrayList<>();
public ArrayList<Simplenews_data> original_items2 = new ArrayList<>();
public ArrayList<Simplenews_data> filtered_items2 = new ArrayList<>();
// ItemFilter mFilters = new ItemFilter();
public PostAdapter2(Context c, ArrayList<News_data> postList) {
this.c = c;
this.original_items = postList;
this.filtered_items = postList;
}
public PostAdapter2(FragmentManager mContext, ArrayList<Simplenews_data> postList) {
this.mContext = mContext;
this.original_items2 = postList;
this.filtered_items2 = postList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_news, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
try {
final Simplenews_data post = filtered_items2.get(position);
PicassoClient.downloadImage(c, post.getImage_simplenews(), holder.image_news);
holder.txt_news_title.setText(post.getName_simplenews());
holder.txt_date.setText(post.getTime_simplenews());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick() {
Bundle x = new Bundle();
x.putString("news_title", post.getName_simplenews());
x.putString("news", post.getDesc_simplenews());
x.putString("image",post.getImage_simplenews());
x.putString("time",post.getTime_simplenews());
x.putString("date",post.getDate_simplenews());
Fragment descriptionFragment = new DescriptionFragment();
FragmentTransaction transaction = mContext.beginTransaction();
descriptionFragment.setArguments(x);
transaction.replace(R.id.framelayout, descriptionFragment).addToBackStack(null).commit();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return filtered_items2.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
TextView txt_news_title,txt_date;
ImageView image_news;
public ViewHolder(View itemView) {
super(itemView);
txt_news_title = (TextView) itemView.findViewById(R.id.txt_news_title);
txt_date = (TextView) itemView.findViewById(R.id.txt_timedate);
image_news = (ImageView) itemView.findViewById(R.id.image_news);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
try {
this.itemClickListener.onItemClick();
}catch (Exception e)
{
e.printStackTrace();
}
}
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener=itemClickListener;
}
}
}
I am using a PHP interface to add news.
The getTime_simplenews() contains the news sumbmitted time format as : 14:00
So i want to display the immediate news in Top of recyclerview not under the previous news.
Thanks a lot.
UPDATED :
public class Simplenews_data {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
Fragment Code:
public void parseJson2(String response) {
try {
JSONArray array = new JSONArray(response);
JSONObject jsonObject = null;
post_array2.clear();
Simplenews_data p;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
int id_simplenews = jsonObject.getInt("id_simplenews");
String name_simplenews = jsonObject.getString("name_simplenews");
String image_simplenews = jsonObject.getString("image_simplenews");
String desc_simplenews = jsonObject.getString("desc_simplenews");
String time_simplenews = jsonObject.getString("time_simplenews");
String date_simplenews = jsonObject.getString("date_simplenews");
p = new Simplenews_data();
p.setId_simplenews(id_simplenews);
p.setName_simplenews(name_simplenews);
p.setImage_simplenews(image_simplenews);
p.setDesc_simplenews(desc_simplenews);
p.setTime_simplenews(time_simplenews);
p.setDate_simplenews(date_simplenews);
post_array2.add(p);
}
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
e.printStackTrace();
}
adapter = new PostAdapter2(getFragmentManager(), post_array2);
recycler_post.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
I have updated your model class and implemented Comparable to it
public class Simplenews_data implements Comparable<Simplenews_data> {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
#Override
public int compareTo(MyObject o) {
Date newDate = formatDateTime(o.getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
Date inputDate = formatDateTime(getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
return inputDate.compareTo(newDate);
}
public Date formatDateTime(String date, String fromFormat, String toFormat) {
Date d = null;
try {
d = new SimpleDateFormat(fromFormat, Locale.US).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new SimpleDateFormat(toFormat, Locale.US).parse(d);
}
}
Sort the list using below code
Collections.sort(yourList);

How to perform sorting operation on list view android?

In my application i am using Custom adapter ans showing the service data to list view. Every thing works fine for me but i want to sort the list view items based on "fare" condition.
Any one help me how to sort my list view based on "fare" (lowest to highest)
My code:
BusData.java :
package com.reloadapp.reload.data;
/**
* Created by user1 on 5/21/2015.
*/
public class BusData
{
private String routescheduleid;
private String companyname;
private String companyid;
private String deptime;
private String arrtime;
private int fare;
private String buslabel;
private String avaliableseats;
private String bustypename;
private String difftime;
boolean ac,non_ac,sleeper,non_slepeer;
private String pickuproutescheduleid;
private String pickupname;
public String getDropoffname() {
return Dropoffname;
}
public void setDropoffname(String dropoffname) {
Dropoffname = dropoffname;
}
public boolean getac() {
return ac;
}
public void setac(boolean ac) {
this.ac = ac;
}
public boolean getnon_ac() {
return non_ac;
}
public void setnon_ac(boolean non_ac) {
this.non_ac = non_ac;
}
public boolean getsleeper() {
return sleeper;
}
public void setsleeper(boolean sleeper) {
this.sleeper = sleeper;
}
public boolean getnon_slepeer() {
return non_slepeer;
}
public void setnon_slepeer(boolean non_slepeer) {
this.non_slepeer = non_slepeer;
}
private String Dropoffname;
public BusData()
{
}
public String getPickuproutescheduleid() {
return pickuproutescheduleid;
}
public void setPickuproutescheduleid(String pickuproutescheduleid) {
this.pickuproutescheduleid = pickuproutescheduleid;
}
public String getPickupname() {
return pickupname;
}
public void setPickupname(String pickupname) {
this.pickupname = pickupname;
}
public String getDifftime() {
return difftime;
}
public void setDifftime(String difftime) {
this.difftime = difftime;
}
public BusData(String routescheduleid,String companyname,String companyid,String deptime,String arrtime,int fare,String buslabel,String avaliableseats,String bustypename,String difftime)
{
this.routescheduleid=routescheduleid;
this.companyname=companyname;
this.companyid=companyid;
this.deptime=deptime;
this.arrtime=arrtime;
this.fare=fare;
this.buslabel=buslabel;
this.avaliableseats=avaliableseats;
this.bustypename=bustypename;
this.difftime=difftime;
}
public String getRoutescheduleid() {
return routescheduleid;
}
public void setRoutescheduleid(String routescheduleid) {
this.routescheduleid = routescheduleid;
}
public String getCompanyname() {
return companyname;
}
public void setCompanyname(String companyname) {
this.companyname = companyname;
}
public String getCompanyid() {
return companyid;
}
public void setCompanyid(String companyid) {
this.companyid = companyid;
}
public String getDeptime() {
return deptime;
}
public void setDeptime(String deptime) {
this.deptime = deptime;
}
public String getArrtime() {
return arrtime;
}
public void setArrtime(String arrtime) {
this.arrtime = arrtime;
}
public int getFare() {
return fare;
}
public void setFare(int fare) {
this.fare = fare;
}
public String getBuslabel() {
return buslabel;
}
public void setBuslabel(String buslabel) {
this.buslabel = buslabel;
}
public String getAvaliableseats() {
return avaliableseats;
}
public void setAvaliableseats(String avaliableseats) {
this.avaliableseats = avaliableseats;
}
public String getBustypename() {
return bustypename;
}
public void setBustypename(String bustypename) {
this.bustypename = bustypename;
}
}
BusAdapter.java:
public class BusDataAdapter extends BaseAdapter {
ArrayList<BusData> bpData;
private ArrayList<BusData> arraylist;
private Activity activity;
ProgressDialog mProgressDialog;
public static String journey_bus;
public static String rid;
String travelname, travetime = null;
private LayoutInflater inflater;
//SearchActivity obj=new SearchActivity(journey_bus);
public BusDataAdapter(Activity activity, ArrayList<BusData> bpData) {
// TODO Auto-generated constructor stub
this.activity = activity;
this.bpData = bpData;
mProgressDialog = new ProgressDialog(activity);
inflater = LayoutInflater.from(activity);
}
public void setJourneyBus(String journey_bus) {
this.journey_bus = journey_bus;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return bpData.size();
}
#Override
public Object getItem(int location) {
// TODO Auto-generated method stub
return location;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.buslistviewitems, null);
Typeface custom_bold = Typeface.createFromAsset(activity.getAssets(),
"fonts/SourceSansPro_Semibold.ttf");
Typeface custom_regular = Typeface.createFromAsset(activity.getAssets(),
"fonts/SourceSansPro_Light.ttf");
viewHolder.deptime = (TextView) convertView
.findViewById(R.id.deptime);
viewHolder.difftime = (TextView) convertView
.findViewById(R.id.difftime);
viewHolder.busfare = (TextView) convertView
.findViewById(R.id.busfare);
viewHolder.buslabel = (TextView) convertView
.findViewById(R.id.buslabel);
viewHolder.routeid = (TextView) convertView
.findViewById(R.id.routeid);
viewHolder.bustypename = (TextView) convertView
.findViewById(R.id.bustypename);
viewHolder.availableseat = (TextView) convertView
.findViewById(R.id.avaliableseats);
viewHolder.businfo = (LinearLayout) convertView.findViewById(R.id.businfo);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.deptime.setText(bpData.get(position).getDeptime() + "-" + bpData.get(position).getArrtime());
// travetime = bpData.get(position).getDeptime() + "-" + bpData.get(position).getArrtime();
viewHolder.difftime.setText(bpData.get(position).getDifftime());
viewHolder.busfare.setText(bpData.get(position).getFare());
viewHolder.buslabel.setText(bpData.get(position).getBuslabel());
viewHolder.routeid.setText(bpData.get(position).getRoutescheduleid());
viewHolder.bustypename.setText(bpData.get(position).getBustypename());
// travelname = bpData.get(position).getBuslabel();
viewHolder.availableseat.setText(bpData.get(position).getAvaliableseats() + "Seats");
if (bpData.get(position).getAvaliableseats().equalsIgnoreCase("0")) {
viewHolder.availableseat.setText("Sold Out");
} else {
viewHolder.availableseat.setText(bpData.get(position).getAvaliableseats() + "Seats");
}
class ViewHolder {
TextView difftime, deptime, busfare, buslabel, routeid, bustypename, availableseat;
LinearLayout businfo;
//Button businfo;
}}
FromtoActivity.java:
public class FromtoActivity extends AppCompatActivity {
ArrayList<BusData> bdata = new ArrayList<BusData>();
ArrayList<BusData> filter_list = new ArrayList<BusData>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fromto);
Intent intent = getIntent();
json_object = intent.getStringExtra("json_objcet");
busdata();
}
public void busdata() {
try {
bdata.clear();
travel_list.clear();
filter_list.clear();
JSONObject result = new JSONObject(json_object);
JSONObject Data = result.getJSONObject("Data");
routearray = Data.getJSONArray("Route");
for (int i = 0; i < routearray.length(); i++) {
// String companyid = routearray.getJSONObject(i).getString("CompanyId");
CompanyName = routearray.getJSONObject(i).getString("CompanyName");
String deptime = routearray.getJSONObject(i).getString("DepTime");
routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
String arrtime = routearray.getJSONObject(i).getString("ArrTime");
/* String dtDeparture = "2014-12-15T13:30:00";
String dtArrival = "2014-12-15T23:00:00";*/
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dateDeparture = format.parse(deptime);
Date dateArrival = format.parse(arrtime);
dateArrival.compareTo(dateDeparture);
long diff = dateArrival.getTime() - dateDeparture.getTime();
long arrivaltime = dateArrival.getTime();
arrivaldate = new SimpleDateFormat("hh:mm a").format(new Date(arrivaltime));
long departuretime = dateDeparture.getTime();
depardate = new SimpleDateFormat("hh:mm a").format(new Date(departuretime));
/* Log.v("TAG_realarrtime",""+arrivaldate);
Log.v("TAG_realdeptime",""+depardate);
*/
long hours = TimeUnit.MILLISECONDS.toHours(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff) - hours * 60;
// System.out.println(hours + "." + minutes + "hrs");
msg = hours + "." + minutes + "hrs";
fare = routearray.getJSONObject(i).getInt("Fare");
hasac = routearray.getJSONObject(i).getString("HasAC");
hasnac = routearray.getJSONObject(i).getString("HasNAC");
hasseater = routearray.getJSONObject(i).getString("HasSeater");
hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
String isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
buslabel = routearray.getJSONObject(i).getString("BusLabel");
avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
bustypename = routearray.getJSONObject(i).getString("BusTypeName");
BusData bs = new BusData();
// bs.setCompanyname(CompanyName);
//bs.setCompanyid(companyid);
bs.setFare(fare);
bs.setBuslabel(CompanyName);
bs.setBustypename(bustypename);
bs.setAvaliableseats(avaliableseats);
bs.setArrtime(arrivaldate);
bs.setDeptime(depardate);
bs.setDifftime(msg);
bs.setac(routearray.getJSONObject(i).getBoolean("HasAC"));
bs.setnon_ac(routearray.getJSONObject(i).getBoolean("HasNAC"));
bs.setsleeper(routearray.getJSONObject(i).getBoolean("HasSleeper"));
bs.setnon_slepeer(routearray.getJSONObject(i).getBoolean("HasSeater"));
bs.setRoutescheduleid(routeScheduleId);
bdata.add(bs);
if (!travel_list.contains(bdata.get(i).getBuslabel()))
travel_list.add(bdata.get(i).getBuslabel());
}
adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
adapter.setJourneyBus(date_bus);
filter_list.addAll(bdata);
adapter = new BusDataAdapter(this, filter_list);
fromto.setAdapter(adapter);
/* adapter.setrouteid(routeScheduleId);
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
You should sort the list before call adapter to list the data.
Collections.sort(bdata, new Comparator<BusData>() {
public int compare(BusData o1, BusData o2) {
return o2.getFare().compareTo(o1.getFare());
}
});
for(BusData busData:bdata)
{
Log.e("Fare : ",busData.getFare());
}
After sorting completed call Adapter to list the data:
adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
adapter.setJourneyBus(date_bus);
filter_list.addAll(bdata);
adapter = new BusDataAdapter(this, filter_list);
fromto.setAdapter(adapter);
You can use Collections.sort method for this..
Do like this...
Collections.sort(filterlist, new Comparator<bData>() {
#Override
public int compare(bData lhs, bData rhs) {
return (lhs.getFair() > rhs.getFair()) ? -1 : (lhs.getFair() > rhs.getFair()) ? 1 : 0;
}
});
You need to use comparator api in android.
Comparator<BusData> comparator=new Comparator<BusData>() {
#Override
public int compare(final BusData lhs, final BusData rhs) {
return lhs.getFare().equals(rhs.getFare());
}
};
Collections.sort(busDataList,comparator);
then your list will be sorted.
You need to give already sorted collection of buses to your adapter. Adapter shouldn't be responsible for sorting and ListView as well.
Try this:
Collections.sort(bdata, new Comparator<BusData>() {
#Override
public int compare(BusData lhs, BusData rhs) {
return lhs.getFare() > rhs.getFare();
}
});
You can use the Comparator and sort the list
class FareComparator implements Comparator{
public int Compare(Object o1,Object o2){
BusData s1=(BusData)o1;
BusData s2=(BusData)o2;
if(s1.fare==s2.fare)
return 0;
else if(s1.fare>s2.fare)
return -1;
else
return 1;
}
}
and use
Collections.sort(bdata,new FareComparator());
before the
adapter = new BusDataAdapter(this, bdata);

EditText values in a RecyclerView gives same value after 5th position

I have a RecyclerView and each row has a EditText also. I am adding item to RecyclerView by searching them and then I type the quantity in the edit text. Then I send it to the server to store using json format. Item add is working perfectly. There is no edit text value swapping problem also when scrolling. I can display 5 rows in the screen.
Problem is when I send item to the server, edit text values in bottom rows get the same after 5th row.
These are the rows I am adding to the recyclerview.Printed List that send to the server.
Item : 7.50-15 10PR FM CEAT Quantity : 1
Item : 5.60-15 04PR K 511 CEAT Quantity : 2
Item : 2.75-18 04PR SECURA F85 CEAT (F) Quantity : 3
Item : 3.00-17 06PR SECURA ZOOM CEAT (R) Quantity : 4
Item : 6.50-14 10PR FM CEAT Quantity : 5
Item : 5.00-12 04PR GRIP MASTER CEAT Quantity : 5
Item : 4.00-08 06PR AUTO RAJA RPG Quantity : 5
Item : 9.00-20 14PR CEAT CLT LUG Quantity : 5
Item : 8.25-20 14PR TR PLUS SUNTRAC Quantity : 5
Item : 7.00-15 12PR FM CEAT Quantity : 5
After the 5th position Quantity is the same. My input value is not coming.
This is my SelectItem class -
public class SelectItem extends AppCompatActivity implements SelectItemAdapter.OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_item);
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
myRecyclerView = (RecyclerView) findViewById(R.id.selectedItemRecyclerView);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
spinner = (Spinner) findViewById(R.id.selectDistribChannel);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, YourDealerListFragment.disChannel);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
selectedDisChannel = spinner.getSelectedItem().toString();
sqLiteHandler = new SQLiteHandler(getApplicationContext());
myRecyclerViewAdapter = new SelectItemAdapter(this);
myRecyclerViewAdapter.setOnItemClickListener(this);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
myRecyclerViewAdapter.notifyDataSetChanged();
dealerName = DealerListAdapter.getDealerName();
dealerID = DealerListAdapter.getDealerID();
repID = DealerListAdapter.getRepID();
//order number
orderId = "70000001";
if (newOrderId == null) {
newOrderId = orderId;
}
bAdd = (Button) findViewById(R.id.bAdd);
bAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (myRecyclerViewAdapter.getItemCount() != 0) {
new AlertDialog.Builder(SelectItem.this)
.setTitle("Confirmation")
.setMessage("Do you want to send?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
checkOrderNo();
}
})
.setNegativeButton(android.R.string.no, null).show();
} else {
Toast.makeText(getApplicationContext(), "Empty List", Toast.LENGTH_SHORT).show();
}
}
});
//textView.setText(dealerName);
getSupportActionBar().setTitle(dealerName);
final AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
adapter = new MaterialSuggestionAdapter(getApplicationContext());
acTextView.setAdapter(adapter);
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product result = adapter.getItem(position);
String newName = result.getMatName().toString();
String newQty = String.valueOf(result.getMatQuantity());
String newPCode = result.getMatNo().toString();
String newPlant = result.getMatPlant().toString();
if (!newName.equals("")) {
if (myRecyclerViewAdapter.getItemCount() > 0) {
if (!isPresent(newPlant, newPCode, myRecyclerViewAdapter)) {
myRecyclerViewAdapter.add(1, newName, newQty, newPCode, newPlant);
} else {
Toast.makeText(getApplicationContext(), "Product Already in the List", Toast.LENGTH_SHORT).show();
}
} else {
myRecyclerViewAdapter.add(0, newName, newQty, newPCode, newPlant);
}
} else {
Toast.makeText(getApplicationContext(), "Invalied Item!", Toast.LENGTH_SHORT).show();
}
acTextView.setText("");
}
});
}
private boolean isPresent(String newPlant, String newPCode, SelectItemAdapter myRecyclerViewAdapter) {
boolean isPresent = false;
for (int i = 0; i < myRecyclerViewAdapter.getItemCount(); i++) {
if (newPCode.equalsIgnoreCase(myRecyclerViewAdapter.getItemPCode(i).toString()) && newPlant.equalsIgnoreCase(myRecyclerViewAdapter.getItemPlant(i).toString())) {
isPresent = true;
break;
}
}
return isPresent;
}
//send items for one order
private class SendItemAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... arg0) {
//Create JSON string start
json_string = "{\"sending_items\":[";
for (int i = 0; i < myRecyclerViewAdapter.getItemCount(); i++) {
/* if (myRecyclerView.findViewHolderForLayoutPosition(i) instanceof SelectItemAdapter.ItemHolder) {
SelectItemAdapter.ItemHolder childHolder = (SelectItemAdapter.ItemHolder) myRecyclerView.findViewHolderForLayoutPosition(i);
numberPickerNumber = childHolder.getQtyNumber();
}*/
getNumPicNumber(i);
//Repeat and loop this until all objects are added (and add try+catch)
try {
JSONObject obj_new = new JSONObject();
obj_new.put("order_no", orderIdForItemTable);
obj_new.put("items", myRecyclerViewAdapter.getItemName(i).toString());
obj_new.put("items_no", myRecyclerViewAdapter.getItemPCode(i).toString());
obj_new.put("plant", myRecyclerViewAdapter.getItemPlant(i).toString());
obj_new.put("quantity", numberPickerNumber);
json_string = json_string + obj_new.toString() + ",";
} catch (JSONException e) {
e.printStackTrace();
}
}
//Close JSON string
json_string = json_string.substring(0, json_string.length() - 1);
json_string += "]}";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3500);
HttpConnectionParams.setSoTimeout(httpParams, 1000);
HttpClient client = new DefaultHttpClient(httpParams);
String url = AppConfig.URL_ITEMS_SEND;
HttpPost request = new HttpPost(url);
try {
request.setEntity(new ByteArrayEntity(json_string.getBytes("UTF8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.setHeader("json", json_string);
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
Log.i("", "excuting request");
HttpResponse response = null;
try {
response = client.execute(request);
Log.d("HTTP Response", response.getStatusLine().toString());
try {
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("Server Response", responseBody);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
finish();
Bundle basket = new Bundle();
basket.putString("dealerName", dealerName);
basket.putString("orderNo", newOrderId);
basket.putString("jsonString", json_string);
Intent intent = new Intent(SelectItem.this, ItemCart.class);
intent.putExtras(basket);
startActivity(intent);
finish();
//Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
}
}
private String getNumPicNumber(int i) {
if (myRecyclerView.findViewHolderForLayoutPosition(i) instanceof SelectItemAdapter.ItemHolder) {
SelectItemAdapter.ItemHolder childHolder = (SelectItemAdapter.ItemHolder) myRecyclerView.findViewHolderForLayoutPosition(i);
numberPickerNumber = childHolder.getQtyNumber();
}
return numberPickerNumber;
}
#Override
public void onItemClick(SelectItemAdapter.ItemHolder item, int position) {
Toast.makeText(this,
"Remove " + position + " : " + item.getItemName(),
Toast.LENGTH_SHORT).show();
myRecyclerViewAdapter.remove(position);
}
private void checkOrderNo() {
showDialog();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
final String nowDate = df.format(new Date());
//final day of the month
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
final String lastDate = sdf.format(lastDayOfMonth);
Log.d("Last day ", sdf.format(lastDayOfMonth) + " // Today" + nowDate);
// Tag used to cancel the insert
String tag_string_req = "req_insert";
final StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_ITEM_DETAILS_SEND, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
if (jObj.names().get(0).equals("found")) {
newOrderId = jObj.getString("found").toString();
orderIdForItemTable = newOrderId;
new SendItemAsync().execute();
Log.d(TAG, "newOrderId: " + newOrderId);
Log.d(TAG, "New repID 2 inserted into sqlite: " + newOrderId + " " + nowDate);
sqLiteHandler.addItemDetails(newOrderId, repID, dealerID, nowDate, lastDate, selectedDisChannel);
} else {
Toast.makeText(getApplicationContext(), "Invalied Request", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Inserting Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("order_no", orderId);
params.put("repID", repID);
params.put("dealerID", dealerID);
params.put("nowDate", nowDate);
params.put("lastDate", lastDate);
params.put("disChannel", selectedDisChannel);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(6000, 1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
My Adapter class.
public class SelectItemAdapter extends RecyclerView.Adapter<SelectItemAdapter.ItemHolder> {
private List<String> itemsName, itemsQty, itemsPCode, itemPlant;
private OnItemClickListener onItemClickListener;
private LayoutInflater layoutInflater;
private RecyclerView myRecyclerview;
public SelectItemAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
itemsName = new ArrayList<String>();
itemsQty = new ArrayList<String>();
itemsPCode = new ArrayList<String>();
itemPlant = new ArrayList<String>();
}
#Override
public SelectItemAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.custom_row_selected_item, parent, false);
return new ItemHolder(itemView, this);
}
#Override
public void onBindViewHolder(SelectItemAdapter.ItemHolder holder, int position) {
holder.setItemName(itemsName.get(position));
holder.setItemQty(itemsQty.get(position));
holder.setItemPCode(itemsPCode.get(position));
holder.setItemPlant(itemPlant.get(position));
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return itemsName.size();
}
public Object getItemName(int position) {
return itemsName.get(position);
}
public Object getItemPCode(int position) {
return itemsPCode.get(position);
}
public Object getItemPlant(int position) {
return itemPlant.get(position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
onItemClickListener = listener;
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public interface OnItemClickListener {
public void onItemClick(ItemHolder item, int position);
}
public void add(int location, String iName, String iQty, String iPCode, String iPlant) {
itemsName.add(location, iName);
itemsQty.add(location, iQty);
itemsPCode.add(location, iPCode);
itemPlant.add(location, iPlant);
notifyItemInserted(location);
}
public void remove(int location) {
if (location >= itemsName.size())
return;
itemsName.remove(location);
notifyItemRemoved(location);
}
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private SelectItemAdapter parent;
TextView textItemName, txtPCode, txtAvailableQty, txtTempQty, txtPlant;
Button bRemove;
EditText numPicker;
public ItemHolder(View itemView, SelectItemAdapter parent) {
super(itemView);
this.parent = parent;
textItemName = (TextView) itemView.findViewById(R.id.txtProductName);
txtAvailableQty = (TextView) itemView.findViewById(R.id.txtAvailbleQty);
txtPCode = (TextView) itemView.findViewById(R.id.txtPCode);
txtPlant = (TextView) itemView.findViewById(R.id.txtPlant);
bRemove = (Button) itemView.findViewById(R.id.bRemove);
numPicker = (EditText) itemView.findViewById(R.id.numberPicker);
bRemove.setOnClickListener(this);
}
public void setItemName(CharSequence name) {
textItemName.setText(name);
}
public void setItemQty(CharSequence name) {
txtAvailableQty.setText(name);
}
public void setItemPCode(CharSequence name) {
txtPCode.setText(name);
}
public void setItemPlant(CharSequence name) {
txtPlant.setText(name);
}
public String getQtyNumber() {
return numPicker.getText().toString();
}
public CharSequence getItemName() {
return textItemName.getText();
}
public CharSequence getItemPCode() {
return txtPCode.getText();
}
#Override
public void onClick(View v) {
final OnItemClickListener listener = parent.getOnItemClickListener();
if (listener != null) {
listener.onItemClick(this, getPosition());
}
}
}
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
holder.setIsRecyclable(false);// set this in your adapter class as like it is
}
Override getItemViewType method
override fun getItemViewType(position: Int): Int {
return position
}
RecyclerView creates only as many view holders as are needed to display the on-screen portion of the dynamic content, plus a few extra. As the user scrolls through the list, the RecyclerView takes the off-screen views and rebinds them to the data which is scrolling onto the screen
// Items for recycler View
//binding data
private ArrayList<Data> Items;
//HashMap to store editText text afterTextChanged
//each editext in RecyclerView contains Unique Key And Value
private HashMap<String,String> sourceData=new HashMap<>();
Refer This RecyclerView Program
public class DataRecyclerView extends RecyclerView.Adapter<DataRecyclerView.DataViewHolder> {
private Context context;
// Items for recycler View
//binding data
private ArrayList<Data> Items;
private LayoutInflater layoutInflater;
//HashMap to store editText text afterTextChanged
//each editext in RecyclerView contains Unique Key And Value
private HashMap<String,String> sourceData=new HashMap<>();
DataRecyclerView(Context context,ArrayList<Data> Items)
{
this.Items=Items;
this.context=context;
layoutInflater=LayoutInflater.from(context);
}
#NonNull
#Override
public DataViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//DataBinding is used to bind Data
DataViewHolderBinding binding= DataBindingUtil.inflate(layoutInflater, R.layout.template,parent,false);
return new DataViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull DataViewHolder holder, int position) {
//Pass Data pojo to Holder
holder.bindData(Items.get(position));
}
#Override
public int getItemCount() {
return Items.size();
}
class DataViewHolder extends RecyclerView.ViewHolder {
private EditText amount;
DataViewHolder(DataViewHolderBinding itemView) {
super(itemView.getRoot());
binding=itemView;
amount=binding.PayAmount;
}
void bindData(Data data)//Data pojo for DataBinding
{
if(binding!=null) {
// data will automatically set to textViews In DataBinding
binding.setData(data);
//every time data binds to views
//get text of respective edittext and assign to that current edittext
if (sourceData.containsKey((String.valueOf(getAdapterPosition())))) {// checks current editText key is availible or not
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
amount.setText(sourceData.get((String.valueOf(getAdapterPosition()))).getAmount());
}else
{
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
amount.setText(null);
}
amount.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
//when user enter text into edittext
//editetext key already availible in sourceData
// then update the value to hashmap sourceData
if (sourceData.containsKey(String.valueOf(getAdapterPosition()))) {
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
if (!s.toString().trim().isEmpty()) {
if (!s.toString().trim().equals("0")) {
sourceData.put(String.valueOf(getAdapterPosition()),s.toString().trim());
} else {
sourceData.put(String.valueOf(getAdapterPosition()), s.toString().trim();
}
} else {
sourceData.put(String.valueOf(getAdapterPosition()),null );
}
}
}
else {
//when user enter text into edittext for the first time
//check for current Data pojo IDNumber with getAdapterPosition Items Data pojo IDNumber
//if it equal
//then we store text into hashmap for specific edittext by using adapterPosition as key
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
if (!s.toString().trim().isEmpty()) {
if (!s.toString().trim().equals("0")) {
sourceData.put(String.valueOf(getAdapterPosition()),s.toString().trim());
} else {
sourceData.put(String.valueOf(getAdapterPosition()), s.toString().trim();
}
} else {
sourceData.put(String.valueOf(getAdapterPosition()),null );
}
}
}
}
});
}
}
}
}
### Image Reference I can't show proper Image but Its Look Like this
The rows in RecyclerView is reusing while scrolling. So you need to create an array for save each EditText value
Then addTextChangedListener to your EditText to save the EditText value while you input
public void onBindViewHolder(SelectItemAdapter.ItemHolder holder, int position) {
...
holder.numPicker.setText(arrayForSaveEditTextValue[position]);
holder.numPicker.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
arrayForSaveEditTextValue[position] = arg0.toString();
}
});
...
}

Categories

Resources