Error in list search - android

I'm having difficulty updating the data of a listview, I've developed the search function in the listview and I can search the data, but I need to access the details in detail, passing to an activity, when I do that the data that is passed is those of the id 0 of the first list ... that is, only the view is being updated and not the data. Does anyone know how to fix it?
Search Activity
public class PesquisaTesteActivity extends AppCompatActivity {
public static TextView txt;
public static List<PesquisaBD> lista_produtos;
public static ListView lv;
AdapterBDLocal adapter;
private Button btn;
public static ArrayList list = new ArrayList();
private EditText searchView;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pesquisa_teste);
lv = (ListView)findViewById(R.id.lv2);
searchView = (EditText) findViewById(R.id.search);
lista_produtos = DataBaseClass.getInstance(getApplicationContext()).getAllProdutos();
txt = findViewById(R.id.textView);
adapter = new AdapterBDLocal(PesquisaTesteActivity.this, lista_produtos);
searchView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
final List<PesquisaBD> filtro = filter(lista_produtos,s.toString());
adapter.setFilter(filtro);
lv.setAdapter(adapter);
}
});
btn = (Button) findViewById(R.id.btn_te);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(PesquisaTesteActivity.this, Scan3Activity.class);
startActivity(i);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent inte = new Intent(PesquisaTesteActivity.this, DetalhesPesquisaActivity.class);
inte.putExtra("nome", lista_produtos.get(i).getNome_completo());
inte.putExtra("codigo", lista_produtos.get(i).getCodigo_barras());
inte.putExtra("imagem", lista_produtos.get(i).getImagem());
inte.putExtra("unidade", lista_produtos.get(i).getUnidade());
inte.putExtra("preco", lista_produtos.get(i).getPreco());
startActivity(inte);
}
});
lv.setAdapter(adapter);
}
private List<PesquisaBD> filter(List<PesquisaBD> lista, String query){
query = query.toLowerCase();
final List<PesquisaBD> filtro = new ArrayList<>();
for(PesquisaBD p : lista){
final String texte = p.getNome_completo().toLowerCase();
if(texte.startsWith(query)){
filtro.add(p);
}
}
return filtro;
}
}
Adapter
public class AdapterBDLocal extends BaseAdapter{
private Context mContext;
private List<PesquisaBD> produtosList = new ArrayList<>();
private Filter filter;
public AdapterBDLocal(Context mContext, List<PesquisaBD> produtosList) {
this.mContext = mContext;
this.produtosList = produtosList;
}
#Override
public int getCount() {
return produtosList.size();
}
#Override
public Object getItem(int i) {
return produtosList.size();
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View listItem = view;
if(listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.item_lista_pesquisa,viewGroup,false);
final PesquisaBD p = produtosList.get(i);
ImageView img_produto_pesquisa = listItem.findViewById(R.id.img_produto_pesquisa);
TextView nome = (TextView) listItem.findViewById(R.id.txt_nome_produto2);
nome.setText(p.getNome_completo());
TextView categoria = (TextView) listItem.findViewById(R.id.txt_categoria2);
categoria.setText(p.getPreco());
TextView unidade = (TextView) listItem.findViewById(R.id.txt_unidade2);
unidade.setText(p.getUnidade());
ImageView btn_add = (ImageView)listItem.findViewById(R.id.btn_add);
ImageView btn_rem = (ImageView)listItem.findViewById(R.id.btn_rem);
if(p.getImagem() == null){
Picasso.with(mContext).load(R.drawable.ic_logo).fit().into(img_produto_pesquisa);
} else {
//Picasso.with(mContext).load(p.getImagem()).networkPolicy(NetworkPolicy.OFFLINE).fit().into(img_produto_pesquisa);
Glide.with(mContext).load(p.getImagem()).into(img_produto_pesquisa);
}
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String m = p.getCodigo_barras();
if(list.size()<=9){
list.add(m);
txt.setText(list.toString());
Toast.makeText(mContext, "Adiconado", Toast.LENGTH_SHORT).show();
if(txt.getText()!= null){
}
} else{
Toast.makeText(mContext, "Sua Lista esta grande demais!", Toast.LENGTH_SHORT).show();
}
}
});
btn_rem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String m = p.getCodigo_barras();
list.remove(m);
txt.setText(list.toString());
Toast.makeText(mContext, "Removido da lista!", Toast.LENGTH_SHORT).show();
}
});
return listItem;
}
public void setFilter(List<PesquisaBD> l) {
produtosList = new ArrayList<PesquisaBD>();
produtosList.addAll(l);
notifyDataSetChanged();
}
}

