I have a spinner contains three options "ALL","PAYMENTS" and "EXPENSES". These will show 3 listviews. "ALL" option will show the mixture of both "PAYMENT" and "EXPENSES".
My problem is I want to add setOnItemClickListener for both of the lists. Please refer the screenshot. I will pass certain values whenever I click on each list. Whenever I click on list in payments, it will go to paymentdetails activity, and whenever click on list in expense it will go to expense details activity. This should be same from "ALL". There are three different adapter for each list (i.e., ALL, PAYMENT and expense). The code is below.
try {
final JSONArray invoices = new JSONArray(common.json);
if (invoices.length() == 0) {
(rootView.findViewById(R.id.no_items)).setVisibility(View.VISIBLE);
return;
}
final ArrayList<String[]> invoiceListData = new ArrayList<>();
for (int i = 0; i < invoices.length(); i++) {
JSONObject jsonObject1 = invoices.getJSONObject(i);
String[] data = new String[9];
data[0] = jsonObject1.getString("ID");
data[1] = jsonObject1.getString("EntryNo");
data[2] = jsonObject1.getString("Company");
data[3] = jsonObject1.getString("Date");
data[4] = jsonObject1.getString("PaymentMode");
data[5] = jsonObject1.getString("Amount");
data[6] = jsonObject1.getString("Type");
data[7] = jsonObject1.getString("ApprovalDate");
data[8] = jsonObject1.getString("GeneralNotes");
invoiceListData.add(data);
}
adapter = new CustomAdapter(getContext(), invoiceListData, Common.PREVIOUSPAYMENTS);
invoiceList.setAdapter(adapter);
(rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
final ArrayList<String[]>PaymentListData=new ArrayList<>();
final ArrayList<String[]>ExpenseListData=new ArrayList<>();
for (int i = 0; i < invoiceListData.size(); i++) {
if (invoiceListData.get(i)[6].equals("Payment")) {
PaymentListData.add(invoiceListData.get(i));
invoiceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent approvalDetailsIntent = new Intent(getContext(),ApprovalDetails.class);
approvalDetailsIntent.putExtra(Common.APPROVALID,invoiceListData.get(position)[0]);
approvalDetailsIntent.putExtra(Common.ENTRYNO,invoiceListData.get(position)[1]);
approvalDetailsIntent.putExtra(Common.PAYMENT_MODE,invoiceListData.get(position)[2]);
approvalDetailsIntent.putExtra(Common.PAYMENT_DATE,invoiceListData.get(position)[3]);
approvalDetailsIntent.putExtra(Common.AMOUNT,invoiceListData.get(position)[4]);
approvalDetailsIntent.putExtra(Common.COMPANY_DETAILS,invoiceListData.get(position)[5]);
approvalDetailsIntent.putExtra(Common.GENERAL_NOTES,invoiceListData.get(position)[8]);
startActivity(approvalDetailsIntent);
}
});
} else if(invoiceListData.get(i)[6].equals("Expense")) {
(rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
invoiceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent approvalDetailsIntent = new Intent(getContext(),ApprovalExpenseDetails.class);
approvalDetailsIntent.putExtra(Common.APPROVALID,ExpenseListData.get(position)[0]);
approvalDetailsIntent.putExtra(Common.REFNO,ExpenseListData.get(position)[1]);
startActivity(approvalDetailsIntent);
}
});
}
}
Padapter = new CustomAdapter(getContext(),PaymentListData,Common.PREVIOUSPAYMENTS); //Global variable
invoiceList.setAdapter(Padapter);
(rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
Eadapter = new CustomAdapter(getContext(),ExpenseListData,Common.PREVIOUSPAYMENTS);
invoiceList.setAdapter(adapter);
(rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
// Values passing for payments only.I dont know whether invoiceListData.get()..is correct or not.
invoiceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent approvalDetailsIntent=new Intent(getContext(),ApprovalDetails.class);
approvalDetailsIntent.putExtra(Common.APPROVALID,invoiceListData.get(position)[0]);
approvalDetailsIntent.putExtra(Common.ENTRYNO,invoiceListData.get(position)[1]);
approvalDetailsIntent.putExtra(Common.PAYMENT_MODE,invoiceListData.get(position)[2]);
approvalDetailsIntent.putExtra(Common.PAYMENT_DATE,invoiceListData.get(position)[3]);
approvalDetailsIntent.putExtra(Common.AMOUNT,invoiceListData.get(position)[4]);
approvalDetailsIntent.putExtra(Common.COMPANY_DETAILS,invoiceListData.get(position)[5]);
approvalDetailsIntent.putExtra(Common.GENERAL_NOTES,invoiceListData.get(position)[8]);
startActivity(approvalDetailsIntent);
}
});
//values passing for expense only
invoiceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent approvalDetailsIntent = new Intent(getContext(),ApprovalExpenseDetails.class);
approvalDetailsIntent.putExtra(Common.APPROVALID,ExpenseListData.get(position)[0]);
approvalDetailsIntent.putExtra(Common.REFNO,ExpenseListData.get(position)[1]);
startActivity(approvalDetailsIntent);
}
});
you can not set onclicklistener for items in list ! you must set onclicklistener for each view in customAdapter
If you have same type of data for all 3 types follow certain development rules.
Create POJO (model) class for data. that help you in storing data in structured manner.
InvoiceData.java
public class InvoiceData {
private String Id;
private String EntryNo;
private String Company;
private String Date;
private String PaymentMode;
private String Amount;
private String Type; // "ALL", "Income", "Expense"
private String ApprovalDate;
private String GeneralNotes;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getEntryNo() {
return EntryNo;
}
public void setEntryNo(String entryNo) {
EntryNo = entryNo;
}
public String getCompany() {
return Company;
}
public void setCompany(String company) {
Company = company;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getPaymentMode() {
return PaymentMode;
}
public void setPaymentMode(String paymentMode) {
PaymentMode = paymentMode;
}
public String getAmount() {
return Amount;
}
public void setAmount(String amount) {
Amount = amount;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public String getApprovalDate() {
return ApprovalDate;
}
public void setApprovalDate(String approvalDate) {
ApprovalDate = approvalDate;
}
public String getGeneralNotes() {
return GeneralNotes;
}
public void setGeneralNotes(String generalNotes) {
GeneralNotes = generalNotes;
}
}
Set data like this with model
final ArrayList<InvoiceData> invoiceListData = new ArrayList<>();
JSONObject jsonObject1;
InvoiceData rowObject;
for (int i = 0; i < invoices.length(); i++) {
jsonObject1 = invoices.getJSONObject(i);
rowObject = new InvoiceData();
rowObject.setId(jsonObject1.getString("ID"));
rowObject.setEntryNo(jsonObject1.getString("EntryNo"));
rowObject.setCompany(jsonObject1.getString("Company"));
rowObject.setDate(jsonObject1.getString("Date"));
rowObject.setPaymentMode(jsonObject1.getString("PaymentMode"));
rowObject.setAmount(jsonObject1.getString("Amount"));
rowObject.setApprovalDate(jsonObject1.getString("ApprovalDate"));
rowObject.setGeneralNotes(jsonObject1.getString("GeneralNotes"));
rowObject.setType("Expense");
invoiceListData.add(rowObject);
}
adapter = new CustomAdapter(getContext(), invoiceListData, Common.PREVIOUSPAYMENTS);
invoiceList.setAdapter(adapter);
And to set on item click listener on Listview (Make sure it is listview b'z recycler view have no such method)
invoiceList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
InvoiceData rowObject = adapter.getItem(position);
if(rowObject != null) {
if(rowObject.getType().equals("Expense")) {
// write different code for Expense here
} else if(rowObject.getType().equals("Income")) {
// write different code for Income here
}
}
}
});
Hope this will help...
Related
Main activity.java
public class activity_3 extends AppCompatActivity {
TextView question,option_1,option_2,option_3,description,winnner;
NumberProgressBar option_progress1, option_progress2,option_progress3;
int val_1;
int val_2;
int val_3;
DatabaseReference Polldata_3;
String optionOne;
String optionTwo;
String optionThree;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
final String que = getIntent().getExtras().getString("que");
final String des = getIntent().getExtras().getString("des");
optionOne = getIntent().getExtras().getString("option1");
optionTwo = getIntent().getExtras().getString("option2");
optionThree = getIntent().getExtras().getString("option3");
final String id_user = getIntent().getExtras().getString("id");
val_1 = getIntent().getExtras().getInt("val1");
val_2 = getIntent().getExtras().getInt("val2");
val_2 = getIntent().getExtras().getInt("val3");
option_progress1 = (NumberProgressBar) findViewById(R.id.option1_progressbar);
option_progress2 = (NumberProgressBar) findViewById(R.id.option2_progressbar);
option_progress3 = (NumberProgressBar) findViewById(R.id.option3_progressbar);
Polldata_3 = FirebaseDatabase.getInstance().getReference("POll").child("poll_3");
final DatabaseReference answsersave = Polldata_3.child(id_user);
question = (TextView) findViewById(R.id.question_showpoll);
option_1 = (TextView) findViewById(R.id.option_1);
option_2 = (TextView) findViewById(R.id.option_2);
option_3 = (TextView) findViewById(R.id.option_3);
description = (TextView) findViewById(R.id.description_user_3);
winnner = (TextView) findViewById(R.id.winner);
option_1.setText(optionOne);
option_2.setText(optionTwo);
option_3.setText(optionThree);
question.setText(que);
description.setText(des);
option_progress1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress1.setProgress(val_1+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_1++;
answsersave.child("option_1_value").setValue(val_1);
//winnerdeclare();
}
});
option_progress2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress2.setProgress(val_2+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_2++;
answsersave.child("option_2_value").setValue(val_2);
// winnerdeclare();
}
});
option_progress3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress3.setProgress(val_3+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_3++;
// winnerdeclare();
answsersave.child("option_3_value").setValue(val_3);
}
});
}
}
ADAPTER CLASS
public class listview_3 extends AppCompatActivity {
ListView listviewpoll3;
private DatabaseReference Poll_data_3;
List<addpoll_3> addpoll_3List;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview_3);
listviewpoll3 = (ListView) findViewById(R.id.poll_listview_3);
Poll_data_3 = FirebaseDatabase.getInstance().getReference("POll").child("poll_3");
addpoll_3List = new ArrayList<>();
listviewpoll3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Intent intent = new Intent(listview_3.this, activity_3.class);
addpoll_3 poll = addpoll_3List.get(position);
final String optionone = poll.getOption_1();
final String optiontwo = poll.getOption_2();
final String optionthree = poll.getOption_3();
final String id_user = poll.getId();
final int value_1 = poll.getOption_1_value();
final int value_2 = poll.getOption_2_value();
final int value_3 = poll.getOption_3_value();
final String question = poll.getQuestion();
final String desp = poll.getDescription();
intent.putExtra("option1",optionone);
intent.putExtra("option2",optiontwo);
intent.putExtra("option3",optionthree);
intent.putExtra("id",id_user);
intent.putExtra("val1",value_1);
intent.putExtra("val2",value_2);
intent.putExtra("val3",value_3);
intent.putExtra("que",question);
intent.putExtra("descp",desp);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
Poll_data_3.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
addpoll_3List.clear();
for(DataSnapshot pollSnapshot: dataSnapshot.getChildren())
{
addpoll_3 poll = pollSnapshot.getValue(addpoll_3.class);
addpoll_3List.add(poll);
}
poll_list_3 adapter = new poll_list_3(listview_3.this,addpoll_3List);
listviewpoll3.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
list class
public class poll_list_3 extends ArrayAdapter<addpoll_3> {
private Activity context;
private List<addpoll_3> addpoll_3List;
public poll_list_3(Activity context, List<addpoll_3> addpoll_3List) {
super(context, R.layout.list_layout, addpoll_3List);
this.context = context;
this.addpoll_3List = addpoll_3List;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View viewitem = inflater.inflate(R.layout.list_layout,null);
TextView textViewName = (TextView) viewitem.findViewById(R.id.tv);
TextView textViewDesp = (TextView) viewitem.findViewById(R.id.tv1);
final addpoll_3 poll1 = addpoll_3List.get(position);
textViewName.setText(poll1.getQuestion());
textViewDesp.setText(poll1.getDescription());
return viewitem;
}
}
I am making a polling app where user can create a poll which is then stored in the firebase database and retrieved into listview of the app
when the user clicks on the list view he is directed to the the activity where there are number of progressbars
i have added a ON-click listener o the progress bar, So when user clicks on the progressbar the val of that option gets incremented in the database. so when a different user vote on the same poll the value from the database is fetched and value of the current user is added displaying the winner,but problem is the value of the progressbar1 gets the value from the database but the other two keep progress bar values start from 0 every time user clicks on the other two progress bar (ie 2 and 3).
please help
addpoll_3.java
public class addpoll_3 {
String id;
String question;
String description;
String option_1;
String option_2;
String option_3;
int option_1_value;
int option_2_value;
int option_3_value;
public addpoll_3(){}
public addpoll_3(String id, String question, String description, String option_1, String option_2, String option_3, int option_1_value, int option_2_value, int option_3_value) {
this.id = id;
this.question = question;
this.description = description;
this.option_1 = option_1;
this.option_2 = option_2;
this.option_3 = option_3;
this.option_1_value = option_1_value;
this.option_2_value = option_2_value;
this.option_3_value = option_3_value;
}
public String getId() {
return id;
}
public String getQuestion() {
return question;
}
public String getDescription() {
return description;
}
public String getOption_1() {
return option_1;
}
public String getOption_2() {
return option_2;
}
public String getOption_3() {
return option_3;
}
public int getOption_1_value() {
return option_1_value;
}
public int getOption_2_value() {
return option_2_value;
}
public int getOption_3_value() {
return option_3_value;
}
}
code:
Activity_3.java
val_1 = getIntent().getExtras().getInt("val1");
val_2 = getIntent().getExtras().getInt("val2");
val_3 = getIntent().getExtras().getInt("val3");
These were changes to be made
//Read from the database
myRef.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
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;
}
This is my Adapter Class for ListView,
Need Help, I am getting original positions, after filtering the listview, instead positions of filtered result. Code is given below, kindly go through it,if any query kindly ask.
// This is my Adapter Class for ListView
public class mAdapter extends BaseAdapter implements Filterable {
ArrayList<MlaData> dats;
public ArrayList<MlaData> filterList;
enter code here
CustomFilter filter;
Context c;
ImageLoader imageLoader;
public mAdapter(Context ctx,ArrayList<MlaData> dats){
this.c=ctx;
this.dats=dats;
this.filterList = dats;
}
#Override
public int getCount() {
return dats.size();
}
#Override
public Object getItem(int position) {
return dats.get(position);
}
#Override
public long getItemId(int position) {
int itemID;
// orig will be null only if we haven't filtered yet:
if (filterList == null)
{
itemID = position;
}
else
{
itemID = dats.indexOf(dats.get(position));
}
return itemID;
}
#Override
public Filter getFilter() {
if(filter==null)
{
filter = new CustomFilter();
}
return filter;
}
class CustomFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint!=null && constraint.length()>0)
{
constraint = constraint.toString().toUpperCase();
ArrayList<MlaData> filters = new ArrayList<MlaData>();
//Filtering
for(int i=0;i<filterList.size();i++)
{
if(filterList.get(i).getName().toUpperCase().contains(constraint)){
MlaData MlaDat = new MlaData(filterList.get(i).getName(),filterList.get(i).getImageUrl(),filterList.get(i).getArea(),filterList.get(i).getId(),filterList.get(i).getEmail());
filters.add(MlaDat);
}
results.count=filters.size();
results.values=filters;
}
}else {
results.count=filterList.size();
results.values=filterList;
}
return results;
}#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
dats=(ArrayList<MlaData>)results.values;
notifyDataSetChanged();
}
}
MainActivity.java
(Only The ListView OnClick Function) :
private ArrayList<MlaData> MlaDats = new ArrayList<MlaData>();
private String MlaNameString, MlaImageString, MlaIdString, MlaEmailString, MlaAreaString;
private GridView listView;
private mAdapter adapt;
private SearchView sv;
listView = (GridView) findViewById(R.id.mldata);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posi = (int) adapt.getItemId(position);
Intent intent = new Intent(Rajasthan_Mla.this, MainActivity.class);
// int pos = (int) adapt.getItemId(position);
String MLAID = MlaDats.get(posi).getId();
String MLANAME = MlaDats.get(posi).getName();
String MLAEMAIL = MlaDats.get(posi).getEmail();
String MLAIMAGE = MlaDats.get(posi).getImageUrl();
String MLAAREA=MlaDats.get(posi).getArea();
intent.putExtra("MLA_ID", MLAID);
intent.put
Extra("MLA_NAME", MLANAME);
intent.putExtra("MLA_EMAIL", MLAEMAIL);
intent.putExtra("MLA_IMAGE", MLAIMAGE);
intent.putExtra("MLA_AREA", MLAAREA);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("Mukesh", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MLAID", MLAID);
editor.putString("MLANAME",MLANAME);
editor.commit();
startActivity(intent);
}
});
DataModel Class :
package com.wdm.mukku.wdm;
public class MlaData {
private String name;
private String imageUrl;
private String area;
private String email;
private String id;
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return imageUrl;
}
public void setImage(String image) {
this.imageUrl = image;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public MlaData(String name,String image,String area,String id,String email) {
this.name=name;
this.imageUrl=image;
this.area=area;
this.id=id;
this.email=email;
}
public MlaData() {
}
}
You can get filtered listview's position by
((ListView) parent).getAdapter().getItem(position)
Example
private ArrayList MlaDats = new ArrayList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
MlaData mModel = ((ListView) parent).getAdapter().getItem(position);
String id = mModel.getId();
Log.d(TAG,"id = "+id);
}
});
First change this
public mAdapter(Context ctx,ArrayList<MlaData> dats){
this.c=ctx;
this.dats=dats;
// will create a new array instead of referencing to the same object
this.filterList = new ArrayList<MlaData>(dats);
}
Next don't modify dats anymore and only use the filtered list, so you will keep the original list and use that when you filter on something else.
So use this in your filter
// temp array to store filtered data
ArrayList<MlaData> filters = new ArrayList<MlaData>();
// use original list to loop through and check for matches
for (int i = 0; i < dats.size(); i++) {
if (dats.get(i).getName().toUpperCase().contains(constraint)) {
MlaData MlaDat = new MlaData(dats.get(i).getName(), dats.get(i).getImageUrl(), dats.get(i).getArea(), dats.get(i).getId(), dats.get(i).getEmail());
filters.add(MlaDat);
}
}
results.count = filters.size();
results.values = filters;
}
else {
results.count = dats.size();
results.values = dats;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// assign the filtered data to filterList
filterList = (ArrayList<MlaData>)results.values;
notifyDataSetChanged();
}
And finally change your methods to use the filtered list
#Override
public int getCount() {
return filterList.size();
}
#Override
public Object getItem(int position) {
return filterList.get(position);
}
#Override
public long getItemId(int position) {
return ((MlaData)filterList.get(position)).getId();
}
When you clear the filter you should reset the filterList to the original data again
filterList = new ArrayList<MlaData>(dats);
1. Update your adapter's method getItemId() as below:
#Override
public long getItemId(int position) {
return position;
}
2. Update ListView onItemClick() method as below:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MlaData item = MlaDats.get(position);
String MLAID = item.getId();
String MLANAME = item.getName();
String MLAEMAIL = item.getEmail();
String MLAIMAGE = item.getImageUrl();
String MLAAREA = item.getArea();
Intent intent = new Intent(Rajasthan_Mla.this, MainActivity.class);
intent.putExtra("MLA_ID", MLAID);
intent.putExtra("MLA_NAME", MLANAME);
intent.putExtra("MLA_EMAIL", MLAEMAIL);
intent.putExtra("MLA_IMAGE", MLAIMAGE);
intent.putExtra("MLA_AREA", MLAAREA);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("Mukesh", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MLAID", MLAID);
editor.putString("MLANAME",MLANAME);
editor.commit();
startActivity(intent);
}
});
Hello I'm new at Android. I want to populate a Spinner with a list of objects. I have googled how to do it but I just find examples with an array of strings.
Can any one help me?
This is my code:
Categories class:
public class Categories
{
#com.google.gson.annotations.SerializedName("id")
private String mId;
#com.google.gson.annotations.SerializedName("name")
private String mName;
public Categories()
{}
public Categories(String id, String name)
{
this.setId(id);
this.setName(name);
}
#Override
public String toString()
{
return mName;
}
// ******** GET *************
public String getId()
{
return mId;
}
public String getName()
{
return mName;
}
// ******** SET *************
public final void setId(String id)
{
mId = id;
}
public final void setName(String name)
{
mName = name;
}
}
This is my Activity code:
public class AgregarActividadActivity extends ActionBarActivity
{
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private MobileServiceTable<Categories> mCategoriesTable;
private MobileServiceTable<Projects> mProjectsTable;
private EditText mTxtTitulo;
private EditText mTxtDescr;
String categryId = null;
List<Categories> catList = new ArrayList<Categories>();
Spinner spEstado;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_agregar_actividad);
try
{
mClient = new MobileServiceClient(
"https://site.azure-mobile.net/",
"AppKey",
this);
mActivitiesTable = mClient.getTable(Activities.class);
mCategoriesTable = mClient.getTable(Categories.class);
}
catch (MalformedURLException e)
{
createAndShowDialogExc(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mTxtTitulo = (EditText) findViewById(R.id.txtTitulo);
mTxtDescr = (EditText) findViewById(R.id.txtDescripcion);
getCategories();
spEstado = (Spinner)this.findViewById(R.id.spEstado);
ArrayAdapter<Categories> Adapter = new ArrayAdapter<Categories>(this,
android.R.layout.simple_spinner_item, catList);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEstado.setAdapter(Adapter);
spEstado.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent,
View view,
int position,
long id) {
Categories item = (Categories) parent.getItemAtPosition(position);
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
spProjects = (Spinner)this.findViewById(R.id.spProyecto);
ArrayAdapter<Projects> proAdapter = new ArrayAdapter<Projects>(this,
android.R.layout.simple_spinner_item, proList);
proAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spProjects.setAdapter(proAdapter);
}
private void getCategories()
{
mCategoriesTable.execute(new TableQueryCallback<Categories>()
{
public void onCompleted(List<Categories> result, int count, Exception exception, ServiceFilterResponse response)
{
if (exception == null)
{
for (Categories item : result)
{
catList.add(item);
}
}
else
{
createAndShowDialog(exception, "Error");
}
}
});
}
}
I get the dropdownlist with the objects, but when I select one item, it is not displayed as the selected item, when the dropdownlist is hidden.
Any idea will help me! Thank you!!
You need to write a CustomAdapter for this. It is similar to writing a CustomAdapter for a ListView. You can look at Custom Adapter for List View for an idea
Im trying to make ListView using data from Array, but I need to get Id of clicked row (not shown in that row, but userd in creation of that product)
Im using this class for object:
package com.example.raidplanner;
public class RaidWpis {
private int id;
private int id_gildia;
private String nazwa;
private int schemat;
private int data_zapis;
private int data_start;
private int opis;
private int id_officer;
private int nick_officer;
private int typ;
public RaidWpis(int id,String nazwa) {
setNazwa(nazwa);
setId(id);
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getNazwa() { return nazwa; }
public void setNazwa(String nazwa) { this.nazwa = nazwa; }
public String toString() {
return this.nazwa;
}
public String toString2() {
return this.id+" - "+nazwa;
}
}
And this code in Activity:
RaidWpis[] items = {
new RaidWpis(1, "aaaa"),
new RaidWpis(3, "bbbb"),
new RaidWpis(6, "cccc"),
new RaidWpis(11, "dddd"),
new RaidWpis(17, "eeee"),
};
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayAdapter<RaidWpis> raidList = new ArrayAdapter<RaidWpis>(this, R.layout.simplerow, items);
// Create ArrayAdapter using the raid list.
mainListView.setAdapter(raidList);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
I need to get Id of clicked row (not shown in that row, but userd in creation of that product)
Try this in your onItemClick() method:
RaidWpis obj = parent.getAdapter().getItem(position); // or just raidList.get(position) if raidList is a field variable
Toast.makeText(getBaseContext(), obj.getID() + "", Toast.LENGTH_LONG).show();
from the position, you can get the RaidWpis Object by using raidList.get(position). Once you have this RaidWpis object, you can call getId() to get the id