PopUp window with Spinner OnItem Selection Not Working - java

I was tried to implement the spinner inside the popupwindow, selection of spinner item with OnItemselection was not working, I have two kind of Experimental Test in this scenario.
Experimental Test-1 I've implemented the OnItemSelectionListener,result of experiment test-1 is
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference.
Experimental Test-2 use getSelectedItem() method to get the position, result of only first position value showing in Toast.
Here is my code,
Java Code Implementation
private void DialogTest(){
String[] Title = {"Select Title","Teacher","Employer","Lecturer","Coach","Mentor","Co-Worker","Prinicpal","Dean","Other"};
LayoutInflater layoutInflater =(LayoutInflater)getActivity().getBaseContext().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.dialog_test, null);
final PopupWindow popupWindow = new PopupWindow(popupView, isPortrait ? getHeightByPercentage(50) : getWidthByPercentage(50), LinearLayout.LayoutParams.WRAP_CONTENT);
Spinner popupSpinner = (Spinner)popupView.findViewById(R.id.popupspinner);
Button button_test_cancel =(Button)popupView.findViewById(R.id.button_test_cancel);
Button button_test_send =(Button)popupView.findViewById(R.id.button_test_send);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, Title);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupWindow.showAsDropDown(btn_request_testimonial, 50, -30);
//Step-1 Experimental Test
popupSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int selectedPosition = position;
Toast.makeText(getActivity().getBaseContext(),selectedPosition, Toast.LENGTH_LONG).show();
}
});
//Step-2 Experimental Test
final String categoryTitle = popupSpinner.getSelectedItem().toString();
Toast.makeText(getActivity().getBaseContext(),categoryTitle, Toast.LENGTH_LONG).show();
button_test_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
button_test_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
}
dialog_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="38dp"
android:background="#color/colorAccent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/testimonial_request"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#color/white"
android:layout_centerInParent="true"/>
</RelativeLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<EditText
android:id="#+id/edTxt_Testi_Name"
style="#style/edittextstyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="textPersonName"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorAccent"
tools:ignore="HardcodedText"/>
<!--android:text="Trd#sm20"-->
</android.support.design.widget.TextInputLayout>
<Spinner
android:id="#+id/popupspinner"
style="#style/edittextstyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dialog"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorAccent"/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<EditText
android:id="#+id/edTxt_Testi_Email"
style="#style/edittextstyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="E-Mail"
android:inputType="textEmailAddress"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorAccent"
tools:ignore="HardcodedText"/>
<!--android:text="Trd#sm20"-->
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<EditText
android:id="#+id/edTxt_Testi_Org"
style="#style/edittextstyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Organization Name"
android:inputType="textPersonName"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorAccent"
tools:ignore="HardcodedText"/>
<!--android:text="Trd#sm20"-->
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<EditText
android:id="#+id/edTxt_Testi_Comments"
style="#style/edittextstyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Comments"
android:inputType="textMultiLine"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorAccent"
tools:ignore="HardcodedText"/>
<!--android:text="Trd#sm20"-->
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/button_test_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentEnd="true"
android:layout_alignParentRight="true" android:layout_alignParentTop="true"
android:background="#color/colorAccent"
android:text="Send"
android:textColor="#color/white"
android:textSize="12sp"/>
<Button
android:id="#+id/button_test_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button_test_send"
android:layout_marginEnd="6dp"
android:layout_marginRight="6dp"
android:layout_toLeftOf="#+id/button_test_send" android:layout_toStartOf="#+id/button_test_send"
android:background="#color/colorAccent"
android:text="Cancel"
android:textColor="#color/white"
android:textSize="12sp"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>

