Null object reference for Button defined in Dialog using ButterKnife - android

I have a problem about defining objects in Dialog screen via ButterKnife.
I can define a holder class to determie each object using in Dialog screen.
When I run the app, it throws an error shown below.
java.lang.NullPointerException: Attempt to read from field 'android.widget.Button com.example.dialog.AlertDialogActivity$ViewHolder.buttonUyeOl' on a null object reference
How can I connect each object via ButterKnifer to the Dialog Screen?
How can I fix it?
Here is my code shown below.
public class AlertDialogActivity extends AppCompatActivity {
#BindView(R.id.dialogAc)
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert_dialog);
ButterKnife.bind(this);
openDialog();
}
private void openDialog() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialogScreen();
}
});
}
private void openDialogScreen() {
LayoutInflater ınflater = this.getLayoutInflater();
View view = ınflater.inflate(R.layout.alert_dialog, null);
final ViewHolder holder;
if (view != null) {
holder = (ViewHolder) view.getTag();
} else {
holder = new ViewHolder(view);
view.setTag(holder);
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setView(view);
alert.setCancelable(false);
final AlertDialog dialog = alert.create();
holder.buttonUyeOl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), holder.mailEditText.getText().toString() + " "
+ holder.kadiEditText.getText().toString() + " " + holder.sifreEditText.getText().toString()
, Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
holder.buttonCik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
}
static final class ViewHolder {
#BindView((R.id.mailAdres))
EditText mailEditText;
#BindView(R.id.kullanici)
EditText kadiEditText;
#BindView(R.id.sifre)
EditText sifreEditText;
#BindView(R.id.buttonUyeOl)
Button buttonUyeOl;
#BindView(R.id.buttonExit)
Button buttonCik;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
XML file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#324589"
android:orientation="vertical"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/kullanici"
android:hint="Kullanıcı İsmini Giriniz"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/mailAdres"
android:hint="Mail Adresi Giriniz"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sifre"
android:inputType="textPassword"
android:hint="Şifre Giriniz"/>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Uye Ol"
android:id="#+id/buttonUyeOl"
/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="İptal Et"
android:id="#+id/buttonExit"
/>
</LinearLayout>
</LinearLayout>

My answer
private void openDialogScreen() {
LayoutInflater ınflater = this.getLayoutInflater();
View view = ınflater.inflate(R.layout.alert_dialog, null);
final ViewHolder holder = new ViewHolder(view);
....
}

Related

When I press the button to delete an item from ListView it deletes the last one

I have next problem with a list view: So on the layout (prod_row) I set an image view(rvCls) that I want to delete an item while clicked. It deletes an item, but is always the last one. If I close this activity and I reopen it, it deletes the correct item, but what should I do to see the change instantly and not have to refresh the page?
on the Cos class I build logic for list view and cosAdapter is the Adapter class for my list view
COS class the one with the list view
public class Cos extends AppCompatActivity {
ListView lvProd;
SwipeMenuListView listView;
Button btnTrm, btnCls;
TextView tvTotal;
DatabaseReference mDatabase;
ArrayList<Produs> list = new ArrayList<Produs>();
String email;
Integer contor = 1;
ImageView rvCls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cos);
FirebaseAuth mAuth;
mAuth=FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
email = currentUser.getEmail();
tvTotal = findViewById(R.id.tvTotal);
btnTrm = findViewById(R.id.btnTrm);
Intent i = getIntent();
list = (ArrayList<Produs>) i.getSerializableExtra("set");
Double total = 0.0;
for(Produs p: list){
total+= Double.valueOf(p.getPret()) * p.getQt();
}
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
if(hour == 15){
total /= 2;
}
tvTotal.setText("Total: " + String.valueOf(total) + " lei");
btnTrm = findViewById(R.id.btnTrm);
btnCls = findViewById(R.id.btnCls);
// lvProd = findViewById(R.id.lvProd);
listView = (SwipeMenuListView) findViewById(R.id.listView);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Istoric");
try {
ArrayAdapter<Produs> adapter = new cosAdapter(this, 0 ,list);
listView.setAdapter(adapter);
}catch (Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
btnCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("set",(Serializable)list);
startActivity(intent);
}catch (Exception e){
Toast.makeText(Cos.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
btnTrm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(Produs p : list){
IstoricData id= new IstoricData(email,p.getNume(),false,p.getQt());
Task t = mDatabase.push().setValue(id);
contor ++;
t.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
Toast.makeText(Cos.this, "Comanda a fost trimisa cu succes", Toast.LENGTH_SHORT).show();
}
});
t.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Cos.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
}
COS adapter the adapter class for my list view adapter
public class cosAdapter extends ArrayAdapter<Produs> {
private Context context;
//private List<Produs> produse;
ArrayList<Produs> produse;
public cosAdapter(Context context, int resource, ArrayList<Produs> objects){
super(context, resource, objects);
this.context = context;
this.produse = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
RecyclerView.ViewHolder holder;LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
TextView rvNume, rvPret, rvCantitate, rvQT;
ImageView rvImage;
CardView cardView;
ImageView rvCls;
Produs model = produse.get(position);
View view = inflater.inflate(R.layout.prod_row, null);
View cos = inflater.inflate(R.layout.activity_cos, null);
rvNume = view.findViewById(R.id.rvNume);
rvCantitate = view.findViewById(R.id.rvCantitate);
rvPret = view.findViewById(R.id.rvPret);
rvImage = view.findViewById(R.id.rvImage);
cardView = view.findViewById(R.id.cv);
rvQT = view.findViewById(R.id.rvQT);
rvCls = view.findViewById(R.id.rvCls);
rvPret.setText("Pret: "+model.getPret()+ " lei");
rvNume.setText(model.getNume());
rvCantitate.setText("Cantitate: "+model.getCantitate()+" grame");
rvQT.setText("Numar: x" +String.valueOf(model.getQt()));
Picasso.get().load(model.getImage()).into(rvImage);
rvCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
produse.remove(position);
cosAdapter.super.notifyDataSetChanged();
}
});
return view;
}
}
My layout for each item in list view
<?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:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<ImageView
android:id="#+id/rvCls"
android:layout_width="34dp"
android:layout_height="34dp"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:layout_margin="5dp"
android:layout_toRightOf="#+id/view"
android:clickable="true"
android:gravity="right"
app:srcCompat="#drawable/ic_baseline_close_24" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/rvImage"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_weight="2"
android:maxHeight="50dp"
tools:srcCompat="#tools:sample/avatars" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/rvNume"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textStyle="bold" />
<TextView
android:id="#+id/rvCantitate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/rvPret"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/rvQT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
There are 2 ways you could fix your code:
1.) Set position value as tag to your rvCls and fetch this tag for usage of position in your ClickListener
rvCls.setTag(position);
rvCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
produse.remove((int)v.getTag());
notifyDataSetChanged();
}
});
2.) Use a variable finalPosition in getView and use that as position inside ClickListener.
final int finalPosition = position;
rvCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
produse.remove(finalPosition);
notifyDataSetChanged();
}
});