In your adapter use this :- produtosList.clear(); instead of
produtosList = new ArrayList<PesquisaBD>(); that is
public void setFilter(List<PesquisaBD> l) {
produtosList.clear();
produtosList.addAll(l);
notifyDataSetChanged(); }

Related

Listview search does not show search results

First, please bear with me as I am just a beginner in learning Android.
What I want is that when the user adds an item from another activity, the details will be shown from my listview in the MainActivity (I am using a regular expression for my search results). And when the user tries to search an item, I want the search results to show.
From my code below, only the added items are shown and the search results will not display.
Here is a snippet of my code from MainActivity.java
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.notifyDataSetChanged();
}//end if
}
//update the listview
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(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(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
Student.java
public class Student {
Uri uriImage;
String studlname, studfname, studcourse;
//constructor
public Student(Uri uriImage, String studlname, String studfname, String studcourse) {
super();
this.uriImage = uriImage;
this.studlname = studlname;
this.studfname = studfname;
this.studcourse = studcourse;
}
//getters and setters
public Uri getUriImage() {
return uriImage;
}
public void setUriImage(Uri uriImage) {
this.uriImage = uriImage;
}
public String getStudlname() {
return studlname;
}
public void setStudlname(String studlname) {
this.studlname = studlname;
}
public String getStudfname() {
return studfname;
}
public void setStudfname(String studfname) {
this.studfname = studfname;
}
public String getStudcourse() {
return studcourse;
}
public void setStudcourse(String studcourse) {
this.studcourse = studcourse;
}
}
Update your code as below
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.refreshList(findlist)
}//end if
}
//update the listview
anotheradapter.refreshList(findlist)
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
Add refresh List method in adapter
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
public void refreshList(ArrayList<Student> list){
this.list = list;
notifyDataSetChanged()
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
You need to update your adapter initialization as below.
Update in the onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
// initialize the findlist to show all student list by default
findlist.addAll(studentArrayList);
anotheradapter = new CustomAdapter(this, findlist);
// ----- Remove these lines - as you don't need multiple adapters
//adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
//adapter.notifyDataSetChanged();
//lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
show_builder = new AlertDialog.Builder(this);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
// Remove the below line as you don't need to update the list multipletimes
//anotheradapter.notifyDataSetChanged();
}
}
// Add these lines to show the list of all student when the searchbox is empty. This will reset the findList to initial state.
if (txtsearch.getText().length() == 0 && findlist.isEmpty()) {
findlist.addAll(studentArrayList);
}
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}

Return Back the Data from the Activity who calls the fragment dialog

