Android RecyclerView doesn't show cardview on the screen - android

I have a database, and I am trying to show the columns on cardview on my app.
Nothing wrong database side I guess. I have checked it, for example I can add items to the database. I can login-register. But when I add my items, I should be seeing them on the cardview after addition process.
When I add item on the database, it goes back to the recyclerview layout but shows nothing. Only an empty page.
No errors on the debug process until now.
Here is my cardview layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="15dp"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stock Name"
android:textColor="#color/colorPrimary" />
<TextView
android:id="#+id/barcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stock Code" />
<TextView
android:id="#+id/tvQuantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity" />
<TextView
android:id="#+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price" />
<TextView
android:id="#+id/tvCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cost" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
recyclerlayout:
<?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="wrap_content"
android:orientation="horizontal"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
RECYCLER.JAVA
public class recycler extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private DatabaseHelper myDb;
private itemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler);
myDb = new DatabaseHelper(this);
Intent intent =getIntent();
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.addMenu:
goToAddActivity();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void goToAddActivity(){
Intent intent = new Intent(recycler.this, add.class);
startActivity(intent);
}
}
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ViewHolder> {
private List<list> mItemsList;
private Context mContext; //to inflate list layout
private RecyclerView mRecyclerV;
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView nameTxt;
public TextView quantityTxt;
public TextView priceTxt;
public TextView costTxt;
public TextView barcodeTxt;
public View layout;
public ViewHolder( View v) {
super(v);
layout = v;
nameTxt = (TextView) v.findViewById(R.id.itemName);
quantityTxt = (TextView) v.findViewById(R.id.tvQuantity);
priceTxt = (TextView) v.findViewById(R.id.tvPrice);
costTxt = (TextView) v.findViewById(R.id.tvCost);
barcodeTxt = (TextView) v.findViewById(R.id.barcode);
}
}
public void add(int position, list list) {
mItemsList.add(position, list);
notifyItemInserted(position);
}
public void remove(int position) {
mItemsList.remove(position);
notifyItemRemoved(position);
}
// Provide a suitable constructor (depends on the kind of dataset)
public itemAdapter(List<list> myDataset, Context context, RecyclerView recyclerView) {
mItemsList = myDataset;
mContext = context;
mRecyclerV = recyclerView;
}
// Create new views (invoked by the layout manager)
#Override
public itemAdapter.ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
//create a new view
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v =inflater.inflate(R.layout.activity_list, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final list list = mItemsList.get(position);
holder.nameTxt.setText("Stock Name: " + list.getName());
holder.barcodeTxt.setText("Barcode: " + list.getBarcode());
holder.quantityTxt.setText("Quantity: " + list.getQuantity());
holder.priceTxt.setText("Price: " + list.getPrice());
holder.costTxt.setText("Cost: " + list.getCost());
holder.layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Choose option");
builder.setMessage("Update or delete stock?");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
goToUpdateActivity(list.getId());
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHelper dbHelper = new DatabaseHelper(mContext);
dbHelper.deleteRecord(list.getId(), mContext);
mItemsList.remove(position);
mRecyclerV.removeViewAt(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mItemsList.size());
notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
});
}
private void goToUpdateActivity(long listID){
Intent goToUpdate = new Intent(mContext, update.class);
goToUpdate.putExtra("listID", listID);
mContext.startActivity(goToUpdate);
}
#Override
public int getItemCount() {
return mItemsList.size();
}
}

Related

in Android Studio the Button in ListView does not work