Activity's background become black when i entered in activity or onLongPress of Listview

I am trying to implement one ListView in activity. In my XML there is a ListView to fill that ListView data I have invoked one WebService in AsynkTask. I have used BaseAdapter to set that ListView. Now, Whenever I came on that activity the background becomes black for fraction seconds of time and than disappear. Same things happened when I longpress on ListView. The screen shot had attached with this question as well as following are the code that I have implemented.
Main Activity's 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:background="#color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.agraeta.user.btl.ComboOfferListActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#color/strip_bg"
android:textColor="#color/white"
android:gravity="center"
android:textSize="17sp"
android:text="COMBO OFFERS"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollingCache="false"
android:cacheColorHint="#color/white"
android:id="#+id/list_comboOffers"
android:background="#color/white"
android:divider="#android:color/transparent"
android:dividerHeight="5dp"/>
</LinearLayout>
Java File Of Main Activity :
public class ComboOfferListActivity extends AppCompatActivity implements Callback<ComboOfferData> {
ListView list_comboOffers;
ComboOfferListAdapter offerListAdapter;
List<ComboOfferItem> offerItemList=new ArrayList<>();
AdminAPI adminAPI;
Custom_ProgressDialog dialog;
String userID="";
String roleID="";
AppPrefs prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_combo_offer_list);
prefs=new AppPrefs(this);
adminAPI=ServiceGenerator.getAPIServiceClass();
dialog=new Custom_ProgressDialog(this,"Please Wait...");
dialog.setCancelable(false);
userID=prefs.getUserId();
roleID=prefs.getUserRoleId();
if(roleID.equals(C.ADMIN) || roleID.equals(C.COMP_SALES_PERSON) || roleID.equals(C.DISTRIBUTOR_SALES_PERSON)){
roleID=prefs.getSubSalesId();
userID=prefs.getSalesPersonId();
}
fetchIDs();
setActionBar();
}
private void fetchIDs() {
list_comboOffers=(ListView) findViewById(R.id.list_comboOffers);
offerListAdapter=new ComboOfferListAdapter(offerItemList,ComboOfferListActivity.this);
list_comboOffers.setAdapter(offerListAdapter);
list_comboOffers.setCacheColorHint(Color.TRANSPARENT);
list_comboOffers.requestFocus(0);
list_comboOffers.setScrollingCacheEnabled(false);
dialog.show();
Log.e("UR",userID+"-->"+roleID);
Call<ComboOfferData> offerDataCall=adminAPI.comboOfferDataCall(userID,roleID);
offerDataCall.enqueue(this);
}
private void setActionBar() {
// TODO Auto-generated method stub
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
mActionBar.setCustomView(R.layout.actionbar_design);
View mCustomView = mActionBar.getCustomView();
ImageView image_drawer = (ImageView) mCustomView.findViewById(R.id.image_drawer);
ImageView img_home = (ImageView) mCustomView.findViewById(R.id.img_home);
ImageView img_notification = (ImageView) mCustomView.findViewById(R.id.img_notification);
FrameLayout unread = (FrameLayout) mCustomView.findViewById(R.id.unread);
image_drawer.setImageResource(R.drawable.ic_action_btl_back);
img_home.setVisibility(View.GONE);
img_notification.setVisibility(View.GONE);
unread.setVisibility(View.GONE);
image_drawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
}
#Override
public void onResponse(Call<ComboOfferData> call, Response<ComboOfferData> response) {
dialog.dismiss();
offerItemList.clear();
ComboOfferData offerData=response.body();
if(offerData.isStatus()){
offerItemList.addAll(offerData.getOfferItemList());
}
else {
Globals.Toast2(this,offerData.getMessage());
}
Log.e("Size","-->"+offerItemList.size());
offerListAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<ComboOfferData> call, Throwable t) {
dialog.dismiss();
Globals.showError(t,this);
}
#Override
public void onBackPressed() {
finish();
}
}
Adapter Class :
public class ComboOfferListAdapter extends BaseAdapter {
List<ComboOfferItem> offerItemList=new ArrayList<>();
Activity activity;
LayoutInflater inflater;
public ComboOfferListAdapter(List<ComboOfferItem> offerItemList, Activity activity) {
this.offerItemList = offerItemList;
this.activity = activity;
inflater=activity.getLayoutInflater();
}
#Override
public int getCount() {
return offerItemList.size();
}
#Override
public Object getItem(int position) {
return offerItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder=new ViewHolder();
convertView=inflater.inflate(R.layout.layout_combooffer_list,parent,false);
holder.img_offerThumb=(ImageView) convertView.findViewById(R.id.img_offerThumb);
holder.txt_offerTitle=(TextView) convertView.findViewById(R.id.txt_offerTitle);
holder.card_comboOffer = (CardView) convertView.findViewById(R.id.card_comboOffer);
holder.layout_combo = (LinearLayout) convertView.findViewById(R.id.layout_combo);
convertView.setTag(holder);
}
else {
holder= (ViewHolder) convertView.getTag();
}
Picasso.with(activity).load(Globals.IMAGE_LINK+offerItemList.get(position).getImagePath())
.into(holder.img_offerThumb);
holder.txt_offerTitle.setText(offerItemList.get(position).getOfferTitle());
holder.img_offerThumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, ComboOfferActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("combo_id", offerItemList.get(position).getOfferID());
activity.startActivity(intent);
}
});
holder.txt_offerTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, ComboOfferActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("combo_id", offerItemList.get(position).getOfferID());
activity.startActivity(intent);
}
});
return convertView;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
Log.e("Called","-->"+offerItemList.size());
}
private class ViewHolder {
ImageView img_offerThumb;
TextView txt_offerTitle;
CardView card_comboOffer;
LinearLayout layout_combo;
}
}
Layout File For Adapter's View :
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/card_comboOffer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical"
cardBackgroundColor="#fff"
app:cardCornerRadius="2dp"
app:cardElevation="5dp"
app:theme="#style/CardView.Dark">
<LinearLayout
android:id="#+id/layout_combo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/img_offerThumb"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_gravity="center"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/txt_offerTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f58634"
android:padding="5dp"
android:textColor="#color/white"
android:layout_gravity="center"
android:textSize="15sp"/>
</LinearLayout>
</android.support.v7.widget.CardView>