I have a code that calls a fragment as an activity. From that fragment I select a data then give it back to the activity caller and here is my code.
Heres how I open the dialog
fragment_customer_list dialog = new fragment_customer_list();
dialog.show(getFragmentManager(),"CustomerList");
And here is how I return the value
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
add callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
}
});
I will call a function from the activity that calls the dialog to update the edittext.
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
The problem is the dialog is fixed in one activity. My question is how can I return the data from the activity caller? Since this fragment will be used by many activity
============================updated=============================
Here is how I open my fragment and i open it as a dialog
/* Open Customer List */
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
show_customer_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment_customer_list dialog = new fragment_customer_list();
dialog.setOnClickItemListener(new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
dialog.show(getFragmentManager(),"CustomerList");
}
});
And here is the whole code fragment_customer_list
public class fragment_customer_list extends DialogFragment {
private static final String TAG = "CustomerList";
DatabaseHelper myDb;
String pattern_email;
SimpleAdapter adapter;
private DialogInterface.OnClickListener listener;
private OnClickItemListener mListener;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_customer_list, container, false);
final ListView listView = (ListView) view.findViewById(R.id.customer_list);
myDb = new DatabaseHelper(getActivity());
pattern_email = credentials.email;
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer(pattern_email);
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
// add_activity callingActivity = (add_activity ) getActivity();
// callingActivity.onUserSelectValue(customer_name, customer_address);
if (mListener != null) {
mListener.value(customer_name, customer_address);
}
getDialog().dismiss();
}
});
android.widget.Button clickButton = (android.widget.Button) view.findViewById(R.id.close);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDialog().dismiss();
}
});
/* Search customer */
EditText customer_search = (EditText) view.findViewById(R.id.search_customer);
customer_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer_search(cs.toString(),pattern_email);
if (data.getCount() == 0) {
//Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
}
});
return view;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), R.style.WideDialog);
}
public void setOnClickItemListener(OnClickItemListener l) {
mListener = l;
}
interface OnClickItemListener {
void value(String name, String address);
}
}
As you can see on the code above there is Listview that has a code that same as this
add_activity callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
The code above will get the value from listview and call the onUserSelectValue from add_activity then close the dialog
and this is onUserSelectValue and it is located at add_activity
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
Here is my question.
How can I return the value of the listview to the textfield of the activity who opens the fragment(where the list view is located).
UPDATED CODE
I created a class called DialogHelper.java and this is the code
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
}
fragment_customer_list dialog = wr.get();
dialog.OnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null) return;
wr.get().dismiss();
}
}
In my customer_fragment_list.java I have a listview listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
TextView position3 = (TextView) view.findViewById(R.id.list_code);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
String customer_code = position3.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address,customer_code );
}
}
});
together with this
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address,String KUNNR);
}
public interface OnClickItemListener { void value(String name, String address, String code); }
and on my Activity this the code on how i open the dialog
/* Open Customer List */
DialogHelper.userSelectValue(add_covplan.this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(name);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(address);
}
});
you can do this. Don't know if you mean this?
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
private static WeakReference<Activity> wrActivity;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null || wrActivity == null || wrActivity.get() == null || wrActivity.get() != context) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
wrActivity = new WeakReference<>(context);
}
fragment_customer_list dialog = wr.get();
dialog.setOnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null || !wr.get().isShowing()) return;
wr.get().dismiss();
}
}
use
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
DialogHelper.userSelectValue(this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
edit answer
// Suppose this is a FragmentDialog
public class FragmentList {
private OnClickListener listener;
private ListView listView;
// Suppose this has your list listener
public void onResume() {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address);
}
}
});
}
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address);
}
}
// Suppose this is a Activity
class YourActivity extends Activity
{
private FragmentList fragmentList;
EditText customer_address;
EditText customer_name;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
fragmentList = new FragmentList();
customer_address = (EditText) findViewById(R.id.address);
customer_name = (EditText) findViewById(R.id.cusname);
fragmentList.setOnClickListener(new FragmentList.OnClickListener()
{
#Override
public void click(String name, String address)
{
// ...
customer_name.setText(name);
customer_address.setText(address);
}
});
}
}
You can use a ViewModel class implementation to share resources between Activity and Fragment. Share the single context across multiple usages of ViewModel, each sharing a the same ViewModel. It works with the observer and observable pattern and perfect for this use case. You can check details on how to implement it here

how to remove custom listview item in android

