Joe
Joe

Reputation: 246

android edittext value is clear in recyclerview

I am developing an app containing fragment and tab layout. In my details fragment have two tabs. That are "category" and "items". In the Items showing list. I used Recyclerview to show list. I want add search on the list that i shown on the below. The serch is working as fine. In the List i want to use edit text. When click on the "save" option Options menu i want the entered values of edit text recyclerview. My problem is when entering the value (in edittext) of clock. when search table fan and come back to all items the edit text became clear. I want the value is fix. when searching an a another items.

The fragment of Tab xml code

fragment_itemtab.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="wrap_content"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"

        android:layout_height="wrap_content"
        android:queryHint="Search... " />

    <LinearLayout
    android:id="@+id/lItemsHeader"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dip"
    android:layout_marginRight="5dip"
    android:layout_marginTop="2dip"
    android:background="@color/title_background">


    <TextView
        android:id="@+id/item2"
        style="@style/ItemsHeader"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="3dip"
        android:layout_weight="40"
        android:width="0dip"
        android:text="@string/caption_item"
        android:textColor="@color/font1" />


    <TextView
        android:id="@+id/item4"
        style="@style/ItemsHeader"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="10"
        android:width="0dip"
        android:gravity="center_horizontal"
        android:text="Rate"
        android:textColor="@color/font1" />

    <TextView
        android:id="@+id/item5"
        style="@style/ItemsHeader"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="10"
        android:width="0dip"
        android:gravity="right"
        android:text="Qty"
        android:textColor="@color/font1" />

</LinearLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical" />

</LinearLayout>

</RelativeLayout> 


The xml code of recyclerview

recyclerviewitem_item_tab.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="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:background="@color/recycler_item_background"
android:paddingBottom="5dp"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:orientation="vertical"
    android:padding="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp"
        android:weightSum="1.0">

        <TextView

            android:id="@+id/Itemname"
            android:layout_width="90dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/Rate"
            android:layout_width="45dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:gravity="right" />

        <EditText
            android:id="@+id/Qty"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.3"
            android:ems="10"
            android:inputType="textPersonName"

             />


    </LinearLayout>

</LinearLayout>

</RelativeLayout>

Itemtab.java

public class Itemtab extends Fragment implements SearchView.OnQueryTextListener {

private RecyclerView mRecyclerView;
//private RecyclerView.Adapter mAdapter;
private RecyclerView.Adapter mAdapter = new Recycleradapter_item_tab(getDataSet());
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
private Recycleradapter_item_tab adapter;
String qty;
// AutoCompleteTextView pview;
private SearchView mSearchView;
View v;

private ArrayList<Item_object> results;
ViewPager viewPager;
public Itemtab() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   v = inflater.inflate(R.layout.fragment_itemtab, container, false);

    mSearchView = v.findViewById(R.id.search_view);
    viewPager =  getActivity().findViewById(R.id.pager);


    mRecyclerView = v.findViewById(R.id.my_recycler_view);


    setHasOptionsMenu(true);



    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new Recycleradapter_item_tab(getDataSet());
    mRecyclerView.setAdapter(mAdapter);
    RecyclerView.ItemDecoration itemDecoration =
            new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
    mRecyclerView.addItemDecoration(itemDecoration);


    adapter = new Recycleradapter_item_tab(this.getContext(),results );
    mRecyclerView.setAdapter(adapter);
    setupSearchView();
    return v;

}

private ArrayList<Item_object> getDataSet() {

    results = new ArrayList<Item_object>();
    Item_object obj;
int nl=0;
    //  adapter.notifyDataSetChanged();
    if(qty==null)
    {

        obj = new Item_object("Mobile phone", "20000");
        results.add(obj);
        obj = new Item_object("Table Fan", "2000");
        results.add(obj);
        obj = new Item_object("Bag", "1400");
        results.add(obj);
        obj = new Item_object("Clock", "500");
        results.add(obj);
    }
   else {
       nl=1;
      obj = new Item_object("Mobile phone", "20000", qty);
        results.add(obj);
        obj = new Item_object("Table Fan", "2000", qty);
        results.add(obj);
        obj = new Item_object("Bag", "1400", qty);
        results.add(obj);
        obj = new Item_object("Clock", "500", qty);
        results.add(obj);
    }

    Log.d("qty"+qty,"val");
  //  Toast.makeText(getActivity(), "qty "+nl , Toast.LENGTH_SHORT).show();
    return results;
}
private void setupSearchView() {

   // results.clone();

    mSearchView.setIconifiedByDefault(false);
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setSubmitButtonEnabled(true);
    // mSearchView.setQueryHint("Search Here");
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.home1, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.back:
            FragmentActivitiesInvoice fragmentActivitiesInvoice = new FragmentActivitiesInvoice();
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.content_frame, fragmentActivitiesInvoice);
            transaction.addToBackStack("tag");
            transaction.commit();
            //do something
            return true;

    }
    return super.onOptionsItemSelected(item);
}