I'm creating a shopping list similar to listonic app, but I'm stuck in listView, the button inside my listView does not read clicks but OnItemClickListener is working well. the objective is the user can save multiple shopping list for example grocery list, self-care list, etc. I have searched everywhere but did not find something that works.
here is the activity for the shopping list
private ArrayList<String> data = new ArrayList<String>();
private FloatingActionButton addList;
private ListView listView;
private TextView nList_name;
private DatabaseHelper dbHelper;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_lists);
dbHelper = new DatabaseHelper(this);
listView = findViewById(R.id.list_view);
addList = findViewById(R.id.add_list);
loadTaskList();
addList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add_item();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(MyListsActivity.this, "list num "+position, Toast.LENGTH_SHORT).show();
}
});
}
private class MyListAdapter extends ArrayAdapter<String>
{
private final int layout;
public MyListAdapter(#NonNull Context context, int resource, #NonNull List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
final int pos = position;
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
viewHolder = new ViewHolder();
viewHolder.thumbnail = convertView.findViewById(R.id.list_item_thumbnail);
viewHolder.title = convertView.findViewById(R.id.list_item_text);
viewHolder.button = convertView.findViewById(R.id.list_item_btn);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(getItem(position));
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MyListsActivity.this, "btn at row "+position, Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(viewHolder);
return convertView;
}
}
public static class ViewHolder
{
ImageView thumbnail;
TextView title;
Button button;
}
private void add_item()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MyListsActivity.this);
builder.setTitle("Add new list");
View v = LayoutInflater.from(MyListsActivity.this).inflate(R.layout.shop_list_dialog_item, null, false);
builder.setView(v);
TextInputEditText nList_name_edit_txt = v.findViewById(R.id.list_name_edit_txt);
TextInputLayout nList_name_layout = v.findViewById(R.id.list_name_layout);
builder.setPositiveButton("CREATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i){}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {dialogInterface.cancel();}
});
AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String task = String.valueOf(nList_name_edit_txt.getText()).trim();
if (!TextUtils.isEmpty(nList_name_edit_txt.getText()))
{
dbHelper.insertNewTask(task);
loadTaskList();
dialog.cancel();
}
else{nList_name_layout.setError("Name your list");}
}
});
}
private void loadTaskList() {
ArrayList<String> taskList = dbHelper.getTaskList();
if(mAdapter==null){
mAdapter = new ArrayAdapter<String>(this, R.layout.list_wrapper_item, R.id.list_item_text, taskList);
listView.setAdapter(mAdapter);
}
else{
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
}
}
this is the xml for the shopping list activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MyListsActivity">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/add_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/ic_baseline_add_24" />
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</ListView>
</androidx.constraintlayout.widget.ConstraintLayout>
and this is the layout for the adapter
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:descendantFocusability="blocksDescendants">
<ImageView
android:id="#+id/list_item_thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_image_24" />
<TextView
android:id="#+id/list_item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
android:textColor="#color/youtube"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/list_item_thumbnail"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/list_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Your MyListAdapter works as it should except int position should be final int position because button calls it from inner class.
The problem is that you are not using MyListAdapter. So change
mAdapter = new ArrayAdapter<String>(this, R.layout.list_wrapper_item, R.id.list_item_text, taskList);
To
mAdapter = new MyListAdapter(this, R.layout.list_wrapper_item, taskList);

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 SetImageResource failed to work in Gridview on button click