i want to remove listview item in my list.. But When I click On Button nothing happened. please tell ME Where I m Doing Wrong...this code can add item but only remove item cant...
//listview java
public class MemberActivity extends AppCompatActivity implements BaseColumns {
ListView mylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member);
final ListView listview;
final ListViewAdapter adapter;
//final ArrayList<String> items = new ArrayList<String>();
mylist = (ListView) findViewById(R.id.listview1);
final LinearLayout linewarLayout1 = (LinearLayout) findViewById(R.id.addmember);
final LinearLayout linewarLayout2 = (LinearLayout) findViewById(R.id.buttongroup);
adapter = new ListViewAdapter();
listview = (ListView) findViewById(R.id.listview1);
final View header = getLayoutInflater().inflate(R.layout.listview_header, null, false);
listview.setAdapter(adapter);
Button addButton = (Button) findViewById(R.id.add);
addButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mylist.setVisibility(View.INVISIBLE);
linewarLayout2.setVisibility(View.INVISIBLE);
linewarLayout1.setVisibility(View.VISIBLE);
}
});
final EditText name = ((EditText) findViewById(R.id.etName));
final EditText ID = ((EditText) findViewById(R.id.etID));
final EditText Major = ((EditText) findViewById(R.id.etMajor));
Button btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//TextView cnttxt = (TextView)findViewById(R.id.count);
//cnttxt.setText(adapter.getCount());
adapter.addItem(name.getText().toString(), ID.getText().toString(), Major.getText().toString());
name.setText("");
ID.setText("");
Major.setText("");
Toast.makeText(getApplicationContext(), "add.", Toast.LENGTH_LONG).show();
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
Button btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
name.setText("");
ID.setText("");
Major.setText("");
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
// delete button
Button deleteButton = (Button) findViewById(R.id.delete);
deleteButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
int count, checked;
count = adapter.getCount();
if (count > 0) {
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
checked = listview.getCheckedItemPosition();
if (checked > -1 && checked < count) {
adapter.removeitem(checked);
listview.clearChoices();
adapter.notifyDataSetChanged();
}
}
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
// get item
ListViewItem item = (ListViewItem) parent.getItemAtPosition(position);
String nameStr = item.getname();
String IDStr = item.getID();
String majorStr = item.getmajor();
}
});
}
}//adapter
public class ListViewAdapter extends BaseAdapter {
private ArrayList<ListViewItem> listViewItemList = new ArrayList<ListViewItem>();
public ListViewAdapter() {
}
#Override
public int getCount() {
return listViewItemList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_item, parent, false);
}
TextView nameTextView = (TextView) convertView.findViewById(R.id.list_name);
TextView IDTextView = (TextView) convertView.findViewById(R.id.list_ID);
TextView majorTextView = (TextView) convertView.findViewById(R.id.list_major);
ListViewItem listViewItem = listViewItemList.get(position);
nameTextView.setText(listViewItem.getname());
IDTextView.setText(listViewItem.getID());
majorTextView.setText(listViewItem.getmajor());
return convertView;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return listViewItemList.get(position);
}
public void removeitem(int position) {
listViewItemList.remove(position);
notifyDataSetChanged();
}
public void addItem(String name, String ID, String major) {
ListViewItem item = new ListViewItem();
item.setname(name);
item.setID(ID);
item.setmajor(major);
listViewItemList.add(item);
notifyDataSetChanged();
}
}
//ListViewItem java
public class ListViewItem {
private String nameStr;
private String IDStr;
private String majorStr;
public void setname(String name) {
nameStr = name;
}
public void setID(String ID) {
IDStr = ID;
}
public void setmajor(String major) {
majorStr = major;
}
public String getname() {
return this.nameStr;
}
public String getID() {
return this.IDStr;
}
public String getmajor() {
return this.majorStr;
}
}
Update your code as below. Set choice mode to CHOICE_MODE_SINGLE when you crate listview and before set adapter. Remove CHOICE_MODE_SINGLE from button click.
listview = (ListView) findViewById(R.id.listview1);
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setAdapter(adapter);
Also, You need to setItemChecked in onItemClick of listview.
Check below example code.
public class MainActivity extends Activity {
private ListView mListView;
private String[] mData = new String[] { "xxx", "yyy", "zzz", "aaa" };
private BaseAdapter mAdapter;
private int mLastCorrectPosition = -1;
private int mButtonPosition = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.list_view);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, mData);
mListView.setAdapter(mAdapter);
mListView.setSelector(new ColorDrawable(0));
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == mButtonPosition) {
if (mLastCorrectPosition != -1) {
mListView.setItemChecked(mLastCorrectPosition, true);
}
else {
mListView.setItemChecked(mButtonPosition, false);
}
// here show dialog
}
else {
mLastCorrectPosition = position;
// here refresh fragment
}
}
});
}
}