@Override
public boolean onQueryTextSubmit(String query) {
    qty="3";
    Toast.makeText(getActivity(), "qty "+qty , Toast.LENGTH_SHORT).show();





    results.clone();
    adapter.notifyDataSetChanged();
    mAdapter.notifyDataSetChanged();

 return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    qty="3";
    Toast.makeText(getActivity(), "qty "+qty , Toast.LENGTH_SHORT).show();
    adapter.filter(newText);
    // mAdapter.filter(newText);
    results.clone();
mAdapter.notifyDataSetChanged();

adapter.notifyDataSetChanged();

    return false;
}
}

Recycleradapter_item_tab.java

public class Recycleradapter_item_tab  extends RecyclerView.Adapter <Recycleradapter_item_tab.DataObjectHolder>{
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<Item_object> mDataset,filterList;;
private static MyClickListener01 myClickListener;
private Context mContext;

private View.OnClickListener mListener;

public interface OnItemClickListener {
    public void onItemClick(View view, int position);

}

public interface ItemClickListener {
    void onClick(View view, int position, boolean isLongClick);
}




public ArrayList<Item_object> getmDataset() {
    return mDataset;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView itemname,rate,qty;
    TabLayout tabLayout;

    private ItemClickListener clickListener;



    public DataObjectHolder(View itemView) {
        super(itemView);

        rate = (TextView) itemView.findViewById(R.id.Rate);
        itemname = (TextView) itemView.findViewById(R.id.Itemname);
        qty = (TextView) itemView.findViewById(R.id.Qty);

        itemView.setOnClickListener(this);

        // Log.i(LOG_TAG, "Adding Listener");
        // itemView.setOnClickListener(this);
    }

    public void setClickListener(ItemClickListener itemClickListener) {
        this.clickListener = itemClickListener;
    }

    @Override
    public void onClick(View v) {
        // myClickListener.onItemClick(getPosition(), v);


       // tabLayout.getTabAt(1).select();


    }
}

public Recycleradapter_item_tab(Context contexts, ArrayList<Item_object> myDataset) {
    this.mContext = contexts;
    this.mDataset = myDataset;
    this.filterList = new ArrayList<Item_object>();
    // we copy the original list to the filter list and use it for setting row values
    this.filterList.addAll(this.mDataset);
}
public Recycleradapter_item_tab(ArrayList<Item_object> myDataset) {
    mDataset = myDataset;
}



@Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
    TextView name;

    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recyclerviewitem_item_tab, parent, false);
    //  name= view.findViewById(R.id.itemname);
  /*  name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    /*TabHost host = v.findViewById(R.id.tabLayout);
    host.setCurrentTab(1);
    host.setup();*/
   /* View viewPager = v.findViewById(R.id.pager);
    viewPager.setCurrentItem(1);
   /*Pager2 mPager = null;
    mPager.setCurrentItem(1);
    */
    //     }
    // });


    DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
    return dataObjectHolder;


}

@Override
public void onBindViewHolder(final DataObjectHolder holder, int position) {

    //Item_object  = filterList.get(position);


    holder.itemname.setText(mDataset.get(position).getItemname());

    holder.qty.setText(mDataset.get(position).getQty());
    holder.rate.setText(mDataset.get(position).getRate());
    // Item_object itemlist=filterList.get(position);

    Item_object listItem = filterList.get(position);
    holder.itemname.setText(listItem.getItemname());
    // customViewHolder.tvName.setText(listItem.name);
    holder.setClickListener(new ItemClickListener() {
        @Override
        public void onClick(View view, int position, boolean isLongClick) {

        }
    });

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Log.d("LOG","clicked1:"+holder.itemname.getText().toString());


            popUp(holder.itemView.getContext(), holder.itemname.getText().toString(),holder.qty.getText().toString(),holder.rate.getText().toString());
        }
    });








}
@Override
public int getItemCount() {
    return (null != filterList ? filterList.size() : 0);
}