You are setting onClickListener to spinner thus it's being clicked by the first item. Rater you should use onItemSelectedListener
//Step-1 Experimental Test
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(SolveTest.this, String.valueOf(position), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

try this one
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Object item = arg0.getItemAtPosition(arg2);
if (item!=null) {
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
Toast.makeText(MainActivity.this, "Selected",
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

Related

setOnClickListener not working in fragment Android

I am trying to apply a setOnClickListener on an EditText View in a Fragment and for some reason, It is not working, the code in the listener doesn't execute when I click on the EditText.
The fragment xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp"
tools:context=".add_payment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/testpay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Time:"
android:textColor="#000000"
android:textSize="24sp" />
<EditText
android:id="#+id/add_pay_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:ems="10"
android:inputType="time" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Date:"
android:textColor="#000000"
android:textSize="24sp" />
<EditText
android:id="#+id/add_pay_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name:"
android:textColor="#000000"
android:textSize="24sp" />
<EditText
android:id="#+id/add_pay_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Table:"
android:textColor="#000000"
android:textSize="24sp" />
<EditText
android:id="#+id/add_pay_table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Amount:"
android:textColor="#000000"
android:textSize="24sp" />
<EditText
android:id="#+id/add_pay_amm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
</LinearLayout>
</LinearLayout>
The fragment code:
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_payment_fragment, container, false);
view.findViewById(R.id.add_pay_time).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "aaaa", Toast.LENGTH_LONG).show();
}
});
return view;
}
Edit text needs focus to call onClick().
Solution 1
request focus when you set listener:
EditText editText = view.findViewById(R.id.add_pay_time);
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "aaaa", Toast.LENGTH_LONG).show();
}
});
editText.requestFocus(); //request focus
Solution 2
set on touch listener:
EditText editText = view.findViewById(R.id.add_pay_time);
editText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction())
Toast.makeText(getContext(), "aaaa", Toast.LENGTH_LONG).show();
return false;
}
});
Solution 3
you can use onClickListener and onFocusChangeListener together:
EditText editText = view.findViewById(R.id.add_pay_time);
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToast();//call your method
}
});
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
showToast();//call your method
}
});
EditText edText = view.findViewById(R.id.add_pay_time);
edText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "aaaa", Toast.LENGTH_LONG).show();
}
});
Use getActivity().getApplicationContext() instead

Send data inside recyclerview with button in Fragment

I have 2 layouts where first layout for Fragment and second layout for RecyclerView. I have created CardView in RecyclerView, every CardView has some data. And I have created button below RecyclerView where the function of button for sending Data on CardView. My problem is I don't know how to send data when i click button in Fragment.
Fragment Layout :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container_daftar_alamat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.menu.menu_signin.menu.MenuAddressFragment">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<Button
android:id="#+id/buttonMoveTambahAlamat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:background="#null"
android:drawableStart="#drawable/ic_tambah_alamat"
android:drawablePadding="10dp"
android:text="Tambah Alamat"
android:textAllCaps="false"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="normal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Daftar Alamat"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="bold" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rc_tambah_alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/gunakanAlamat"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="100dp"
android:background="#drawable/bg_button_red"
android:text="Gunakan Alamat"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="16sp" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
RecyclerView Layout :
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="12dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="12dp"
android:orientation="vertical"
app:cardBackgroundColor="#color/colorWhite"
app:cardCornerRadius="4dp"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/radioButton">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/nameUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Muhammad Rafi Bahrur Rizki"
android:textColor="#color/colorBlack"
android:textSize="14sp"
android:textStyle="bold"
tools:ignore="UnusedAttribute" />
<TextView
android:id="#+id/addressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:maxLines="1"
android:text="(Alamat Kantor)"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/streetName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Mangga Dua Square Lantai 1 Jakarta,"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp"
tools:ignore="UnusedAttribute" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/blokAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="Blok C no. 148 - 150"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/cityAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/countryAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/phoneUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="0812951825"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<Button
android:id="#+id/buttonEdit"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:drawableStart="#drawable/ic_edit"
android:text="Edit"
android:textAllCaps="false"
android:textSize="12sp" />
<Button
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#id/buttonEdit"
android:drawableStart="#drawable/ic_delete"
android:text="Hapus"
android:textAllCaps="false"
android:textSize="12sp" />
</RelativeLayout>
</TableLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
When i select RadioButton, only data in RadioButton will be obtained. And when i click button, the data will be send to another activity.
Adapter RecyclerView :
public class AdapterGetAddress extends RecyclerView.Adapter<AdapterGetAddress.ViewHolder> {
Context context;
private List<ModelGetAddress> modelGetAddressList;
private BaseApiService baseApiService;
private int previousSelected = -1;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_address, parent, false);
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final ModelGetAddress adapterAddress = modelGetAddressList.get(position);
}
#Override
public int getItemCount() {
return modelGetAddressList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView nameUser, addressUser, streetName, blokAddressUser, cityAddressUser, countryUser, phoneUser;
private RadioButton radioButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameUser = itemView.findViewById(R.id.nameUser);
addressUser = itemView.findViewById(R.id.addressUser);
streetName = itemView.findViewById(R.id.streetName);
countryUser = itemView.findViewById(R.id.countryAddressUser);
blokAddressUser = itemView.findViewById(R.id.blokAddressUser);
cityAddressUser = itemView.findViewById(R.id.cityAddressUser);
phoneUser = itemView.findViewById(R.id.phoneUser);
radioButton = itemView.findViewById(R.id.radioButton);
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
}
});
}
}
}
Code in Fragment :
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Here's were i'm stuck
}
});
return view;
}
}
You can solve this via an interface.
public interface ItemClickedCallback{
void onItemClicked(String nameUser //, the other data you wanna pass );
}
pass it through the constructor of your adapter.
Use this adapter constructor
ItemClickedCallback callback;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList, ItemClickedCallback callback) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
this.callback= callback;
}
When checking a radio button of any item; call the interface method, like this.
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
callback.onItemClicked(getNameUser //, the rest..);
}
});
Now, when you initialize the adapter in the fragment, create the new interface via the constructor and assign the data to class variables like this.
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
private String nameUser_;
// the rest...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
AdapterGetAddress adapter = new AdapterGetAddress(getActivity, list, new ItemClickedCallback() {
#Override
public void onItemClicked(String userName //, the rest..) {
// assign to the class variable like this
nameUser_ = userName;
// the rest..
}
}););
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Use the data as you want..
}
});
return view;
}
}