I try to display some items in a Gridview and set button click listener. When the item was clicked, it shows a dialog box, if clicking yes, it will change the Imageview.
java coding
public class table extends AppCompatActivity implements AdapterView.OnItemClickListener{
GridView gridView;
my_adapter my_adapter;
String table_names[]={"1a","1b","1c","1d","2a","2b","2c","2d","3a","3b","3c","3d"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
gridView=(GridView)findViewById(R.id.gridview);
my_adapter=new my_adapter(this,table_names);
gridView.setAdapter(my_adapter);
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(final AdapterView<?> adapterView, final View view, final int i, long l) {
new AlertDialog.Builder(this)
.setTitle("Table number: "+adapterView.getItemAtPosition(i).toString())
.setMessage("Open Table?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
my_adapter.change_img(); // change to new image
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
my_adapter.change_img2(); // change back to original image
}
})
.show();
}
}
class my_adapter extends BaseAdapter{
ImageView imageView;
LayoutInflater inflater=null;
Context ctx;
String table_names[];
ArrayList store_table_no;
my_adapter(Context ctx, String table_names[]){
this.ctx=ctx;
this.table_names=table_names;
store_table_no=new ArrayList<Integer>();
for (int i=0;i<table_names.length;i++){
store_table_no.add(table_names[i]);
}
}
#Override
public int getCount() {
return store_table_no.size();
}
#Override
public Object getItem(int i) {
return store_table_no.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View row=view;
if(row==null){
inflater=(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.single,null);
}
TextView tv_table_no=(TextView)row.findViewById(R.id.table_no);
imageView=(ImageView)row.findViewById(R.id.imageView);
tv_table_no.setText(""+store_table_no.get(i));
return row;
}
public void change_img(){
imageView.setImageResource(R.drawable.table_full);
}
public void change_img2(){
imageView.setImageResource(R.drawable.table3d2);
}
}
single.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="101"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/table_no"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="22sp" />
<ImageView
app:srcCompat="#drawable/table"
android:id="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="130dp"
android:layout_height="100dp" />
</RelativeLayout>
Here is a screenshot, please have a look
It simply doesn't change the imageview. Looks like something is wrong with my coding. anyone knows what's happening ?
You are implementing GridView's OnItemClickListener to show a dialog and getting decision from user for each item. When you are showing up a dialog it needs to update current clicked item of grid. But in your case you have change_img() in adapter. No position specification is given to the adapter.
To make it work, move your logic from activity to adapter. Handle the click events with the positions.
In your activity,
public class table extends AppCompatActivity{
GridView gridView;
my_adapter my_adapter;
String table_names[] = {"1a", "1b", "1c", "1d", "2a", "2b", "2c", "2d", "3a", "3b", "3c", "3d"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
gridView = (GridView) findViewById(R.id.grid);
my_adapter = new my_adapter(this, table_names);
gridView.setAdapter(my_adapter);
}
class my_adapter extends BaseAdapter {
LayoutInflater inflater = null;
Context ctx;
String table_names[];
ArrayList<String> store_table_no;
my_adapter(Context ctx, String table_names[]) {
this.ctx = ctx;
this.table_names = table_names;
store_table_no = new ArrayList<>();
store_table_no.addAll(Arrays.asList(table_names));
}
#Override
public int getCount() {
return store_table_no.size();
}
#Override
public Object getItem(int i) {
return store_table_no.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View row = view;
if (row == null) {
inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.single, null);
}
RelativeLayout layout = (RelativeLayout) row.findViewById(R.id.relative_layout);
TextView tv_table_no = (TextView) row.findViewById(R.id.table_no);
final ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
tv_table_no.setText(store_table_no.get(i));
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(GridActivity.this)
.setTitle("Table number: " + store_table_no.get(i))
.setMessage("Open Table?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
imageView.setImageResource(R.mipmap.ic_launcher);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
imageView.setImageResource(R.drawable.icon);
}
})
.show();
}
});
return row;
}
}
}
In your xml file add id to Parent RElative Layout as follows,
single.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/relative_layout"
android:clickable="true"
android:layout_height="match_parent">
<TextView
android:text="101"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/table_no"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="22sp" />
<ImageView
app:srcCompat="#drawable/table"
android:id="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="130dp"
android:layout_height="100dp" />
</RelativeLayout>
I hope it will help you.

multi select checkable dropdown check boxes in alert dailog in android