private void popUp(final Context context, final String name, final String qty, final String rate) {

    Button closePopupBtn,btnSubmit;
    Spinner spinner1, spinner2;
    final PopupWindow popupWindow;
    LayoutInflater layoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View customView = layoutInflater.inflate(R.layout.add_item_popup,null);
    closePopupBtn = (Button) customView.findViewById(R.id.closePopupBtn);
    spinner1 = (Spinner) customView.findViewById(R.id.spinner1);
    spinner2 = (Spinner) customView.findViewById(R.id.spinner2);
    ArrayList<String> item = new ArrayList<String>();
    item.add("Package of 100");
    item.add("Package of 10");
    item.add("Batch of 100");
    item.add("Batch of 10");

    ArrayList<String> item1 = new ArrayList<String>();
    item1.add("Package of 100");
    item1.add("Package of 10");
    item1.add("Batch of 100");
    item1.add("Batch of 10");


    ArrayAdapter <CharSequence> adapter = new ArrayAdapter(context,R.layout.spinner_item,item);
    adapter.setDropDownViewResource(R.layout.spinner_item);
    spinner1.setAdapter(adapter);

    ArrayAdapter <CharSequence> adapter1 = new ArrayAdapter(context,R.layout.spinner_item,item);
    adapter.setDropDownViewResource(R.layout.spinner_item);
    spinner2.setAdapter(adapter1);

    btnSubmit = customView.findViewById(R.id.btnSubmit);





    popupWindow = new PopupWindow(customView, 700, ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.showAtLocation(popupWindow.getContentView(), Gravity.CENTER, 0, 0);
    popupWindow.setOutsideTouchable(false);
    popupWindow.setFocusable(true);
    popupWindow.update();

    closePopupBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            popupWindow.dismiss();
        }
    });

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           /* Toast.makeText(mContext,"Successfully updated", Toast.LENGTH_SHORT).show();
            popupWindow.dismiss();*/
            String PREFS_NAME = "IVS_ITEM";
            String ITEMS = "items";

            SharedPreferences settings;
            SharedPreferences.Editor editor;
            settings = context.getSharedPreferences(PREFS_NAME,
                    Context.MODE_PRIVATE);
            editor = settings.edit();
            Gson gson = new Gson();

            if (settings.contains("items")) {
                Log.d("LOG","having shared ");
                String jsonItems = settings.getString("items", null);
                List<Cash> products;

                Cash[] pItems = gson.fromJson(jsonItems,
                        Cash[].class);

                products = Arrays.asList(pItems);
                products = new ArrayList<Cash>(products);
                Cash cash = new Cash(qty,qty,rate,name);products.add(cash);


                String jsonProducts = gson.toJson(products);
                editor.putString(ITEMS, jsonProducts);
                editor.commit();


            }else {

                List<Cash> products;
                products = new ArrayList<Cash>();



                Cash cash = new Cash(qty,qty,rate,name);products.add(cash);

                String jsonProducts = gson.toJson(products);
                editor.putString(ITEMS, jsonProducts);
                editor.commit();


                Log.d("LOG","no shared ");
            }





                /*
                String jsonItems = settings.getString("Items", null);
                Gson gson = new Gson();
                List<Class> mListItems = new ArrayList<Class>();
                settings = context.getSharedPreferences("Items",
                        Context.MODE_PRIVATE);
                Class[] items = gson.fromJson(jsonItems,
                        Class[].class);

                mListItems = Arrays.asList(items);
                mListItems = new ArrayList<Class>(mListItems);
                Log.d("LOG", "Refund : " + mListItems.size());

                */





          /*  SharedPreferences settings;

            SharedPreferences.Editor editor = null;

            List<Class> mListItems = new ArrayList<Class>();
            settings = context.getSharedPreferences("Items",
                    Context.MODE_PRIVATE);

            if (settings.contains("Items")) {
                String jsonItems = settings.getString("Refund", null);
                Gson gson = new Gson();
                Class[] items = gson.fromJson(jsonItems,
                        Class[].class);

                mListItems = Arrays.asList(items);
                mListItems = new ArrayList<Class>(mListItems);
                Log.d("LOG", "Refund : " + mListItems.size());

                ArrayList<HashMap<String, String>> list;

                list = new ArrayList<HashMap<String, String>>();


            }*/

            Toast.makeText(context,"Successfully updated", Toast.LENGTH_SHORT).show();
            popupWindow.dismiss();


        }
    });


}


public void addItem(Item_object dataObj, int index) {
    mDataset.add(dataObj);
    notifyItemInserted(index);
}

public void deleteItem(int index) {
    mDataset.remove(index);
    notifyItemRemoved(index);
}




private static class MyClickListener01 {

}