Everything shows inside the dialog except the listview

I'm trying to have an edittext with a list view to choose contacts from a custom listview here is the code but everything appears except the listview:
InstantDialogBox:
public class InstantTextBoxDialog extends DialogFragment {
private EditText message;
private Button sendToAll;
private Button sendToLimited;
private ListView listContacts;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
LayoutInflater inflater=getActivity().getLayoutInflater();
View view=inflater.inflate(R.layout.intant_message,null,false);
message=(EditText)view.findViewById(R.id.instant_message);
sendToAll=(Button) view.findViewById(R.id.btn_sent_to_all);
listContacts=(ListView)view.findViewById(R.id.list_checkable);
ChackableListAdapter adapter=new ChackableListAdapter(getActivity(),R.layout.list_chackable_item,new ArrayList<Contact>());
sendToAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!TextUtils.isEmpty(message.getText())){
ChatService.bind.getService().sendMessageToAll(message.getText().toString());
message.setText("");
dismiss();
}
}
});
sendToLimited=(Button) view.findViewById(R.id.btn_send_to_limited);
sendToLimited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!TextUtils.isEmpty(message.getText())){
}
}
});
listContacts.setAdapter(adapter);
builder.setView(view);
return builder.create();
}
CheckableListAdapter:
public class ChackableListAdapter extends ArrayAdapter<Contact> {
private ArrayList<Contact> contacts;
private int resource;
private Context context;
private ArrayList<Contact> choosen;
public ChackableListAdapter(#NonNull Context context, int resource,ArrayList<Contact> arrayList) {
super(context, resource,arrayList);
this.context=context;
this.resource=resource;
this.contacts=arrayList;
contacts= DatabaseHandler.getDataBaseHandler(context).getAllRegisteredContacts();
choosen=new ArrayList<>();
}
#Nullable
#Override
public Contact getItem(int position) {
return contacts.get(position);
}
#NonNull
#Override
public View getView(final int position, #Nullable View view, #NonNull ViewGroup parent) {
Holder holder=null;
if (view == null || view.getTag() == null) {
holder=new Holder();
view= LayoutInflater.from(context).inflate(resource,null);
holder.phone=(TextView)view.findViewById(R.id.text_number);
holder.name=(CheckBox)view.findViewById(R.id.checkbox_number);
view.setTag(holder);
}
else {
holder = (Holder) view.getTag();
}
holder.phone.setText(getItem(position).phone_number);
holder.name.setText(getItem(position).name);
holder.name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
choosen.add(getItem(position));
}else {
int i=0;
for (Contact contact:choosen){
if(contact.phone_number.equalsIgnoreCase(getItem(position).phone_number)){
choosen.remove(i);
notifyDataSetChanged();
}
i++;
}
}
}
});
Log.wtf("generating rows"," yes");
return view;
}
private class Holder{
public CheckBox name;
public TextView phone;
}
public ArrayList<Contact> getChoosenContacts(){
return choosen;
}
}
intant_message.xml:
<?xml version="1.0" encoding="utf-8"?>
<EditText
android:id="#+id/instant_message"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_weight="5"
android:gravity="top"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/btn_send_to_limited"
android:text="send to limited"
android:layout_width="95dp"
android:textSize="10sp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
<Button
android:id="#+id/btn_sent_to_all"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:text="send to all"
android:textSize="10sp"
android:layout_below="#+id/btn_send_to_limited"
android:layout_marginTop="5dp"
/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools">
<ListView
android:id="#+id/list_checkable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/list_chackable_item">
</ListView>
</LinearLayout>
list_chacakble_item:
<?xml version="1.0" encoding="utf-8"?>
<CheckBox
android:id="#+id/checkbox_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abdallah"
android:textStyle="bold"/>
<TextView
android:id="#+id/text_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7656156165156651"
android:layout_marginLeft="30dp"/>
The dialog box is trigered from an adapter of a listview and that's the adapter's code:
holder.replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InstantTextBoxDialog exampleDialog=new InstantTextBoxDialog();
exampleDialog.show(((Activity) activity).getFragmentManager(),"sadsdadsaadassd");
}
});
But till now nothing shows except the buttons and no listview