I am trying to alert multi selection dropdown check box in alert dialog like spinner but with check boxes in my android application ,can any one help here?
It may not work properly with respect to touch events. I guess that you will have to clone it and develop something like MultiSelectSpinner. You might wanna consult this answer for further detail.
Use customlayout in AlertDialog class using api, dialog.setconteView() method. You can add whatever widgets you wish in your custom layout
Use below code:-
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.setTitle("Title");
builder.setMultiChoiceItems(list, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog,
int indexSelected, boolean isChecked)
{
}
})
.setPositiveButton("OK",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog,
int id)
{
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id)
{
}
});
dialog = builder.create();
dialog.show();
As your view, Cant get the click events in AlertDialog.
Best solution for your Question. Just include the custom layout and get the Alertdialog Click events in your activity.
create a XML layout which you want to design
Include that XML layout in your activity through SetContentView()
Get the click events through your activity.
Please check this link for reference http://www.mkyong.com/android/android-custom-dialog-example/
Happy Coding :)
for Custom checkbox dropdown Dialogbox first we need to create MultiCheckAdaptar
public class MultiCheckAdaptar extends RecyclerView.Adapter<MultiCheckAdaptar.MyViewHolder> {
protected Context context;
private LayoutInflater inflater;
private ArrayList<ModelSpacialization> joblist ;
private String TYPE = "";
private int count = 0 ;
MultiCheckAdaptar.OnItemClickListener listener;
public interface OnItemClickListener {
void onClick(ModelSpacialization jobs, int pos , boolean type);
}
public MultiCheckAdaptar(Context context, ArrayList<ModelSpacialization> list, MultiCheckAdaptar.OnItemClickListener listener) {
this.context = context;
this.listener = listener;
if (context != null) {
inflater = LayoutInflater.from(context);
this.joblist= new ArrayList<>();
this.joblist.addAll(list);
}
}
public MultiCheckAdaptar.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_ckeck_item , parent, false);
MultiCheckAdaptar.MyViewHolder holder = new MultiCheckAdaptar.MyViewHolder(view);
return holder;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(#NonNull final MultiCheckAdaptar.MyViewHolder holder, final int position) {
ModelSpacialization item = joblist.get(position);
holder.txt_item.setText(item.getName());
if(item.isCheck())
holder.txt_item.setChecked(true) ;
else
holder.txt_item.setChecked(false) ;
holder.txt_item.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listener.onClick(item, position, false);
}
});
}
#Override
public int getItemCount() {
return joblist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
CheckBox txt_item ;
public MyViewHolder(View itemView) {
super(itemView);
txt_item = itemView.findViewById(R.id.txt_item);
}
}
}
layout_check_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/txt_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/size_10"
android:text="text"
android:textSize="#dimen/size_16" />
</RelativeLayout>
dialog_dropdwon_recyle.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:text="TItle"
android:id="#+id/tv_dialogTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#color/primary"
android:fontFamily="#font/poppins_medium"
android:textSize="#dimen/size_16"
tools:ignore="SpUsage" />
<ImageButton
android:id="#+id/btn_dialog_close"
android:layout_width="#dimen/size_25"
android:layout_height="#dimen/size_25"
android:layout_alignParentEnd="true"
android:layout_gravity="right"
android:background="#drawable/btn_grey_transparent"
android:elevation="1dp"
android:padding="#dimen/size_5"
android:src="#drawable/ic_close" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_dialog_close"
android:paddingHorizontal="#dimen/size_5"
android:orientation="vertical">
<EditText
android:id="#+id/edit_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search..."
android:visibility="gone" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/dialog_list"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/size_10"
android:scrollbars="none" />
<Button
android:id="#+id/btn_save"
android:layout_width="match_parent"
android:layout_height="#dimen/size_40"
android:layout_marginHorizontal="#dimen/size_10"
android:layout_marginTop="#dimen/size_10"
android:layout_marginBottom="#dimen/size_10"
android:background="#drawable/button_primary"
android:fontFamily="#font/poppins_medium"
android:text="Save"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="#dimen/size_15" />
</LinearLayout>
</RelativeLayout>
in Activity
Dialog dg_industries = new Dialog(context);
selected_spaci = new HashSet<>();
industresList.addAll(industries2);
selected_spaci = new HashSet<>();
dg_industries.setContentView(R.layout.dailogbox_dwondwon_recycle);
final RecyclerView indview = (RecyclerView) dg_industries.findViewById(R.id.dialog_list);
final TextView title = (TextView) dg_industries.findViewById(R.id.tv_dialogTitle);
title.setVisibility(View.VISIBLE);
title.setText("Select Specialization");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
indview.setLayoutManager(linearLayoutManager);
adaptor = new MultiCheckAdaptar(context, industresList, new MultiCheckAdaptar.OnItemClickListener() {
#Override
public void onClick(ModelSpacialization jobs, int pos, boolean type) {
jobs.setCheck(type);
selected_spaci.add(jobs);
Log.e("industries2", new Gson().toJson(industresList));
}
});
dg_industries.setCancelable(false);
dg_industries.show();

Spinner value disappear after layout visibility is changed + specific flows