public void setClickListener(View.OnClickListener callback) {
    mListener = callback;
}
public void filter(final String text) {

    // Searching could be complex..so we will dispatch it to a different thread...
    new Thread(new Runnable() {
        @Override
        public void run() {

            // Clear the filter list
            filterList.clear();

            // If there is no search value, then add all original list items to filter list
            if (TextUtils.isEmpty(text)) {

                filterList.addAll( mDataset);

            } else {
                // Iterate in the original List and add it to filter list...
                for (Item_object item :  mDataset) {
                    if (item.itemname.toLowerCase().contains(text.toLowerCase()) ) {
                        // Adding Matched items
                        filterList.add(item);
                    }
                }
            }

            // Set on UI Thread
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Notify the List that the DataSet has changed...
                    notifyDataSetChanged();
                }
            });

        }
    }).start();

}

}

Itemtab.java

public class Itemtab extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
//private RecyclerView.Adapter mAdapter;
private RecyclerView.Adapter mAdapter = new Recycleradapter_item_tab(getDataSet());
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
private Recycleradapter_item_tab adapter;
String qty;
// AutoCompleteTextView pview;
private SearchView mSearchView;
View v;

private ArrayList<Item_object> results;
ViewPager viewPager;
public Itemtab() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   v = inflater.inflate(R.layout.fragment_itemtab, container, false);

    mSearchView = v.findViewById(R.id.search_view);
    viewPager =  getActivity().findViewById(R.id.pager);


    mRecyclerView = v.findViewById(R.id.my_recycler_view);


    setHasOptionsMenu(true);



    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new Recycleradapter_item_tab(getDataSet());
    mRecyclerView.setAdapter(mAdapter);
    RecyclerView.ItemDecoration itemDecoration =
            new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
    mRecyclerView.addItemDecoration(itemDecoration);


    adapter = new Recycleradapter_item_tab(this.getContext(),results );
    mRecyclerView.setAdapter(adapter);
    setupSearchView();
    return v;

}

private ArrayList<Item_object> getDataSet() {

    results = new ArrayList<Item_object>();
    Item_object obj;
int nl=0;
    //  adapter.notifyDataSetChanged();
    if(qty==null)
    {

        obj = new Item_object("Mobile phone", "20000");
        results.add(obj);
        obj = new Item_object("Table Fan", "2000");
        results.add(obj);
        obj = new Item_object("Bag", "1400");
        results.add(obj);
        obj = new Item_object("Clock", "500");
        results.add(obj);
    }
   else {
       nl=1;
      obj = new Item_object("Mobile phone", "20000", qty);
        results.add(obj);
        obj = new Item_object("Table Fan", "2000", qty);
        results.add(obj);
        obj = new Item_object("Bag", "1400", qty);
        results.add(obj);
        obj = new Item_object("Clock", "500", qty);
        results.add(obj);
    }

    Log.d("qty"+qty,"val");
  //  Toast.makeText(getActivity(), "qty "+nl , Toast.LENGTH_SHORT).show();
    return results;
}
private void setupSearchView() {

   // results.clone();

    mSearchView.setIconifiedByDefault(false);
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setSubmitButtonEnabled(true);
    // mSearchView.setQueryHint("Search Here");
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.home1, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.back:
            FragmentActivitiesInvoice fragmentActivitiesInvoice = new FragmentActivitiesInvoice();
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.content_frame, fragmentActivitiesInvoice);
            transaction.addToBackStack("tag");
            transaction.commit();
            //do something
            return true;

    }
    return super.onOptionsItemSelected(item);
}


@Override
public boolean onQueryTextSubmit(String query) {






    results.clone();
    adapter.notifyDataSetChanged();
    mAdapter.notifyDataSetChanged();

 return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    qty="3";
    Toast.makeText(getActivity(), "qty "+qty , Toast.LENGTH_SHORT).show();
    adapter.filter(newText);
    // mAdapter.filter(newText);
    results.clone();
mAdapter.notifyDataSetChanged();
adapter.notifyDataSetChanged();

    return false;
}
}

enter image description here

enter image description here

The first image entering number in edittext. Second image it is clearing. How it is solve? Please help me?

Upvotes: 0

Views: 1428

Answers (1)

Sanjay Kumar
Sanjay Kumar

Reputation: 1185

first create a field current value in Item_object as -

int currentValue;

set the currentValue in each editText in onBindViewHolder(), You can keep editText blank if currentValue = 0
Now implement TextWatcher for each editText in recycler view.
on text change update currentValue based on position

Now if you filter than you will see your value remain in edittext for the item of given position

for textwatcher see the link - How to use the TextWatcher class in Android?

Upvotes: 1

Related Questions