How do I replace my popupmenu code with ListPopupWindow?

Currently , I am programatically creating a popupmenu which displays a list of floors and a title. However, changing the background color of just the title and adding a close button to title is turning out to be a nightmare.
I want to replace this popupmenu with a list popup window so I can add an XML file with background attribute for the title with a black color as the background and a close button on the right and white background for items in the menu. Is there a way I can achieve this with list popup window? Here's my code for that:
private void floorMenu(ImageView btnFloorMenu){
MapData data = new MapDao(MyPlugin.mapId);
final List<Floor> flList = dao.getFloors();
// set popupMenu
final PopupMenu floorsPm = new PopupMenu(MapViewActivity.this,btnFloorMenu);
MenuItem titleItem = floorsPm.getMenu().add(Menu.NONE, Menu.NONE, Menu.NONE, "Floors");
int i = 1;
for(Floor fl : flList)
{
floorsPm.getMenu().add(Menu.NONE, i,i, fl.getName());
if(i>3)
break;
i++;
}
// add popup listener
floorsPm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
// onClick
#Override
public boolean onMenuItemClick(MenuItem item){
// get floorname
int flOrder = item.getOrder();
if(flOrder == Menu.NONE )
return true;
flOrder--;
final String floorId = flList.get(flOrder).getMapId();
// set camera to floor
runOnUiThread(new Runnable() {
#Override
public void run() {
floorsPm.dismiss();
mapFragment.getMapManager().setCameraLayer(floorId, false);
Log.d(TAG, "post cameraLayer set");
changedSteps = true;
pauseNav();
}
});
return true;
}
});
floorsPm.show();
}
Here is my example to create show a ListPopupWindow
First, create layout item_list_popup_window for each item of ListPopupWindow
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e4e4e4"
android:paddingTop="1dp"
android:orientation="horizontal">
<TextView
android:id="#+id/text_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" />
<Button
android:id="#+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
Second, create an Adapter for your ListPopupWindow like
public class ListPopupWindowAdapter extends BaseAdapter{
private Activity mActivity;
private List<String> mDataSource = new ArrayList<>();
private LayoutInflater layoutInflater;
private OnClickDeleteButtonListener clickDeleteButtonListener;
ListPopupWindowAdapter(Activity activity, List<String> dataSource, #NonNull OnClickDeleteButtonListener clickDeleteButtonListener){
this.mActivity = activity;
this.mDataSource = dataSource;
layoutInflater = mActivity.getLayoutInflater();
this.clickDeleteButtonListener = clickDeleteButtonListener;
}
#Override
public int getCount() {
return mDataSource.size();
}
#Override
public String getItem(int position) {
return mDataSource.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_list_popup_window, null);
holder.tvTitle = (TextView) convertView.findViewById(R.id.text_title);
holder.btnDelete = (Button) convertView.findViewById(R.id.button_delete);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
// bind data
holder.tvTitle.setText(getItem(position));
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickDeleteButtonListener.onClickDeleteButton(position);
}
});
return convertView;
}
public class ViewHolder{
private TextView tvTitle;
private Button btnDelete;
}
// interface to return callback to activity
public interface OnClickDeleteButtonListener{
void onClickDeleteButton(int position);
}
}
Third, You create a function for create and show ListPopupWindow
private void showListPopupWindow(View anchorView) {
final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
listPopupWindow.setWidth(600);
List<String> sampleData = new ArrayList<>();
sampleData.add("A");
sampleData.add("B");
sampleData.add("CCCCCCCCCCCCCC");
sampleData.add("D");
sampleData.add("EEEEEEEEE");
listPopupWindow.setAnchorView(anchorView);
ListPopupWindowAdapter listPopupWindowAdapter = new ListPopupWindowAdapter(this, sampleData, new ListPopupWindowAdapter.OnClickDeleteButtonListener() {
#Override
public void onClickDeleteButton(int position) {
Toast.makeText(MainActivity.this, "Click delete " + position, Toast.LENGTH_SHORT).show();
listPopupWindow.dismiss();
}
});
listPopupWindow.setAdapter(listPopupWindowAdapter);
listPopupWindow.show();
}
Finally, you can show the ListPopupWindow by
showListPopupWindow(v);
for example, if you want to show it when click button
anyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showListPopupWindow(v);
}
});
Full Demo is here
Please Try this code, Maybe you wont like this
private void floorMenu(ImageView btnFloorMenu){
final Dialog customDialog = new Dialog(this);
customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
customDialog.setContentView(R.layout.item_dialog_coustom_design);
TextView clickItem = (TextView)customDialog.findViewById(R.id.item_click);
TextView clickItem1 = (TextView)customDialog.findViewById(R.id.item_click1);
TextView clickItem2 = (TextView)customDialog.findViewById(R.id.item_click2);
Button btnClose = (Button)customDialog.findViewById(R.id.btn_close);
clickItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
clickItem1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
clickItem2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
customDialog.show();
}
Create Linearlayout layout_width="280dp" layout_height="wrap_content"
android:orientation="vertical" file name item_dialog_coustom_design.xml then put this code
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Title"
android:background="#000"
android:textColor="#fff"
android:padding="12dp"
android:textSize="20sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click1"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click2"
android:textSize="16sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:background="#fff"
android:gravity="right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_close"
android:text="Close"/>
</LinearLayout>

