I am actually new to Android Programming and I am developing an application in which I have a listView,which only comprises of EditTexts (i.e.TextInputEditText).
I have added hints to the EditTexts, but I want to get values from the EditText that the users enter.
Here is my code:
MyItems.java
public class MyItem {
public String TextTitle;
EditText Message;
public MyItem(String title)
{
this.TextTitle = title;
}
public EditText getEditText() {
return Message;
}`enter code here`
public void setEditText(EditText msg) {
this.Message = msg;
}
}
MyAdapter.java
public class MyAdapter extends BaseAdapter {
private ArrayList<MyItem> listItems;
private Context context;
public MyAdapter(Context context, ArrayList<MyItem> listItems)
{
this.context=context;
this.listItems=listItems;
}
#Override
public int getCount()
{
return listItems.size();
}
#Override
public MyItem getItem(int position)
{
return listItems.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent)
{
View row;
ListViewHolder listViewHolder;
if(view == null) {
LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.my_adapter, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvname = row.findViewById(R.id.tvname);
row.setTag(listViewHolder);
}
else
{
row = view;
listViewHolder = (ListViewHolder) row.getTag();
}
try {
MyItem myItem = getItem(position);
String text = myItem.TextTitle;
listViewHolder.tvname.setHint(text);
}
catch (NullPointerException exec)
{
Log.e(TAG, "Execption ");
}
EditText etText = (EditText)row.findViewById(R.id.etText);
listItems.get(position).setEditText(etText);
return row;
}
}
MainFragment
public class ExistingStudentFragment extends Fragment {
Button btnExisting, btnNew;
Button btnShow, btnSubmit;
ArrayList<MyItem> myitems=new ArrayList<>();
ArrayList<MyItem> myitems2=new ArrayList<>();
ArrayList<MyItem> myitems3=new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.existing_student_fragment,
container, false);
getTextView();
getTextView2();
getTextView3();
ListView listView, listView2, listView3;
final MyAdapter myAdapter, myAdapter2, myAdapter3;
listView = (ListView)view.findViewById(R.id.list_items);
myAdapter = new MyAdapter(getContext(), myitems);
listView2 = (ListView)view.findViewById(R.id.list_items2);
myAdapter2 = new MyAdapter(getContext(), myitems2);
listView3 = (ListView)view.findViewById(R.id.list_items3);
myAdapter3 = new MyAdapter(getContext(), myitems3);
listView.setAdapter(myAdapter);
listView2.setAdapter(myAdapter2);
listView3.setAdapter(myAdapter3);
Spinner spinner_pass = (Spinner)view.findViewById(R.id.spin_passtype);
List<String> passtype = new ArrayList<String>();
passtype.add("Ist Class");
passtype.add("IInd Class");
ArrayAdapter<String> SpinnerAdapter = new ArrayAdapter<String>
(this.getActivity(), android.R.layout.simple_spinner_item, passtype);
SpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdownitem);
spinner_pass.setAdapter(SpinnerAdapter);
btnExisting = (Button)view.findViewById(R.id.btnExisting);
btnNew = (Button)view.findViewById(R.id.btnNew);
btnShow = (Button)view.findViewById(R.id.btnshow);
btnSubmit = (Button)view.findViewById(R.id.btnsubmit);
btnExisting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((UserConcessionActivity)getActivity()).setViewPager(0);
}
});
btnNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((UserConcessionActivity)getActivity()).setViewPager(1);
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = myAdapter.getItem(0).getEditText().toString();
}
});
return view;
}
private void getTextView()
{
myitems.add(new MyItem("Admission Number:"));
myitems.add(new MyItem("Roll Number:"));
myitems.add(new MyItem("Name Of Student:"));
myitems.add(new MyItem("Stream:"));
}
private void getTextView2()
{
myitems2.add(new MyItem("Last Certificate Number(VCH No):"));
myitems2.add(new MyItem("Last Ticket from(Station):"));
myitems2.add(new MyItem("Last Ticket Number(Last 4 digits):"));
myitems2.add(new MyItem("Last Ticket Period(Monthly/Quaterly):"));
myitems2.add(new MyItem("Last Issued Date:"));
}
private void getTextView3()
{
myitems3.add(new MyItem("From Station:"));
myitems3.add(new MyItem("Pass Type(I or II):"));
myitems3.add(new MyItem("Ticket Period:"));
}
}
TextInputEditText extends from AppCompatEditText and,
From the documentation:
A special sub-class of EditText designed for use as a child of
TextInputLayout.
Using this class allows us to display a hint in the IME when in
'extract' mode.
So you should be able to get text like following codes from TextInputEditText:
String retrievedText = textInputName.getText().toString();
Don't forget to define in java-kotlin side with a prefix of your Fragment view (view in your case):
TextInputEditText textInputName = view.findViewById(R.id.edittext_edit_word_1);
And also in Xml layout.
There is also a good sample in here which you can use.
Related
I need to display name, phoneNumber and accountNumber in EditText in the class ConsumerdescAndEdit, so how do pass these values when OnItemClickListener is executed?
ShowAll.java:
I have the ListView that inflated from CustomAdapter.
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
startActivity(intent);
CustomAdapter.java:
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects){
this.objects = objects;
this.mContext = context;
}
public CustomAdapter(){
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout,null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
return convertView;
}
}
ConsumerDescAndEdit.java (where do I need to use variables):
public class ConsumerDescAndEdit extends AppCompatActivity {
Button updateButton;
EditText nameEditTextVar;
EditText phoneEditTextVar;
EditText accountEditTextVar;
// Variables to store user inputted data.
String nameEdit;
String phoneEdit;
String accountEdit;
DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer_desc_and_edit);
dbHelper = new DatabaseHelper(this);
updateButton = findViewById(R.id.updateButton);
nameEditTextVar = findViewById(R.id.nameEditScreen);
phoneEditTextVar = findViewById(R.id.phoneNumberEditScreen);
accountEditTextVar = findViewById(R.id.accountNumberEditScreen);
String s_intent = getIntent().getStringExtra("EXTRA_SESSION_ID");
nameEditTextVar.setText(s_intent);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameEdit = nameEditTextVar.getText().toString();
phoneEdit = phoneEditTextVar.getText().toString();
accountEdit = accountEditTextVar.getText().toString();
if (nameEdit.isEmpty() || phoneEdit.isEmpty() || accountEdit.isEmpty()) {
Toast.makeText(ConsumerDescAndEdit.this, "Data Insufficient", Toast.LENGTH_SHORT).show();
} else {
boolean b = dbHelper.updateData(nameEdit, phoneEdit, accountEdit);
if (b)
Toast.makeText(ConsumerDescAndEdit.this, "Data updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(ConsumerDescAndEdit.this, "Could not update data", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When you create the Intent for the edit Activity, add the data from the selected item as "extras" to the Intent, like this:
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
intent.putExtra("name", name);
intent.putExtra("phone", phone);
intent.putExtra("account", account);
startActivity(intent);
In the edit Activity, extract the data from the Intent like this:
String name = intent.getStringExtra("name");
String phone = intent.getStringExtra("phone");
String account = intent.getStringExtra("account");
Try below code
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
private ItemClickListener itemClickListener;
public interface ItemClickListener {
void onItemClick(Consumer consumer);
}
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects, ItemClickListener itemClickListener) {
this.objects = objects;
this.mContext = context;
this.itemClickListener = itemClickListener;
}
public CustomAdapter() {
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout, null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (itemClickListener != null) {
itemClickListener.onItemClick(consumer);
}
}
});
return convertView;
}
}
In Activity do following
public class ConsumerActivity extends AppCompatActivity implements CustomAdapter.ItemClickListener {
CustomAdapter adapter;
ArrayList<Consumer> objects;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer);
adapter = new CustomAdapter(this, objects, this);
}
#Override
public void onItemClick(Consumer consumer) {
Intent intent = new Intent(this, CustomerEdit.class);
intent.putExtra("Consumer", consumer);
startActivity(intent);
}
}
i have used checked textview with base adapter to fill listview it's working fine but when i try to scroll CheckedTextView lost the selection.please find the code bellow and help me.
public class AttendancePage extends AppCompatActivity {
List<String> studentNames = new ArrayList<String>();
String[] sNames;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance_page);
databaseHelper = new DatabaseHelper(getApplicationContext());
Cursor res = databaseHelper.getStudentNames();
setTitle("Attendance Sheet");
ListView listView = (ListView) findViewById(R.id.listView);
while (res.moveToNext()) {
studentNames.add(res.getString(0));
}
sNames = new String[studentNames.size()];
sNames = studentNames.toArray(sNames);
Student_Attandence_Addapter customAdapter = new Student_Attandence_Addapter(getApplicationContext(), sNames);
listView.setAdapter(customAdapter);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
My custom Adapter class:
public class Student_Attandence_Adapter extends BaseAdapter {
String[] names;
Context context;
LayoutInflater inflter;
String value;
public Student_Attandence_Adapter(Context context, String[] names) {
this.context = context;
this.names = names;
inflter = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return names.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(names[position]);
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
value = "un-Checked";
simpleCheckedTextView.setCheckMarkDrawable(0);
simpleCheckedTextView.setChecked(false);
} else {
value = "Checked";
simpleCheckedTextView.setCheckMarkDrawable(R.drawable.checked);
simpleCheckedTextView.setChecked(true);
}
}
});
return view;
}
}
Basically what happens is the state of the ChekedTextView will be reset whenever the getView method will be called according to the previous cached state of the list item. So in short you need to store the checked state of an item and when the getView method will be called you need to set it again. For example you need an object containing name and checked state
public class Student {
private String name;
private boolean checked;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
}
and your getView method will be like this,
#Override
public View getView(int position, View view, ViewGroup parent) {
/*
* ListView caches the view so only inflate when there
* is no cached view aka null
*/
if (view == null) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
}
Student aStudent = students[position];
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(aStudent.getName());
simpleCheckedTextView.setCheckMarkDrawable(aStudent.isChecked() ? R.drawable.checked : 0);
simpleCheckedTextView.setChecked(aStudent.isChecked());
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
aStudent.setChecked(false);
notifyDataSetChanged();
} else {
aStudent.setChecked(true);
notifyDataSetChanged();
}
}
});
return view;
}
That's the theme. Modify it as you need.
I have a Fragment containing a custom ListView with custom Adapter. What I display in this list are some doctors which attributes are: picture, name, age and gender.
What I would like to do is filter the doctors by gender when a button is pressed. So that the default would display all doctors, a male button will display all males, and a female button all females. (as shown in the image below)
Here is my fragment code:
public class Doctors extends Fragment {
String[] names = {"Richard Johnson", "William Perez", "Jennifer Fields", "Caroline Marin", "John Smith"};
String[] ages = {"25", "32", "41", "31", "29"};
String[] gender = {"Male", "Male", "Female", "Female", "Male"};
int[] images = { R.drawable.delete_doctora,R.drawable.delete_doctora,R.drawable.delete_doctora,R.drawable.delete_doctora,R.drawable.delete_doctora,};
ListView list;
ArrayAdapter<DocItem> adapter;
ArrayList<DocItem> arrayList;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
View view = inflater.inflate(R.layout.activity_doctors, container, false);
arrayList = new ArrayList<DocItem>();
for(int i = 0; i < 5; i++){
arrayList.add(i,new DocItem(names[i], ages[i], gender[i], images[i]));
}
adapter = new DocAdapter(getActivity(), arrayList);
list = (ListView) view.findViewById(R.id.ListDocs);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
return view;
}
}
My custom Adapter:
public class DocAdapter extends ArrayAdapter<DocItem> {
private Context context;
private ArrayList<DocItem> _values;
public DocAdapter(Context context, ArrayList<DocItem> values) {
super(context, 0, values);
this.context = context;
_values = new ArrayList<DocItem>();
_values.addAll(values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.doc_list_row, parent, false);
TextView txtName = (TextView) rowView.findViewById(R.id.Name);
TextView txtAge = (TextView) rowView.findViewById(R.id.Age);
ImageView imageView = (ImageView) rowView.findViewById(R.id.Pic);
txtName.setText(_values.get(position)._name);
txtAge.setText(_values.get(position)._age);
imageView.setImageResource(_values.get(position)._picture);
return rowView;
}
}
And the Item:
public class DocItem {
public String _name, _age, _gender;
int _picture;
public DocItem(String name, String age, String gender, int picture){
_name = name;
_age = age;
_picture= picture;
_gender = gender;
}
}
Use two arrays in the Adapter. Use one for storage and one for currently shown items.
private ArrayList<DocItem> all_values; //All items
private ArrayList<DocItem> filter_values; //Shown items
public DocAdapter(Context context, ArrayList<DocItem> values) {
...
all_values = new ArrayList<DocItem>();
all_values.addAll(values);
filter_values = all_values.clone();
}
...
#Override
public int getCount() {
return filter_values.size();
}
public void noFilter() {
filter_values = all_values;
notifyDataSetChanged();
}
public void filterMales() {
filterGender("Male");
}
public void filterFemales() {
filterGender("Female");
}
private void filterGender(String gender) {
filter_values = new ArrayList<>();
for(DocItem doc : all_values) {
if(doc._gender.equals(gender)) {
filter_values.add(doc);
}
}
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
!!! USE filter_values array
}
Usage:
In your fragments onCreateView:
Button buttonMales = (Button) findViewById(R.id.filterMales);
Button buttonFemales = (Button) findViewById(R.id.filterFemales);
buttonMales.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.filterMales();
}
});
buttonFemales.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.filterFemales();
}
});
Daily Screen :-
public class DailyScreen extends AppCompatActivity implements AdapterView.OnItemClickListener {
ImageView add, edit;
MyCustomAdapter adapter1;
Button ok;
Button next2;
final Context context = this;
ListView listView;
private ArrayAdapter<String> adapter;
List<Milk> items=new ArrayList();
public List<Milk> getItems() {
return items;
}
public void setItems(List<Milk> items) {
this.items = items;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_listview);
add = (ImageView) findViewById(R.id.add);
edit = (ImageView) findViewById(R.id.edit);
listView = (ListView) findViewById(R.id.list);
next2 = (Button) findViewById(R.id.next2);
Milk milkDefault=new Milk("Toned Milk",0);
items.add(milkDefault);
//this.setArrayList((ArrayList<String>) Arrays.asList(items));
adapter1 = new MyCustomAdapter(items, this);
listView.setAdapter(adapter1);
listView.setOnItemClickListener(this);
registerForContextMenu(listView);// to set context menu in list view
}
#Override
protected void onResume() {
super.onResume();
next2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DailyScreen.this, SupplierActivity.class);
intent.putExtra("LIST_ITEMS",List,items);//
startActivity(intent);
}
});
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(DailyScreen.this);
dialog.setTitle("Enter new Milk");
dialog.setContentView(R.layout.dialog_box);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
final EditText editText = (EditText) dialog.findViewById(R.id.pro);
String data = editText.getText().toString();
//button initialization
Button ok = (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = editText.getText().toString();
if (!data.isEmpty()) {
items.add(new Milk(data,0));
adapter1.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "product name is :" + data, Toast.LENGTH_LONG).show();
dialog.cancel();
}
else{
Toast.makeText(DailyScreen.this, "Please enter the data", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
MyCustomAdapter class
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private List<Milk> list = new ArrayList<Milk>();
private Context context;
public MyCustomAdapter(List<Milk> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#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.custom_layout, null);
}
TextView name = (TextView) view.findViewById(R.id.text);
name.setText(list.get(position).getNsme());
final TextView milkCount = (TextView) view.findViewById(R.id.milkcount);
milkCount.setText(""+list.get(position).getAmount());
ImageView increment = (ImageView) view.findViewById(R.id.add);
ImageView decrement = (ImageView) view.findViewById(R.id.sub_item);
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(milkCount.getText().toString().trim());
a = a + 1;
milkCount.setText("" + a);
list.get(position).setAmount(a);
}
});
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(milkCount.getText().toString().trim());
if (a == 0) {
a = 0;
} else {
a = a - 1;
}
milkCount.setText("" + a);
list.get(position).setAmount(a);
}
});
return view;
}
Milk class
public class Milk {
private String nsme ;
private int amount ;
public Milk(String nsme, int amount) {
this.nsme = nsme;
this.amount = amount;
}
public String getNsme() {
return nsme;
}
public void setNsme(String nsme) {
this.nsme = nsme;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
i have tried all thing to send all the data of list view to another activty please suggest me how can i do it ??
Make the list static and u can then access it in any activity. Make sure u initialise the list
milk class extends serializable firstly
then u do
make object of milk class in mainactivity class
Milk milk=new Milk(this);
Intent i=new Intent(getApplicationContext(),Update.class);
i.putExtra("emnumber",(Serializable)milk);
startActivity(i);
then u can pick the value in update class
if(getIntent().getSerializableExtra("emnumber")!=null) {
con = (ArrayList<Contact>) getIntent().getSerializableExtra("emnumber");
email_mobile = contactList.get(0).nsme;
pass__word = contactList.get(0).amount;
you can implement as:
public class Milk implements Parcelable{
......
}
Send arraylist as:
intent.putExtra("files", "your arraylist");
obtain arraylist as:
Intent inIntent = getIntent();
list=inIntent.getParcelableArrayListExtra("files");
Try this. May be it help.
Send arraylist to activity through extras.
intent.putStringArrayListExtra("ARRAY_LIST", arrayList);
Retrieve arraylist in activity.
arrayList= i.getStringArrayListExtra("ARRAY_LIST");
If u have to send arraylist other than string then.
intent.putParcelableArrayListExtra("ARRAY_LIST", (ArrayList<Milk>) milkArrayList);
Milk class must be parcellable
I am a beginner to Android. Now I am working with ListView using custom adapter and custom view. Custom adapter is created as into a separate file. But inside my custom adapter, I set up a click listener for a button of the layout of the list view row. But my problem is how can I update items of the adapter inside event listener that is created inside the custom adapter.
This is my Listview Fragment:
public class TaskListFragment extends Fragment {
private DatabaseHelper dbHelper;
private TextView taskTitle;
private ListView taskListView;
private ArrayAdapter adapter;
private ArrayList<Task> items;
private int optionFocusedItemIndex;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dbHelper = new DatabaseHelper(getActivity());
View view= inflater.inflate(R.layout.task_list, container, false);
taskTitle = (TextView)view.findViewById(R.id.task_textview);
taskListView = (ListView)view.findViewById(R.id.listViewTaskList);
int type = getArguments().getInt("type");
switch (type){
case R.integer.task_list_all:
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
taskTitle.setText("All tasks");
break;
}
taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int tagId = Integer.valueOf(view.getTag().toString());
optionFocusedItemIndex = position;
showOptionDialog(tagId);
return true;
}
});
return view;
}
public void showOptionDialog(final int id)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_option_dialog, null);
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(id);
refreshListView();
alertDialog.cancel();
Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
}
});
Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity)getActivity();
activity.replaceEditTaskFragment(id);
alertDialog.cancel();
}
});
Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteTask(id);
items.remove(optionFocusedItemIndex);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
alertDialog.cancel();
}
});
Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.cancel();
}
});
alertDialog.setView(view);
alertDialog.show();
}
public void refreshListView()
{
if(items!=null)
{
Task taskOld = items.get(optionFocusedItemIndex);
if(taskOld!=null)
{
taskOld.setDone(true);
items.set(optionFocusedItemIndex, taskOld);
adapter.notifyDataSetChanged();
}
}
}
}
Inside the fragment, when I click the done button listView adapter is updated properly and it is working find. Done button is inside the AlertDialog box that appear when long click on one of the rows of list view.
The problem is here.
This is my custom adapter class:
public class TaskListAdapter extends ArrayAdapter<Task> {
private final Context context;
private final ArrayList<Task> values;
private final DatabaseHelper dbHelper;
public TaskListAdapter(Context context,ArrayList<Task> values)
{
super(context,-1,values);
this.context = context;
this.values = values;
this.dbHelper = new DatabaseHelper(context.getApplicationContext());
}
#Override
public View getView(final int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.task_list_row,parent, false);
rowView.setTag(values.get(position).getId());
TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
rowDescription.setText(values.get(position).getDescription());
ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);
Long currentDateMillSec= System.currentTimeMillis();
Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
if(values.get(position).getDone()==Boolean.TRUE)
{
rowStatusIcon.setImageResource(R.drawable.done_icon);
}
else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
{
rowStatusIcon.setImageResource(R.drawable.failed_icon);
}
else{
rowStatusIcon.setImageResource(R.drawable.todo_icon);
}
TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
dateTf.setText(values.get(position).getDate());
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
}
});
return rowView;
}
}
So how can I update the listview items and listview from the click event listener of done button that is inside custom adapter class.
public class TaskListFragment extends Fragment implements TaskListAdapter.RefreshAdapter{//change
private DatabaseHelper dbHelper;
private TextView taskTitle;
private ListView taskListView;
private ArrayAdapter adapter;
private ArrayList<Task> items;
private int optionFocusedItemIndex;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dbHelper = new DatabaseHelper(getActivity());
View view= inflater.inflate(R.layout.task_list, container, false);
taskTitle = (TextView)view.findViewById(R.id.task_textview);
taskListView = (ListView)view.findViewById(R.id.listViewTaskList);
int type = getArguments().getInt("type");
switch (type){
case R.integer.task_list_all:
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
adapter.setRefreshAdapter(this);//change
taskTitle.setText("All tasks");
break;
}
taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int tagId = Integer.valueOf(view.getTag().toString());
optionFocusedItemIndex = position;
showOptionDialog(tagId);
return true;
}
});
return view;
}
public void showOptionDialog(final int id)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_option_dialog, null);
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(id);
refreshListView();
alertDialog.cancel();
Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
}
});
Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity)getActivity();
activity.replaceEditTaskFragment(id);
alertDialog.cancel();
}
});
Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteTask(id);
items.remove(optionFocusedItemIndex);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
alertDialog.cancel();
}
});
Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.cancel();
}
});
alertDialog.setView(view);
alertDialog.show();
}
public void refreshListView()
{
if(items!=null)
{
Task taskOld = items.get(optionFocusedItemIndex);
if(taskOld!=null)
{
taskOld.setDone(true);
items.set(optionFocusedItemIndex, taskOld);
adapter.notifyDataSetChanged();
}
}
}
//change
#Override
public void OnlickRefreshAdapter(){
//todo your code here
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
}
}
adapter class
public class TaskListAdapter extends ArrayAdapter<Task> {
private final Context context;
private final ArrayList<Task> values;
private final DatabaseHelper dbHelper;
private RefreshAdapter refreshAdapter;
public TaskListAdapter(Context context,ArrayList<Task> values)
{
super(context,-1,values);
this.context = context;
this.values = values;
this.dbHelper = new DatabaseHelper(context.getApplicationContext());
}
public Interface RefreshAdapter{
public void OnlickRefreshAdapter();
}
public setRefreshAdapter(RefreshAdapter refresh){
refreshAdapter = refresh;
}
#Override
public View getView(final int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.task_list_row,parent, false);
rowView.setTag(values.get(position).getId());
TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
rowDescription.setText(values.get(position).getDescription());
ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);
Long currentDateMillSec= System.currentTimeMillis();
Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
if(values.get(position).getDone()==Boolean.TRUE)
{
rowStatusIcon.setImageResource(R.drawable.done_icon);
}
else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
{
rowStatusIcon.setImageResource(R.drawable.failed_icon);
}
else{
rowStatusIcon.setImageResource(R.drawable.todo_icon);
}
TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
dateTf.setText(values.get(position).getDate());
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
}
});
return rowView;
}
}
I got the answer, actually it is too simple. What I need to do is just add this code inside the click listener of done button in the custom adapter.
This is the click listener of the doneBtn in custom adapter:
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
if(values!=null)
{
Task oldTask = values.get(position);
oldTask.setDone(Boolean.TRUE);
values.set(position,oldTask);
notifyDataSetChanged();
}
}
});