Listview items duplicated/wrong position when scrolling

This question is been asked multiple times, but everyone has his specific usage of listview adapters (ArrayAdapter or BaseAdapter).
I searched a lot before asking this question, and this same problem happened to me before and i solved it using Holder class, and cleaning code to make it the minimum possible.
But now, i am creating another interface which contains a listview and needs a BaseAdapter to fill it using a List of Object (List).
The weird thing in my case is, if my listview contains only 4 items ( 4 rows ) then everything is ok, but if it contains more than 4, first items will be duplicated, and if i scroll down/up fast , items got wrong positions.
Here is my code :
public class OrdersAdapter extends BaseAdapter {
List<Order> ordersList;
FragmentActivity activity;
private int height;
public OrdersAdapter(FragmentActivity activity, List<Order> ordersList){
this.activity = activity;
this.ordersList = ordersList;
height = Constants.getOneThirdScreenHight(activity);
}
#Override
public int getCount() {
return ordersList.size();
}
#Override
public Order getItem(int position) {
return ordersList.get(position);
}
#Override
public long getItemId(int position) {
return ordersList.hashCode();
}
private class MyHolder{
TextView orderNumber, orderDate, menuCount, orderPrice, orderStatus, orderTelephone, orderStoreName;
ImageView orderDelete, menuPicture;
Order order, mOrder;
String numberText = activity.getResources().getString(R.string.order_number);
HashMap<String, String> map;
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
}
#Override
public View getView (final int position, View convertView, ViewGroup parent) {
View vi;
final MyHolder holder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater)activity.getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new MyHolder();
vi = layoutInflater.inflate(R.layout.sent_order_item, null);
holder.order = getItem(position);
holder.mOrder = new Order();
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.height = height;
vi.findViewById(R.id.order_history_layout).setLayoutParams(layoutParams);
holder.orderNumber = (TextView) vi.findViewById(R.id.order_number);
holder.orderDate = (TextView) vi.findViewById(R.id.order_date);
holder.orderDelete = (ImageView) vi.findViewById(R.id.order_delete);
holder.orderPrice = (TextView) vi.findViewById(R.id.order_history_price);
holder.orderStatus = (TextView) vi.findViewById(R.id.order_history_status);
holder.orderStoreName = (TextView) vi.findViewById(R.id.order_history_store);
holder.orderTelephone = (TextView) vi.findViewById(R.id.order_history_phone);
holder.menuCount = (TextView) vi.findViewById(R.id.order_menu_count1) ;
holder.menuPicture = (ImageView) vi.findViewById(R.id.order_picture);
vi.setTag(holder);
}else{
vi = convertView;
holder = (MyHolder) vi.getTag();
}
//Getting Restaurants infos ( name and telephone ) from firebase
holder.mDatabase.child(Constants.STORES_PROFILES + "/" + holder.order.getOwner_uid() + "/" + holder.order.getStore_id())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(holder.map==null){
holder.map = (HashMap<String, String>)dataSnapshot.getValue();
}
if(dataSnapshot.getValue()!=null) {
holder.orderStoreName.setText(holder.map.get(Constants.NAME));
holder.orderTelephone.setText(holder.map.get(Constants.TELEPHONE));
}
//notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//checking Order's status (received, validated, in progress, delivered)
holder.mDatabase.child(Constants.ORDERS + "/" + holder.order.getOwner_uid() + "/" + holder.order.getStore_id() + "/" + holder.order.getOrderId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
try {
holder.mOrder = dataSnapshot.getValue(Order.class);
if (!holder.order.getStatus().equals(holder.mOrder.getStatus())) {
holder.order.setStatus(holder.mOrder.getStatus());
//update status value for the user
holder.mDatabase.child(Constants.USERS+"/"+ Authentication.getCurrentUser().getUid()+"/"+Constants.SUBMITTED_ORDERS_KEY
+"/"+holder.order.getOrderId()+"/"+Constants.STATUS).setValue(holder.mOrder.getStatus());
//notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
displayOrder(holder);
return vi;
}
public void displayOrder(MyHolder holder){
holder.orderStatus.setText(holder.order.getStatus());
holder.orderNumber.setText(holder.numberText + holder.order.getOrderNumber());
holder.orderDate.setText(Utils.parseDateToDisplay((Long)holder.order.getCreated_at()));
holder.menuCount.setText(holder.order.getMyMealsList().get(0).getQuantity()+"");
holder.orderPrice.setText(holder.order.getTotal_price_formatted());
Glide.with(activity)
.load(holder.order.getMyMealsList().get(0).getMain_image())
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(holder.menuPicture);
if(OrdersContainerFragment.pDialog.isShowing()){
OrdersContainerFragment.pDialog.dismiss();
}
}
}
Here is my "xml" file :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/order_history_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100">
<LinearLayout
android:id="#+id/save_order_linear"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:background="#fcf5ef"
android:orientation="horizontal"
android:weightSum="100">
<TextView
android:id="#+id/order_number"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/order_number"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:typeface="serif"/>
<TextView
android:id="#+id/order_date"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="50"
android:gravity="center"
android:text="00/00/0000"
android:textColor="#color/colorPrimary"
android:typeface="serif"/>
</LinearLayout>
<LinearLayout
android:id="#+id/save_order_pics"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="#+id/save_order_linear"
android:layout_marginLeft="5dp"
android:layout_marginTop="15dp"
android:layout_weight="74"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:weightSum="100">
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="33">
<ImageView
android:id="#+id/order_picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ProgressBar
android:id="#+id/order_progressBar1"
style="#android:style/Widget.DeviceDefault.Light.ProgressBar.Large"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:indeterminate="true"
android:indeterminateDrawable="#drawable/my_progressbar"
android:padding="22dp"
android:visibility="gone"/>
<TextView
android:id="#+id/order_menu_count1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="false"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="false"
android:gravity="bottom|right"
android:paddingBottom="15dp"
android:paddingRight="15dp"
android:text="ABCD"
android:textColor="#color/gray"
android:textSize="22dp"
android:typeface="serif"/>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="67"
android:orientation="vertical"
android:paddingLeft="15dp"
android:weightSum="100">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="false"
android:layout_weight="1"
android:text="#string/order_price"
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
<TextView
android:id="#+id/order_history_price"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="false"
android:layout_weight="1"
android:text="..."
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="#string/order_status"
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
<TextView
android:id="#+id/order_history_status"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="..."
android:textColor="#color/colorAccent"
android:typeface="monospace"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="#string/Phone"
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
<TextView
android:id="#+id/order_history_phone"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="..."
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="25"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="#string/order_store"
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
<TextView
android:id="#+id/order_history_store"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="..."
android:textColor="#color/colorPrimary"
android:typeface="monospace"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/save_order_pics"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#fcf5ef"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>

Search bar to search a listView

I have made an app that has a list of insurance companies using a listView. The listView is populated using an array adapter. I want to be able to search through this list with a search bar and only return an insurance company that is searched for. I have fallowed a tutorial however it doesn't filter the insurance companies. Can someone tell me where I'm going wrong
Here is my code so far
insurance.xml
<EditText
android:layout_width="400dp"
android:layout_height="60dp"
android:id="#+id/editText"
android:layout_marginBottom="50dp"
/>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="107dp">
</ListView>
myList.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_weight="10"
android:background="#26BFDA">
<LinearLayout
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="2"
>
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="6"
android:orientation="vertical"
>
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical"
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="20dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:src="#drawable/nextarrow"
/>
</LinearLayout>
</LinearLayout>
Insurance.java
public class Insurance extends AppCompatActivity {
ListView list;
ArrayAdapter<String> newadapter;
EditText inputSearch;
String[] itemname ={
"AA",
"Acorn",
"Admiral",
};
Integer[] imgid= {
R.drawable.aa,
R.drawable.acorn,
R.drawable.admiral,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insurance);
CustomListAdapter adapter=new CustomListAdapter(this, itemname, imgid);
list=(ListView)findViewById(R.id.list);
newadapter = new ArrayAdapter<String>(this, R.layout.mylist, R.id.item, itemname);
inputSearch = (EditText) findViewById(R.id.editText);
list.setAdapter(newadapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Insurance.this.newadapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String Slecteditem = itemname[+position];
Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
if (Slecteditem.toString() == "AA") {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:028 9032 2232"));
startActivity(intent);
}
if (Slecteditem.toString() == "Carrot") {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:028 9032 2265"));
startActivity(intent);
}
}
});