I have a custom list view with layout contain two layouts, called upper and bottom.
upper layout contain spinner, set and remove buttons.
bottom layout contain text view and back button.
By default bottom layout is in GONE state and when the user clicks on set button upper layout is GONE and bottom is VISIBLE (clicking on back button in bottom layout will return upper bottom back).
my problem is spinner value is disappear after specific flows:
Flow 1:
Add two items
Click on SET button on the first item
Remove the second item
Click on 'Back' button on the first item
Flow 2:
Click on SET
Rotate screen
Click on Back
Just to be clear, spinner values are exist and if drop it down you'll found the names (and I have android:configChanges="keyboardHidden|orientation|screenSize" in my manifest).
So, why spinner value is disappear after those flows ?
Here is my code:
Names.java
public class Names
{
private String name;
private int nameIndex;
private Boolean isNameOnTop;
public Names()
{
name = "";
isNameOnTop = true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNameIndex() {
return nameIndex;
}
public void setNameIndex(int nameIndex) {
this.nameIndex = nameIndex;
}
public Boolean getIsNameOnTop() {
return isNameOnTop;
}
public void setIsNameOnTop(Boolean isNameOnTop) {
this.isNameOnTop = isNameOnTop;
}
}
MainActivity.Java
public class MainActivity extends Activity
{
ArrayList<Names> namesArray = new ArrayList<>();
ListView lvNames;
ListviewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvNames = (ListView) findViewById(R.id.listView);
adapter = new ListviewAdapter(this, namesArray);
lvNames.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add)
{
namesArray.add(new Names());
adapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
}
ListviewAdapter.java
public class ListviewAdapter extends BaseAdapter
{
public Activity context;
public LayoutInflater inflater;
private ArrayList<Names> namesID;
private boolean isDeleted;
public ArrayList<Names> getNamesID() {
return namesID;
}
public void setNamesID(ArrayList<Names> namesID) {
this.namesID = namesID;
}
// Constructor
public ListviewAdapter(Activity context, ArrayList<Names> names)
{
super();
setNamesID(names);
this.context = context;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return getNamesID().size();
}
#Override
public Names getItem(int position) {
return getNamesID().get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder
{
RelativeLayout relativeLayout_Upper;
RelativeLayout relativeLayout_Bottom;
Spinner spNames;
Button btn_set, btn_remove, btn_back;
TextView tvChosen;
int index;
}
#Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_row, null);
holder.relativeLayout_Upper = (RelativeLayout) view.findViewById(R.id.lvRow_upper_layout);
holder.relativeLayout_Bottom = (RelativeLayout) view.findViewById(R.id.lvRow_bottom_layout);
holder.spNames = (Spinner) view.findViewById(R.id.spNames);
holder.btn_set = (Button) view.findViewById(R.id.btn_set);
holder.btn_remove = (Button) view.findViewById(R.id.btn_remove);
holder.btn_back = (Button) view.findViewById(R.id.btn_back);
holder.tvChosen = (TextView) view.findViewById(R.id.tv_chosen);
view.setTag(holder);
}
else
holder = (ViewHolder) view.getTag();
holder.index = i;
if (isDeleted)
{
holder.spNames.setSelection(getItem(holder.index).getNameIndex());
holder.tvChosen.setText("Chosen: " + getItem(holder.index).getName());
if (getItem(holder.index).getIsNameOnTop())
{
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
}
else
{
holder.relativeLayout_Upper.setVisibility(View.GONE);
holder.relativeLayout_Bottom.setVisibility(View.VISIBLE);
}
}
// pop spinner names
String[] names = new String[]{"Tom", "Ben", "Gil", "Adam", "Moshe", "Adi", "Michael", "Yasmin", "Jessica", "Caroline", "Avi", "Yael"};
final ArrayAdapter<String> spNamesAdapter = new ArrayAdapter<String>
(view.getContext(), android.R.layout.simple_spinner_dropdown_item, names);
spNamesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spNames.setAdapter(spNamesAdapter);
holder.spNames.setSelection(getItem(holder.index).getNameIndex());
holder.spNames.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//holder.spNames.setTag(position);
getItem(holder.index).setNameIndex(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.btn_set.setTag(i);
holder.btn_set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getItem(holder.index).setName(holder.spNames.getSelectedItem().toString());
int position = (Integer) v.getTag();
holder.tvChosen.setText("Chosen: " + getItem(position).getName());
holder.relativeLayout_Upper.setVisibility(View.GONE);
holder.relativeLayout_Bottom.setVisibility(View.VISIBLE);
getItem(holder.index).setIsNameOnTop(false);
}
});
// remove
holder.btn_remove.setTag(i);
holder.btn_remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
namesID.remove(position);
notifyDataSetChanged();
isDeleted = true;
}
});
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
}
});
return view;
}
}
activity_main.xml: contain ListView only.
upper_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spNames" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SET"
android:id="#+id/btn_set" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REMOVE"
android:id="#+id/btn_remove" />
</LinearLayout>
bottom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Chosen:"
android:id="#+id/tv_chosen"
android:layout_marginRight="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BACK"
android:id="#+id/btn_back" />
</LinearLayout>
listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvRow_upper_layout">
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/upper_view"
android:id="#+id/includeRow_register"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp" />
</RelativeLayout>
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvRow_bottom_layout"
android:visibility="gone">
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/bottom_view"
android:id="#+id/includeRow_showData"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp" />
</RelativeLayout>
</LinearLayout>
In your ListviewAdapter, change:
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
}
});
to:
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
notifyDataSetChanged();
// OR you can use this
// holder.spNames.requestLayout();
}
});
Whenever you click on "Add" in the method onOptionsItemSelected() you add an object new names() into the list, and in the Names class, the value of attribute name is set to ""
I guess that's why you getting an empty item in the spinner.

Categories

Resources