The following code is a list of items taken from the database that should I selected objects and display them in another listview by pressing a button.
Please help me with advice given situation. Thanks!
public class ParticipantsSelectedActivity extends AppCompatActivity implements View.OnClickListener{
DataBaseHandler myDb;
ListView listViewParticipants;
ParticipantsSelectedListAdapter participantsSelectedListAdapter;
Participants participants;
Button btn_save_participants_selected;
CheckBox ckb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_participants_selected);
myDb = new DataBaseHandler(this);
ckb = (CheckBox)findViewById(R.id.ckb);
listViewParticipants = (ListView) findViewById(R.id.listViewParticipantsSelected);
btn_save_participants_selected = (Button) findViewById(R.id.btn_save_participants_selected);
final ArrayList<Participants> listData = new ArrayList<>();
final Cursor cursor = myDb.getListParticipants();
if(cursor.getCount() == 0){
Toast.makeText(this, "There is no participants", Toast.LENGTH_SHORT).show();
}else {
while(cursor.moveToNext()){
int id =(Integer.valueOf(cursor.getString(0)));
String firstName = cursor.getString(1);
String position = cursor.getString(3);
participants = new Participants(id,firstName,position, true);
listData.add(participants);
participantsSelectedListAdapter = new ParticipantsSelectedListAdapter(this,android.R.layout.simple_list_item_multiple_choice,listData);
listViewParticipants.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewParticipants.setAdapter(participantsSelectedListAdapter);
btn_save_participants_selected.setOnClickListener(this);
}
}
/*
listViewParticipants.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Participants participants = listData.get(position);
Toast.makeText(getApplicationContext(), "Clicked on Id..." + participants.getId(), Toast.LENGTH_SHORT).show();
}
});
*/
}
#Override
public void onClick(View v) {
//another activity to fill another listView
}
}
This is the custom adapter
public class ParticipantsSelectedListAdapter extends ArrayAdapter<Participants> {
public ParticipantsSelectedListAdapter(Context context,int a, ArrayList<Participants> participants) {
super(context, 0, participants);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Participants participants = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_participants_selected, parent, false);
}
// Lookup view for data population
TextView tvFirstName = (TextView) convertView.findViewById(R.id.tvFirstName);
TextView tvPosition = (TextView) convertView.findViewById(R.id.tvPosition);
CheckBox ckb = (CheckBox) convertView.findViewById(R.id.ckb);
// Populate the data into the template view using the data object
tvFirstName.setText(participants.getFirstName());
tvPosition.setText(participants.getPosition());
ckb.setChecked(false);
// Return the completed view to render on screen
return convertView;
}
}
And this is the XML item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:id="#+id/ckb"/>
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvPosition"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In your model class for Participant add one boolean variable like this for making selection and deselection:
In Participant.class
private boolean isSelected;
public void setSelected(boolean selection){
this.isSelected = selection;
}
public boolean isSelected(){
this.isSelected;
}
On database data retrieve you are setting adapter again and again that is wrong, no need to do.
OnClick event added for getting selected items from participants list.
public class ParticipantsSelectedActivity extends AppCompatActivity implements View.OnClickListener {
DataBaseHandler myDb;
ListView listViewParticipants;
ParticipantsSelectedListAdapter participantsSelectedListAdapter;
Participants participants;
Button btn_save_participants_selected;
CheckBox ckb;
final ArrayList<Participants> listData = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_participants_selected);
myDb = new DataBaseHandler(this);
ckb = (CheckBox) findViewById(R.id.ckb);
listViewParticipants = (ListView) findViewById(R.id.listViewParticipantsSelected);
btn_save_participants_selected = (Button) findViewById(R.id.btn_save_participants_selected);
final Cursor cursor = myDb.getListParticipants();
if (cursor.getCount() == 0) {
Toast.makeText(this, "There is no participants", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
int id = (Integer.valueOf(cursor.getString(0)));
String firstName = cursor.getString(1);
String position = cursor.getString(3);
participants = new Participants(id, firstName, position, true);
listData.add(participants);
}
//Setting adapter after all data retrieve from database
participantsSelectedListAdapter = new ParticipantsSelectedListAdapter(this, android.R.layout.simple_list_item_multiple_choice, listData);
listViewParticipants.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewParticipants.setAdapter(participantsSelectedListAdapter);
btn_save_participants_selected.setOnClickListener(this);
}
/*
listViewParticipants.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Participants participants = listData.get(position);
Toast.makeText(getApplicationContext(), "Clicked on Id..." + participants.getId(), Toast.LENGTH_SHORT).show();
}
});
*/
}
#Override
public void onClick(View v) {
//another activity to fill another listView
if (v.getId() == R.id.btn_save_participants_selected) {
ArrayList<Participants> selectedListData = new ArrayList<>();
if (listData != null && listData.size() > 0) {
for (int i = 0; i < listData.size(); i++) {
if (listData.get(i).isSelected()) {
selectedListData.add(listData.get(i));
}
}
//Pass this selectedListData to new activity to show a new Listview
}
}
}
}
Your adapter code change for selection and deselection.
public ParticipantsSelectedListAdapter(Context context, int a, ArrayList<Participants> participants) {
super(context, 0, participants);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
final Participants participants = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_participants_selected, parent, false);
}
// Lookup view for data population
TextView tvFirstName = (TextView) convertView.findViewById(R.id.tvFirstName);
TextView tvPosition = (TextView) convertView.findViewById(R.id.tvPosition);
CheckBox ckb = (CheckBox) convertView.findViewById(R.id.ckb);
// Populate the data into the template view using the data object
tvFirstName.setText(participants.getFirstName());
tvPosition.setText(participants.getPosition());
if(participants.isSelected) {
ckb.setChecked(true);
}else {
ckb.setChecked(false);
}
ckb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
participants.setSelected(!participants.isSelected());
notifyDataSetChanged();
}
});
// Return the completed view to render on screen
return convertView;
}
Related
I've created a customised list view for my Android app in order to add a Delete button for every cell to make the user able to delete rows from the list. The customised list view is working well but when I added a click listener for the button, the list view show empty cells instead of populating the data coming from the array.
Here is the getView code:
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "delete me", Toast.LENGTH_SHORT).show();
}
});
return row;
}
I think the I should return something else not the row, but I have no idea what to return. When I think about it when I return the row it should show the rows filled with data. Note when I delete this piece of code, the list view is working well with showing the data.
This is the whole code of the adapter class
// Our adapter class
class MyAdapter extends ArrayAdapter<String> {
Context context;
String rNames[];
MyAdapter(Context c, String name[]) {
super(c, R.layout.row, R.id.customerName, name);
this.context = c;
this.rNames = name;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "delete me", Toast.LENGTH_SHORT).show();
}
});
return row;
}
}
And this is the whole code of the home fragment page
public class HomeFragment extends Fragment {
// creating an empty array. This is an array of objects (array of arrays).
final ArrayList<String[]> mainObjectsArray = new ArrayList<String[]>();
//final String[][] myFamily = new String[][];
// creating another array of the titles. If our main array is an array of strings we will not need this.
// Why?. ArrayAdapter doesn't accept an array of arrays it only accepts an array of Stings, so we had to create a special array for the titles and bring them from our main array.
final ArrayList<String> theNames = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_home, null);
// creaing a list view and connect it to the list view we created in the XML file
// Note: we need to add (final) to be able to access them from inside the loop
final ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
// Retrieving the data and filling the array with it
ParseQuery<ParseObject> query = ParseQuery.getQuery("Orders");
query.orderByDescending("updatedAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
//Log.i("findInBackground", "Retrieved: " + objects.size() + "objects");
if (objects.size() > 0) {
for (ParseObject object: objects) {
// Converting every object to an array of two itmes, title and body.
String[] artical = {object.getString("TheSavedOrder"), object.getString("mobileNumber"), object.getString("Name")};
// Adding the array to our main array so we will have an array of arrays
mainObjectsArray.add(artical);
//Log.i("This my family array: ", myFamily.toString());
}
// We will add only the names to the array (theNames). theTitles will be an array of strings so we can populate it in the list view.
for (int i = 0; i < mainObjectsArray.size(); i++){
theNames.add(mainObjectsArray.get(i)[2]);
//Log.i("Here are teh title: ", myFamily.get(i)[0]);
Log.i("Here is thti: ", theNames.get(i));
}
// Converting theNames from ArrayList to an array
String[] namesArray = new String[theNames.size()];
namesArray = theNames.toArray(namesArray);
// Applaying our adapter
MyAdapter adapter = new MyAdapter(getActivity(), namesArray);
myListView.setAdapter(adapter);
}
}
}
});
// When clicking on an item in the list view
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Log.i("The body is: ", mainObjectsArray.get(position));
Intent intent = new Intent(getContext(), TheBody.class);
intent.putExtra("mobile", mainObjectsArray.get(position)[1]); // mainObjectsArray.get(position)[1] means we will pass the second item in every array which is the (mobileNumber).
intent.putExtra("order", mainObjectsArray.get(position)[0]);
startActivity(intent);
}
});
return rootView;
}
// Our adapter class
class MyAdapter extends ArrayAdapter<String> {
Context context;
String rNames[];
MyAdapter(Context c, String name[]) {
super(c, R.layout.row, R.id.customerName, name);
this.context = c;
this.rNames = name;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "delete me", Toast.LENGTH_SHORT).show();
}
});
return row;
}
}
}
This is the XML code of the fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/myListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And finally this is the XML code of the customised cell
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp"
android:descendantFocusability="blocksDescendants">
<TextView
android:id="#+id/customerName"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="custoemr name"
android:textColor="#000"
android:layout_margin="5dp"
android:textSize="20sp"/>
<Button
android:id="#+id/deleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
/>
</LinearLayout>
Please help I've been struggling with this for some days!
Many thanks.
public View getView(final int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "delete me", Toast.LENGTH_SHORT).show();
} });
return row;
}
Pls also note that your list, rNames, is an array[] that is fixed size and cannot remove an individual item. You should use ArrayList if you want to implement the delete function.
Updated:
public class HomeFragment extends Fragment {
// creating an empty array. This is an array of objects (array of arrays).
ArrayList<MainObjects> mainObjectsList = new ArrayList<>();
ListView myListView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, null);
// creaing a list view and connect it to the list view we created in the XML file
// Note: we need to add (final) to be able to access them from inside the loop
myListView = (ListView) rootView.findViewById(R.id.myListView);
// Retrieving the data and filling the array with it
ParseQuery<ParseObject> query = ParseQuery.getQuery("Orders");
query.orderByDescending("updatedAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
//Log.i("findInBackground", "Retrieved: " + objects.size() + "objects");
if (objects.size() > 0) {
for (ParseObject object : objects) {
// Converting every object to an array of two items, title and body.
//String[] artical = {object.getString("TheSavedOrder"), object.getString("mobileNumber"), object.getString("Name")};
MainObjects article = new MainObjects(object.getString("TheSavedOrder"), object.getString("mobileNumber"), object.getString("Name");
// Adding the array to our main array so we will have an array of arrays
mainObjectsList.add(article);
//Log.i("This my family array: ", myFamily.toString());
}
// Applying our adapter
MyAdapter adapter = new MyAdapter(getActivity(), mainObjectsList);
myListView.setAdapter(adapter);
}
}
}
});
// When clicking on an item in the list view
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Log.i("The body is: ", mainObjectsList.get(position));
Intent intent = new Intent(getContext(), TheBody.class);
intent.putExtra("mobile", mainObjectsList.get(position).getMobileNumber());
intent.putExtra("order", mainObjectsList.get(position).getSavedOrder());
startActivity(intent);
}
});
return rootView;
}
class MainObjects {
String savedOrder = "", mobileNumber = "", name = "";
public MainObjects(String savedOrder, String mobileNumber, String name) {
this.savedOrder = savedOrder;
this.mobileNumber = mobileNumber;
this.name = name;
}
public String getSavedOrder() {
return savedOrder;
}
public String getMobileNumber() {
return mobileNumber;
}
public String getName() {
return name;
}
}
class MyAdapter extends ArrayAdapter<MainObjects> {
Context context;
LayoutInflater inflater;
ArrayList<MainObjects> rNames;
MyAdapter(Context c, ArrayList<MainObjects> name) {
super(c, R.layout.row, R.id.customerName, name);
this.context = c;
this.rNames = name;
inflater = getLayoutInflater();
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = inflater.inflate(R.layout.row, parent, false);
TextView nameTv = (TextView) row.findViewById(R.id.customerName);
nameTv.setText(getItem(position).getName());
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
String msg = "Delete: " + pos + ". " + getItem(pos).getName() + " !!";
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
rNames.remove(pos);
notifyDataSetChanged();
//
// Codes to update permanent storage, e.g. files/server/db.
//
} });
deleteButt.setTag(position);
return row;
}
}
}
I have a listView with a custom adapter that includes text + button on each item of my list view. I'am retrieving the text from firebase without problem, but i want that if the user clicks on the button of a item, it will write on the database that that user clicked on that item.
Thank you if someone can help me, give me an idea or send a link.
I had an idea of retrieving the index(rec_1, rec_2, rec_3, etc) of the messages i'm putting on the listView and if the user clicks on the button, i write on the database index - userId : 1 or something like that, but how would i put the index value hidden on each item of the listview so i can retrieve when the button is clicked? Is just an ideia, if there is a better alternative, please tell me!
My code:
activity_recados_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textRecados"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true" />
<Button
android:id="#+id/buttonRecadoVisto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textRecados"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Visto" />
</RelativeLayout>
RecadosCustomAdapter.java
public class RecadosCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> recadosList = new ArrayList<String>();
private Context context;
public RecadosCustomAdapter(ArrayList<String> recadosList, Context context) {
this.recadosList = recadosList;
this.context = context;
}
#Override
public int getCount() {
return recadosList.size();
}
#Override
public Object getItem(int pos) {
return recadosList.get(pos);
}
#Override
public long getItemId(int position) {
//return recadosList.get(pos).getId();
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity_recados_item, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.textRecados);
listItemText.setText(recadosList.get(position));
//Handle buttons and add onClickListeners
Button buttonVisto = (Button)view.findViewById(R.id.buttonRecadoVisto);
buttonVisto.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
}
});
return view;
}
}
RecadosActivity.java
ValueEventListener valueEventListener = myRef.limitToLast(15).addValueEventListener(new ValueEventListener() {
ArrayList<String> recadosList = new ArrayList<String>();
RecadosCustomAdapter adapter = new RecadosCustomAdapter(recadosList, RecadosActivity.this);
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
recadosList.clear();
adapter.notifyDataSetChanged();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
RecadosInformation rInfo = new RecadosInformation();
rInfo.setData(ds.getValue(RecadosInformation.class).getData());
rInfo.setMensagem(ds.getValue(RecadosInformation.class).getMensagem());
Log.d(TAG, "showData: Data: " + rInfo.getData());
Log.d(TAG, "showData: Mensagem: " + rInfo.getMensagem());
recadosList.add(rInfo.getData() + "\n" + rInfo.getMensagem() + "\n");
}
Collections.reverse(recadosList);
recados.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you if someone can help me!
I think you should do:
FirebaseDatabase.getInstance().getReference("YOUR_NODE").child("child").setValue(yourvalue);
I think you get the idea?
Read here for more: https://firebase.google.com/docs/database/android/read-and-write
Edit you'll know inside the getView method, that method is called for each item in the list so when u click a button, use the int position to get the particular position of the item
Do:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity_recados_item, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.textRecados);
listItemText.setText(recadosList.get(position));
//Handle buttons and add onClickListeners
Button buttonVisto = (Button)view.findViewById(R.id.buttonRecadoVisto);
buttonVisto.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//upload the index which is position
}
});
return view;
}
Edit 2 give each message an id on firebase database using the push().getKey() method. So in ur getView() do:
String id = yourlist.get(position).getId();
Then do what u want with it.
I have a Spinner that is being populated by a custom adapter.
I can log out all the TextView's in the custom adapter and see what the text is at the position.
TEXT VIEW AT POSITION 0 TEXT: ABC Company
TEXT VIEW AT POSITION 1 TEXT: DEF Company
TEXT VIEW AT POSITION 2 TEXT: GHI Company
TEXT VIEW AT POSITION 3 TEXT: JKL Company
TEXT VIEW AT POSITION 4 TEXT: MNO Company
TEXT VIEW AT POSITION 5 TEXT: PQR Company
So I know passing the data in isn't the problem.
When the Spinner is selected, in the app it just shows up blank.
Anyone see what I am doing wrong?
public class MyActivity extends AppCompatActivity {
private Spinner spinnerCompanies;
private ArrayList<HashMap> arrayOfCompanies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_call);
spinnerCompanies = (Spinner) findViewById(R.id.spCompany);
//do background task and pass JSONArray to processCompanies
processCompanies(jsonArray);
}
public void processCompanies(JSONArray jsonArray){
arrayOfCompanies = new ArrayList<HashMap>();
HashMap company;
JSONObject record;
for (int i = 0; i < jsonArray.length(); i++) {
record = jsonArray.getJSONObject(i);
company = new HashMap<String, String>();
company.put("NAME", record.getString("CompanyName"));
arrayOfCompanies.add(company);
}
CompanyAdapter companyAdapter = new CompanyAdapter(arrayOfCompanies);
spinnerCompanies.setAdapter(companyAdapter);
spinnerCompanies.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
didSelectCompany(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void didSelectCompany(int position){
Log.i(TAG, "didSelectCompany: " + position);
}
public class CompanyAdapter extends BaseAdapter {
private final ArrayList<HashMap> mArrayList;
public CompanyAdapter(ArrayList<HashMap> map) {
mArrayList = map;
}
#Override
public int getCount() {
return mArrayList.size();
}
#Override
public HashMap<String, String> getItem(int position) {
return mArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_company, parent, false);
}
HashMap<String, String> item = getItem(position);
TextView textView = (TextView) convertView.findViewById(R.id.tvSubTermainalName);
textView.setText(item.get("NAME"));
Log.d(TAG, "TEXT VIEW AT POSITION " + position + " TEXT: " + textView.getText());
return convertView;
}
}
}
R.layout.item_company XML used by the custom adapter
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvSubTermainalName"/>
</LinearLayout>
Did you try removing the part
if(convertView==null)
and try inflating the view always?
I'm trying to get the onclick event of a button inside a listview, but it's not working
fragment_contact.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="404dp"
android:layout_weight="0.64"
android:orientation="horizontal"
android:paddingBottom="40dip" >
<ListView
android:id="#+id/contactlistview"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="fill"
android:layout_weight="10"
android:textSize="5pt"
android:visibility="visible" />
</LinearLayout>
fragment_contact_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btn_edit_contact"
android:layout_gravity="right" />
</LinearLayout>
FragmentContact.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_contact, container, false);
ListAdapter adapter_contact = new SimpleAdapter(
getActivity(), allcontact,
R.layout.fragment_contact_content, new String[]{"name", "level", "function", "phone", "email"},
new int[]{R.id.contact, R.id.level, R.id.function, R.id.phone, R.id.email});
listview_contact = (ListView) view.findViewById(R.id.contactlistview);
listview_contact.setItemsCanFocus(true);
listview_contact.setAdapter(adapter_contact);
Button btn_edit_contact = (Button) view.findViewById(R.id.btn_edit_contact);
btn_edit_contact.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Do something");
}
});
return view;
}
I also tried inflating fragment_contact_content.xml but the button still does nothing.
Use custom Adapter and in getView Write your code
public class MealAdapter extends BaseAdapter{
private int mHour, mMinute;
int minutes,hour;
String strtime;
customButtonListener customListner;
private Context context;
private List<Meal> rowItems;
public MealAdapter(Context context, List<Meal> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
private class OptionHolder
{
ImageButton btn_time;
ImageButton btn_delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final OptionHolder holder;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.meal_list_item, null);
holder = new OptionHolder();
holder.btn_time= (ImageButton) convertView.findViewById(R.id.btn_time);
holder.btn_delete =(ImageButton) convertView.findViewById(R.id.btn_delete_meal);
convertView.setTag(holder);
}
else
{
holder = (OptionHolder) convertView.getTag();
}
final Meal row_pos=rowItems.get(position);
row_pos.setMeal("");
row_pos.setDetail("");
holder.ed_meal.setText(row_pos.getMeal());
holder.ed_detail.setText(row_pos.getDetail());
holder.ed_time.setText(row_pos.getTime());
holder.btn_time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(MealPlannerFragment.con,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
strtime=(hourOfDay + ":" + minute);
row_pos.setTime(strtime);
row_pos.setMunite(minute);
row_pos.setHour(hourOfDay);
holder.ed_time.setText(row_pos.getTime());
}
}, mHour, mMinute, false);
tpd.show();
}
});
holder.btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (customListner != null) {
customListner.onButtonClickListner(position,row_pos);
}
}
});
return convertView;
}
public interface customButtonListener {
public void onButtonClickListner(int position,Meal row_pos);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
}
`
you can not get Listview cell's Button event directly in onCreateView. you have to make CustomAdapter class for that.
you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fragment_contact_content, null);
}
//Handle button and add onClickListener
Button editBtn = (Button)view.findViewById(R.id.btn_edit_contact);
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
//some other task
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
You can refer this link: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
just handle on click listener inside getview where you find the button using findviewbyid
I hope it helps!
I have a 'row' view, which has two text views and one check-box. I am trying to implement it so that when the checkbox is clicked on, it displays the strings of the two text views in the same row.
I have implemented a for loop to get the parent of the checkbox view, then iterate all the parent views children and get the strings from inside them. But instead of the text I am getting an empty Toast message.
My first class code:
public class InteractiveArrayAdapter extends ArrayAdapter<model> implements
OnClickListener {
private final List<model> list;
private final Activity context;
public InteractiveArrayAdapter(Activity context, List<model> list) {
super(context, R.layout.rep, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.rep, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.TextView07);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.CheckBox05);
view.getParent();
viewHolder.checkbox
.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onClick(View v) {
boolean h = ((CompoundButton) v).isChecked();
model element = (model) viewHolder.checkbox
.getTag();
element.setSelected(h);
ViewGroup row = (ViewGroup) viewHolder.checkbox
.getParent();
for (int itemPos = 0; itemPos < ((ViewGroup) row)
.getChildCount(); itemPos++) {
View view = ((ViewGroup) row)
.getChildAt(itemPos);
if (view instanceof TextView) {
viewHolder.text = (TextView) view; //Found it!
Toast.makeText(context,
viewHolder.text.getText(), 10000)
.show();
break;
}
}
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
My second class model :
public class ListActivity1 extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list);
// Create an array of Strings, that will be put to our ListActivity
InteractiveArrayAdapter adapter = new InteractiveArrayAdapter(this,
getModel());
setListAdapter(adapter);
}
private List<model> getModel() {
List<model> list = new ArrayList<model>();
list.add(get("Linux"));
list.add(get("Windows7"));
list.add(get("Suse"));
list.add(get("Eclipse"));
list.add(get("Ubuntu"));
list.add(get("Solaris"));
list.add(get("Android"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
// Initially select one of the items
list.get(1).setSelected(true);
return list;
}
private model get(String s) {
return new model(s);
}
}
Can any one help?
pls try this adapter instead of your custom adapter.
public class ListAdapter<T extends BaseEntity> extends ArrayAdapter {
#SuppressWarnings("unused")
private final List<T> objects;
private Activity activity;
private final List<T> checkboxStatusListOfObject;
private OnClickListener listener;
#SuppressWarnings("unchecked")
public ListAdapter(Activity activity, List<T> objects,
OnClickListener listener, List<T> checkboxStatusListOfObject) {
super( R.layout.simple_row_checkbox_1_item_listview , objects);
this.objects = objects;
this.activity = activity;
this.listener = listener;
this.checkboxStatusListOfObject = checkboxStatusListOfObject;
getFilter();
}
#SuppressWarnings("unchecked")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ObjectViews sqView = null;
if(rowView == null)
{
// Get a new instance of the row layout view
LayoutInflater inflater = this.activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.YourCustomLAyout, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sqView = new ObjectViews();
sqView.checbox = (CheckBox) rowView.findViewById(R.id.checkbox);
if(this.listener !=null){
sqView.checbox.setOnClickListener( this.listener);
}
sqView.text1 = (TextView) rowView.findViewById(R.id.text);
sqView.dataObject = new Object();
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sqView);
} else {
sqView = (ObjectViews) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
T object = (T) objects.get(position);
sqView.text1.setText(object.toString());
sqView.checbox.setText("");
sqView.checbox.setTag(sqView);
sqView.dataObject = object;
if(sqView.getChecbox().isChecked()){
if(this.checkboxStatusListOfObject.indexOf( sqView.dataObject) != -1 ){
sqView.getChecbox().setChecked(true);
}
else{
sqView.getChecbox().setChecked(false);
}
}
return rowView;
}
public class ObjectViews {
Object dataObject;
CheckBox checbox;
TextView text1;
public Object getDataObject() {
return dataObject;
}
public void setDataObject(Object dataObject) {
this.dataObject = dataObject;
}
public CheckBox getChecbox() {
return checbox;
}
public void setChecbox(CheckBox checbox) {
this.checbox = checbox;
}
public TextView getText1() {
return text1;
}
public void setText1(TextView text1) {
this.text1 = text1;
}
}
Define your listener in activity and send to adapter.
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
// here your code
if(cb.isChecked()){
ObjectViews object = (ObjectViews) cb.getTag();
String text = object.getText1().getText();
Toast.makeText(context,text, Toast.LENGTH_LONG).show();
}
}
};
//you can configure this adapter constructor. this is only example
yourListView.setAdapter(
new ListAdapter(getApplicationContext(), yourObjectList
listener, YourSelectedObjectList));
and layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="6dip"
android:paddingTop="4dip" >
<CheckBox
android:id="#+id/checkbox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20dp" />
<TextView
android:id="#+id/text"
android:layout_width="0dp"
android:layout_marginLeft="10dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textSize="20dp" />
</LinearLayout>