how to send all the data of array list to another activity?

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

Restore listview in dialog after search

I am have a small problem in my custom dialog.
When the user search for an item in the listview, the list shows the right items, but if the user for example wants to search again, the listview shows the results from the previous search.
The problem:
How do I restore the listview after the first search?
My activity with the custom dialog
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
}
});
}
}
private void showDialog() {
dialog = new Dialog(this);
View view = getLayoutInflater().inflate(R.layout.material_list, null);
searchList = (ListView) view.findViewById(R.id.searchList);
dialog.setTitle("Välj ny artikel");
final MaterialAdapter adapter = new MaterialAdapter(
InformationActivity.this, materialList);
dialog.setContentView(view);
searchList.setAdapter(adapter);
searchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Materials itemMat = materialList.get(position);
resultProduct = itemMat.materialName;
resultProductNo = itemMat.materialNo;
result = resultProduct + " " + resultProductNo;
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_SHORT).show();
}
});
search = (EditText) dialog.findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
cancel = (Button) dialog.findViewById(R.id.btnCancel);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
ok = (Button) dialog.findViewById(R.id.btnOK);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
product.setText(resultProduct);
productNo.setText(resultProductNo);
dialog.dismiss();
}
});
dialog.show();
}
}
My adapter
public class MaterialAdapter extends BaseAdapter {
LayoutInflater inflater;
Context context;
List<Materials> searchItemList = null;
ArrayList<Materials> materialList = new ArrayList<Materials>();
public MaterialAdapter(Context context, List<Materials> searchItemList) {
this.context = context;
inflater = LayoutInflater.from(context);
this.searchItemList = searchItemList;
this.materialList = new ArrayList<Materials>();
this.materialList.addAll(searchItemList);
}
#Override
public int getCount() {
return searchItemList.size();
}
#Override
public Object getItem(int position) {
return searchItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.d, null);
viewHolder = new ViewHolder();
viewHolder.tvMaterialName = (TextView) convertView
.findViewById(R.id.tvMaterialName);
viewHolder.tvMaterialNo = (TextView) convertView
.findViewById(R.id.tvMaterialNo);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvMaterialName.setText((searchItemList.get(position))
.getMaterialName());
viewHolder.tvMaterialNo.setText((searchItemList.get(position))
.getMaterialNo());
return convertView;
}
public class ViewHolder {
TextView tvMaterialName;
TextView tvMaterialNo;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
searchItemList.clear();
if (charText.length() == 0) {
searchItemList.addAll(materialList);
} else {
for (Materials wp : materialList) {
if (wp.getMaterialName().toLowerCase(Locale.getDefault())
.startsWith(charText)) {
searchItemList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Thanks for the help :)
Try to change search.getText() to s.toString()
public void onTextChanged(CharSequence s, int start, int before,
int count) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
to
public void onTextChanged(CharSequence s, int start, int before, int count) {
resultText = s.toString().toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
A secondary thing, make materialList = searchItemList; And searchItemList empty which will be filled with search items (first run will be same elements of materialList.)
P.S Your adapter should implement Filterable in this case (implements Filterable)
#Override
public void afterTextChanged(Editable s) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
Try this and check whether it helps

Categories

Resources