can't get reference with include tag

I have developed a app. In my app there are:
Product.java (fragment)
product.xml (contain a listview and a include tag)
list_single(row of listview)
This is my code:
Product.java
public class Product extends Fragment{
public int ITEM_SELECTED = 1;
ArrayAdapter<String> PROD;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product, container, false);
String [] ELEMENTS1 = {
"A","b","c"};
ListView listView = (ListView)v.findViewById(R.id.listView);
TextView a = (TextView)v.findViewById(R.id.textView);
ImageButton add_cart = (ImageButton)v.findViewById(R.id.button2);
switch(ITEM_SELECTED){
case 1: PROD = new ArrayAdapter<String>(getActivity(), R.layout.single_row, R.id.textView, ELEMENTS1);break;
}
listView.setAdapter(PROD);
add_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("asd","asd");
}
});
return v;
}
}
product.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:id="#+id/layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="PRODOTTI"
android:id="#+id/textView10"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:textColor="#000"
android:textSize="20dp"
android:textStyle="bold"
android:typeface="monospace" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"
android:layout_marginTop="85dp"
android:id="#+id/view1"
android:layout_centerHorizontal="true"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/view1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp" />
<include layout="#layout/single_row"
android:id="#+id/ly"
android:visibility="gone"/>
</RelativeLayout>
and this is list_single.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/editText"
android:layout_alignBottom="#+id/button2"
android:layout_toLeftOf="#+id/button2"
android:layout_toStartOf="#+id/button2" />
<ImageButton
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button2"
android:src="#drawable/product"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#null"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_marginRight="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Q.TA"
android:textColor="#083CBF"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PREZZO"
android:textColor="#083CBF"
android:id="#+id/textView3"
android:layout_alignTop="#+id/textView2"
android:layout_toLeftOf="#+id/textView2"
android:layout_toStartOf="#+id/textView2"
android:layout_marginRight="10dp" />
<EditText
android:layout_width="50dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_alignTop="#+id/editText"
android:layout_alignLeft="#+id/textView3"
android:layout_alignStart="#+id/textView3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="COLLI"
android:textColor="#083CBF"
android:id="#+id/textView4"
android:layout_alignTop="#+id/textView3"
android:layout_toLeftOf="#+id/textView3"
android:layout_toStartOf="#+id/textView3"
android:layout_marginRight="20dp" />
<EditText
android:layout_width="50dp"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/editText3"
android:layout_alignTop="#+id/editText2"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/textView"
android:layout_toStartOf="#+id/textView4"
android:id="#+id/ded"
android:layout_toLeftOf="#+id/textView4"
android:layout_marginRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:singleLine="false"
android:id="#+id/textView"
android:layout_below="#+id/textView4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center" />
</FrameLayout>
Problem:
When i try to click on imagebutton it doesn't show Log.d. It seems that
OnClickListener is not run. I have tried: setText("xy"); but that doesn't work either.
Is the problem is in listview?
I can't use the elements of single_row. My app doesn't crash. Please, help! Thank you
UPDATE:
listView.setAdapter(PROD);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ImageButton add_cart = (ImageButton) view.findViewById(R.id.button2);
add_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("asd", "asd");
Toast.makeText(getActivity(), "hi",
Toast.LENGTH_LONG).show();
}
});
}
});
This doesn't work for me...
You are doing it wrong.
ImageButton add_cart = (ImageButton)v.findViewById(R.id.button2);
Your imagebutton button2 is in list_single.xml and you are trying to find it in View inflated using product.xml. And that too before you are setting the adapter for the ListView. So at the point where you are getting reference to your ImageButton there is view rendering for the ListView. Here is what you should ideally do
listView.setAdapter(PROD);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ImageButton add_cart = (ImageButton)view.findViewById(R.id.button2);
//more logic
}
});

Categories