Android - SetOnItemClickListener doesn't work

I know here we have a lot of questions like mine, but I don't know why none works for me.
My objective: I have an AlertDialog with a ListView with a check box in each row, I can select some of the items, and I wish to make an ArrayList with the elements selected.
For that reason, I'm calling the SetOnclickListener, I put a Log inside the method, but does nothing.
I tried with focusable and clickable almost everywhere, but my Log doesn't appear.
Here My alert Dialog
private void callAdditionalDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(ConfigProductActivity.this);
final View additionalView = layoutInflater.inflate(R.layout.dialog_additional, null);
additionalView.setFocusable(true);
// set the custom dialog components - text, buttons, accountants
TextView titleDialog = (TextView) additionalView.findViewById(R.id.title_additional);
titleDialog.setTypeface(boldFont);
Button buttonAccept = (Button) additionalView.findViewById(R.id.button_accept);
buttonAccept.setTypeface(boldFont);
Button buttonCancel = (Button) additionalView.findViewById(R.id.button_cancel);
buttonCancel.setTypeface(boldFont);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ConfigProductActivity.this);
alertDialogBuilder.setView(additionalView);
final AlertDialog alertD = alertDialogBuilder.create();
alertD.setCanceledOnTouchOutside(false);
//Fill object of additional
final ListView additionalListView = (ListView) additionalView.findViewById(R.id.list_additional);
TextView additionalNotFound = (TextView) additionalView.findViewById(R.id.additional_not_found);
if (!withoutModifiers){
additionalAdapter = new AdditionalAdapter(ConfigProductActivity.this, additionalList);
additionalListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
additionalListView.setAdapter(additionalAdapter);
final ArrayList<ModifierEntity> modifierList = new ArrayList<ModifierEntity>();
additionalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Object modifier = additionalListView.getAdapter().getItem(position).toString();
Log.d(TAG, "SOMETHIIIIING");
}
});
}
else{
additionalListView.setVisibility(View.GONE);
additionalNotFound.setVisibility(View.VISIBLE);
additionalNotFound.setTypeface(font);
buttonCancel.setVisibility(View.GONE);
}
//End of fill object of additional
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
buttonAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//additional.setText(additionalAdapter.getCount());
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
alertD.show();
}
Here my adapter:
public class AdditionalAdapter extends ArrayAdapter {
private static String TAG = AdditionalAdapter.class.getName();
private List<ModifierEntity> originalData = null;
private ConfigProductActivity activity;
private Typeface font;
private Typeface boldFont;
private static ModifierEntity modifier;
public AdditionalAdapter (ConfigProductActivity activity, List<ModifierEntity> listArray){
super(activity, R.layout.additional_item);
this.activity = activity;
this.originalData = listArray ;
font = Typeface.createFromAsset(activity.getAssets(),"HelveticaNeueThn.ttf");
boldFont = Typeface.createFromAsset(activity.getAssets(), "avgardm.ttf");
}
public static class Row
{
public TextView labelName;
public TextView labelPrice;
public CheckBox check;
}
#Override
public int getCount() {
return originalData.size();
}
#Override
public ModifierEntity getItem(int position) {
return originalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int colorFont = activity.getResources().getColor(R.color.brown_tataki);
final Row holder;
View rowView = convertView;
// reuse views
if (convertView == null) {
holder = new Row();
LayoutInflater inflater = LayoutInflater.from(activity);
rowView = inflater.inflate(R.layout.additional_item, null);
rowView.setClickable(true);
//rowView.setFocusable(false);
// configure view holder
holder.labelName = (TextView) rowView.findViewById(R.id.additional_name);
holder.labelPrice = (TextView) rowView.findViewById(R.id.additional_price);
holder.check = (CheckBox) rowView.findViewById(R.id.additional_check);
rowView.setTag(holder);
}
else {
holder = (Row) convertView.getTag();
// rowView.setClickable(true);
}
final ModifierEntity itm = originalData.get(position);
holder.labelName.setText(itm.getModifier_name());
holder.labelName.setTypeface(font);
holder.labelName.setTextColor(colorFont);
holder.labelPrice.setText(GlobalParameters.CURRENCY.concat(String.valueOf(itm.getModifier_cost())));
holder.labelPrice.setTypeface(boldFont);
holder.labelPrice.setTextColor(colorFont);
return rowView;
}
}
Here My Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange_tataki"
android:text="#string/additional_title"
android:textColor="#color/white"
android:textSize="20sp"
android:gravity="center"
android:id="#+id/title_additional"
android:padding="5dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title_additional"
android:gravity="center"
android:background="#color/white"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_additional"
android:divider="#color/brown_tataki"
android:dividerHeight="0.5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/list_additional"
android:gravity="center"
android:padding="10dp"
android:visibility="gone"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_not_found"
android:text="#string/additional_not_found"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttons"
android:layout_marginBottom="10dp"
android:layout_below="#+id/additional_not_found"
android:gravity="center"
android:layout_marginTop="20dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/button_cancel"
android:background="#color/green_tataki"
android:text="#string/button_cancel"
android:textSize="15sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_accept"
android:padding="10dp"
android:background="#color/green_tataki"
android:text="#string/button_accept"
android:textSize="15sp"
android:layout_marginLeft="15dp"
/>
</LinearLayout>
</RelativeLayout>
And Here my item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="QUESO"
android:singleLine="true"
android:padding="10dp"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/additional_price"
android:padding="10dp"
android:text="Bs. 500"
android:textColor="#color/brown_tataki"
android:layout_toRightOf="#id/additional_name"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="#+id/additional_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp" />
Using interfaces I can solve my problem, this link provided me the solution, and bassically consist in create an interface and implement in my activity.
Like this:
1.- Interface
public interface MyListener {
void folderClicked();
}
2.- Implements the interface in the activity
public class ActivityA extends Activity implements MyListener
3.- You will have to auto override the method folderClicked it will look like this:
#Override
protected void folderClicked() {
// Do your stuff here.
}
4.- Send the activity listener to the adapter with constructor like this:
MyAdpater adapter = new MyAdpater(ActivityA.this);
5.- Your adapter class your code should be like this:
public class TimeLineAdapter extends BaseAdapter {
private MyListener mListener;
public TimeLineAdapter(MyListener listener) {
super();
mListener = listener;
}
holder.iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onFolderClicked()
//code to do stuff when the image is clicked
}

Categories

Resources