Dynamically inserting list items to listview in android - android

Friends i'm new to android and learning on my own. I was creating invoice manager app for learning. Here products are added by the admin and that is working fine. User has only permission to create invoice. When user arrives into create_invoice activity he has set of frame layouts in which one is for adding items. When user presses the frame layout he is made to see another activity where he can find all set of list items along with the product price in List view which admin has added. Now when user presses an item he is again brought back to create_invoice activity and a alert box appears which asks the qty required. When user enters the qty and clicks OK button, for the first the list item is displayed properly as i require. But when i add second item, 1st item gets replaced. So now my problem is how can i resolve this problem.. Guys please help me. Codes you people find may be very silly but i'm still learning. Thanks in advance.
Create_invoice activity
//data from activity invoice add_item
product_name = intent.getStringExtra("product_name");
product_price = intent.getDoubleExtra("product_price",0);
//product_qty = intent.getIntExtra("product_qty",0);
product_code = intent.getIntExtra("product_code",0);
if(product_name!= null && product_price!= 0 && product_code!= 0)
{
try {
builder = new AlertDialog.Builder(this);
builder.setTitle("Product Qty");
layoutInflater = LayoutInflater.from(Create_invoice.this);
view = layoutInflater.inflate(R.layout.dialoglayout_invoice,null);
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
EditText etxt_dialog_qty=(EditText)view.findViewById(R.id.
etxt_dialog_qty);
int qty = Integer. parseInt (etxt_dialog_qty.getText().
toString().trim());
invoice_product_list products = new invoice_product_list
(product_name, product_price, qty, product_code);
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.add(products);
customAdapterInvoice.notifyDataSetChanged();
//listview in create_invoice activity
listView_additem = (ListView)
findViewById(R.id.listview_additem);
listView_additem.setAdapter(customAdapterInvoice);
alertDialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
catch (Exception e)
{
System.out.print(e);
}
}
customAdapter
public class custom_adapter_invoice extends ArrayAdapter
<invoice_product_list> {
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view =
layoutInflater.inflate(R.layout.custom_row_invoice_item,parent,false);
invoice_product_list products = getItem(position);
TextView txt_product_name =
(TextView)view.findViewById(R.id.txt_product_name);
TextView txt_product_price =
(TextView)view.findViewById(R.id.txt_product_price);
TextView txt_product_qty =
(TextView)view.findViewById(R.id.txt_product_qty);
TextView txt_product_code =
(TextView)view.findViewById(R.id.txt_product_code);
txt_product_name.setText(products.getProduct_name());
txt_product_price.setText(String.valueOf(products.getProduct_price()));
txt_product_qty.setText(String.valueOf(products.getProduct_qty()));
txt_product_code.setText(String.valueOf(products.getProduct_code()));
return view;
}
create invoice activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.tournonstop.m.invoicemanager.Create_invoice"
tools:showIn="#layout/activity_create_invoice">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/darker_gray">
<include layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="85dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_company">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/company_name"
android:id="#+id/txt_company_name"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_date"
android:id="#+id/txt_invoice_date"
android:layout_gravity="right"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_no"
android:id="#+id/textView3"
android:layout_marginLeft="15dp"
android:layout_marginTop="45dp"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_client"
android:clickable="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/to"
android:id="#+id/txt_to"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/txt_client_address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:hint="#string/client_hint"/>
</FrameLayout>
----listview to add items-----
<FrameLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_add_item"
android:clickable="true">
<ListView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="#+id/listview_additem"
android:divider="#040404" />
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_sub_total">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total_label"
android:id="#+id/txt_sub_total_label"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total"
android:id="#+id/txt_sub_total"
android:layout_gravity="right"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textStyle="bold"
android:hint="#string/total_hint" />
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/invoice_btn"
android:textStyle="bold"
android:background="#color/colorPrimaryDark"
android:textColor="#android:color/white"
android:clickable="true"
android:id="#+id/btn_invoice_save" />
</LinearLayout>
< /android.support.v4.widget.DrawerLayout>
invoice product list(getters and setters)
package com.tournonstop.m.invoicemanager;
public class invoice_product_list {
private String product_name;
private double product_price;
private int product_qty;
private int product_code;
public invoice_product_list(){
}
public invoice_product_list(String product_name,double
product_price,int product_qty,int product_code){
this.product_name = product_name;
this.product_price = product_price;
this.product_qty = product_qty;
this.product_code = product_code;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_code() {
return product_code;
}
public void setProduct_code(int product_code) {
this.product_code = product_code;
}
public double getProduct_price() {
return product_price;
}
public void setProduct_price(double product_price) {
this.product_price = product_price;
}
public int getProduct_qty() {
return product_qty;
}
public void setProduct_qty(int product_qty) {
this.product_qty = product_qty;
}
}

Add item to your list that you're using in adapter and (after verifying adapter is not null ) call method notifyDataSetChanged () on adapter object.

create_invoice activity
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.addProduct(products)
custom Adapter
public class custom_adapter_invoice extends ArrayAdapter <invoice_product_list>
{
ArrayList<invoice_product_list> productList = new ArrayList<>();
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
this.productList =product_details
}
public void addProduct(Product products
productList.add(products);
notifyDataSetChanged();
}
......
}

No,it does not change anything. If you want the latest method of working then I would prefer RecyclerView to custom list adapter. this link is very good for recyclerview
recyclerview demo series link

Related

Can't set RecyclerView inside CardView?

I'm trying to put a RecyclerView inside a CardView and create items dynamically.
Obviously, in XML, RecyclerView is set inside CardView tag, but as you can see picture, RecyclerView item is created outside CardView.
(RecyclerView's items are the parts expressed as kg and set in the photo. And CardView is also an item of another RecyclerView.)
What's the problem?
XML
<androidx.cardview.widget.CardView
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="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="12dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
app:cardElevation="10dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/ll1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/workout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="TEST"/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/light_blue_400"/>
</LinearLayout>
<LinearLayout
android:id="#+id/ll2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#+id/ll1">
<com.google.android.material.button.MaterialButton
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="8dp"
android:layout_marginEnd="4dp"
style="#style/RoutineButtonStyle"
android:text="DELETE"
app:icon="#drawable/ic_delete"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="4dp"
android:layout_marginEnd="8dp"
style="#style/RoutineButtonStyle"
android:text="ADD"
app:icon="#drawable/ic_add"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/ll2"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Let me know if you need any other code.
Here is the Activity of your add/delete CardView:
//Item List if you want to add one or more Items
private List<MyItem> myItems = new ArrayList<>();
private Adapter smallCardAdapter;
private int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.rv);
//Creates a new Object in the Adapter.class
smallCardAdapter = new Adapter();
recyclerView.setAdapter(smallCardAdapter);
CardView cardView = findViewById(R.id.cardView);
MaterialButton delete = findViewById(R.id.delete);
MaterialButton add = findViewById(R.id.add);
//Add onClickListener
add.setOnClickListener(v -> {
try {
size = myItems.size();
//if the value is 0, a new item is created
//if you want to delete the card after 0 than you have to change the value to 0
if(size == 0){
//Creates a new Object in the MyItem.class
myItems.add(new MyItem("Set","1kg"));
}else{
MyItem myItem = myItems.get(0);
//Replace kg with "" to make a Integer
String secondString = myItem.getSecondString().replace("kg","");
Integer value = Integer.valueOf(secondString);
value++;
myItem.setSecondString(value+"kg");
myItems.set(0,myItem);
}
updateAdapter();
}catch (Exception e){
Log.w("MainActivity","Add Button OnClickListener");
e.printStackTrace();
}
});
//Delete onClickListener
delete.setOnClickListener(v->{
try {
size = myItems.size();
//If the value is 0 then canceled to avoid errors
if(size == 0){
return;
}
MyItem myItem = myItems.get(0);
//Replace kg with "" to make a Integer
String secondString = myItem.getSecondString().replace("kg","");
Integer value = Integer.valueOf(secondString);
//if the value is one or lower
if(value <= 1){
//The card will deleted after updateAdapter();
myItems.clear();
}else{
value--;
myItem.setSecondString(value+"kg");
myItems.set(0,myItem);
}
updateAdapter();
}catch (Exception e){
Log.w("MainActivity","Delete Button OnClickListener");
e.printStackTrace();
}
});
}
private void updateAdapter(){
try {
smallCardAdapter.setItems(myItems);
}catch (Exception e){
Log.w("MainActivity","updateAdapter");
e.printStackTrace();
}
}
The custom Item called MyItem:
public class MyItem {
String firstString;
String secondString;
public MyItem(String firstString,String secondString){
this.firstString = firstString;
this.secondString = secondString;
}
public String getFirstString() {
return firstString;
}
public void setFirstString(String firstString) {
this.firstString = firstString;
}
public String getSecondString() {
return secondString;
}
public void setSecondString(String secondString) {
this.secondString = secondString;
}
}
The Adapter.java creates a smallCard:
public class Adapter extends RecyclerView.Adapter<Adapter.SmallCardHolder> {
private List<MyItem> items = new ArrayList<>();
#NonNull
#Override
public SmallCardHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// I created a new smallcard for the CardView
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.smallcard, parent, false);
SmallCardHolder smallCardHolder = new SmallCardHolder(itemView);
return smallCardHolder;
}
#Override
public void onBindViewHolder(#NonNull final SmallCardHolder holder, int position) {
//get the current item of the position
MyItem myItem = items.get(position);
String firstString = myItem.getFirstString();
String secondString = myItem.getSecondString();
holder.textViewSet.setText(firstString);
holder.textViewkg.setText(secondString);
}
#Override
public int getItemCount () {
return items.size();
}
public void setItems(List <MyItem> items) {
this.items = items;
notifyDataSetChanged();
}
class SmallCardHolder extends RecyclerView.ViewHolder {
//Here are the TextView's of the smallcard (smallcard.xml)
private TextView textViewSet;
private TextView textViewkg;
public SmallCardHolder(#NonNull View itemView) {
super(itemView);
textViewSet = itemView.findViewById(R.id.set);
textViewkg = itemView.findViewById(R.id.kg);
}
}
}
Create a new layout with name called smallcard.xml for the Adapter.java:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/set"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:layout_centerVertical="true"
android:textSize="18sp"
android:layout_marginStart="5dp"
android:textColor="?attr/colorPrimary"
android:textStyle="bold"/>
<TextView
android:id="#+id/kg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:layout_toRightOf="#id/set"
android:layout_marginLeft="55dp"
android:layout_centerVertical="true"
android:textColor="?attr/colorPrimary"
android:textSize="16sp"
android:layout_marginRight="10dp"
android:maxLines="1"/>
</RelativeLayout>
</RelativeLayout>
In your XML you have to give the CardView a name. I called it cardView. Here is the code android:id="#+id/cardView"
Result:
You will find more information as comments in the code.

Multiple Intents passing listView info from one activity to another

I'm trying to pass information from my second activity to my first activity. In my second Activity contains a list view of images of provinces in Canada. Each item in the list contains 3 properties (Province Name, Capital of the Province, Image id for the actual flag of the province). When the user selects an item from the listView it should direct them to the first Activity and pass the intent information from the second Activity to the first Activity. The information that will be passed are the name of the province and the capital of the province. I feel like I'm doing it correctly and my app currently has no issue in terms of bugs or crashes but I can't seem to figure out why the information is not being passed from activity 2 to activity 1. It just passes nothing. Thanks to those all in advance that help me out!
Main Activity.Java
TextView provinceTxt, capitalTxt;
String provinceString, capitalString;
ArrayList<Province> provinces;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
provinceTxt = findViewById(R.id.txtProvince);
capitalTxt = findViewById(R.id.txtCapital);
display();
}
public void selectProvince(View view) {
showAlertDialog();
}
public void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Would You Like to Open the Second Activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, Second_Activity.class);
startActivity(intent);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
public void display(){
Intent intent = getIntent();
provinceString = intent.getStringExtra("name");
provinceTxt.setText(provinceString);
capitalString = intent.getStringExtra("capital");
capitalTxt.setText(capitalString);
}
}
Second Activity.Java
List<Province> provinces;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_);
provinces = ProvincesData.getList();
listView = findViewById(R.id.listView);
CustomAdapter adapter = new CustomAdapter(Second_Activity.this, R.layout.list_view_row, provinces);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Province province = (Province) listView.getItemAtPosition(position);
Intent intent = new Intent();
intent.putExtra("name", province.getName());
intent.putExtra("capital", province.getCapital());
finish();
}
});
}
}
Province.Java
public class Province {
String name;
String capital;
public Province(String name, String capital, int armID) {
this.name = name;
this.capital = capital;
this.armID = armID;
}
int armID;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
public int getArmID() {
return armID;
}
public void setArmID(int armID) {
this.armID = armID;
}
}
ProvincesData.Java
public static List<Province> getList() {
List<Province> provinces = new ArrayList<Province>();
Province province1 = new Province("Alberta","Edmonton", R.drawable.alberta);
provinces.add(province1);
Province province2 = new Province("British Columbia","Victoria", R.drawable.british_columbia);
provinces.add(province2);
Province province3 = new Province("Manitoba","Winnipeg", R.drawable.manitoba);
provinces.add(province3);
Province province4 = new Province("New Brunswick","Fredericton", R.drawable.new_brunswick);
provinces.add(province4);
Province province5 = new Province("Newfoundland and Labrador","St. John's", R.drawable.newfoundland_and_labrador);
provinces.add(province5);
Province province6 = new Province("Nova Scotia","Halifax", R.drawable.nova_scotia);
provinces.add(province6);
Province province7 = new Province("Ontario","Toronto", R.drawable.ontario);
provinces.add(province7);
Province province8 = new Province("Quebec","Quebec City", R.drawable.quebec);
provinces.add(province8);
Province province9 = new Province("Saskatchewan","Regina", R.drawable.saskatchewan);
provinces.add(province9);
Province province10 = new Province("Prince Edward ","Charlottetown", R.drawable.prince_edward_island);
provinces.add(province10);
return provinces;
}
}
CustomAdapter.Java
public class CustomAdapter extends ArrayAdapter {
static class ViewHolder{
TextView provinceTv;
TextView cityTv;
ImageView armID;
}
List<Province> provinces;
public CustomAdapter(#NonNull Context context, int resource, #NonNull List objects) {
super(context, resource, objects);
provinces = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_view_row , null);
holder = new ViewHolder();
holder.provinceTv = view.findViewById(R.id.txtProvinceRow);
holder.cityTv = view.findViewById(R.id.txtCapitalRow);
holder.armID = view.findViewById(R.id.imageView);
view.setTag(holder);
}
holder = (ViewHolder)view.getTag();
holder.provinceTv.setText(provinces.get(position).getName());
holder.cityTv.setText(provinces.get(position).getCapital());
holder.armID.setBackgroundResource(provinces.get(position).getArmID());
return view;
}
}
Activity_main.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:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:text="Selected Province Info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="25dp"
android:orientation="horizontal">
<TextView
android:id="#+id/txtProvinceTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Province Name"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/txtProvince"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="text"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="25dp"
android:orientation="horizontal">
<TextView
android:id="#+id/txtCapitalTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Capital City"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"/>
<TextView
android:id="#+id/txtCapital"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="text"
android:textAppearance="#style/TextAppearance.AppCompat.Large" />
</LinearLayout>
<Button
android:id="#+id/btnSelect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="30dp"
android:text="Select Province"
android:onClick="selectProvince"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"/>
</LinearLayout>
Activity_second.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:orientation="vertical"
tools:context=".Second_Activity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_view_row.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:orientation="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
tools:srcCompat="#tools:sample/avatars" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:layout_weight="2"
android:layout_marginHorizontal="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/txtProvinceRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:text="" />
<TextView
android:id="#+id/txtCapitalRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:text="" />
</LinearLayout>
</LinearLayout>
You forget to start the intent
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Province province = (Province) listView.getItemAtPosition(position);
Intent intent = new Intent(this.Second_Activity.class, MainActivity);
intent.putExtra("name", province.getName());
intent.putExtra("capital", province.getCapital());
startActivity(intent);
finish();
}
});
receive the intent
public void display(){
Bundle extras = intent.getExtras();
if(extras != null){
String provinceString = extras.getString("name");
provinceTxt.setText(provinceString);
String capitalString = extras.getString("capital");
capitalTxt.setText(capitalString);
}
}
for more details refer this
you can use Activity.startActivityForResult(Intent intent, int requestCode)to start Second Activity and use Activity.onActivityResult(int requestCode, int resultCode, Intent data) to receive data that from Second Activityin MainActivity

How to fetch data related to a clicked item in a recyclerView from room database to a new activity?

My app has a RawMaterialFragment that displays raw materials data in a recyclerView from room database.
I am trying to build a detail activity(MetrialItemView) to show up the details of an individual raw material by clicking or selecting the raw material from the recyclerView.
my problem is how to send the data from the adapter and how to receive the data in the MetrialItemView Activity and display it.
MaterialListAdapter:
public class MaterialListAdapter extends RecyclerView.Adapter<MaterialListAdapter.ViewHolder> {
private final LayoutInflater mInflater;
private FragmentRawMaterials mContext;
private List<RawMaterialsEntity> mMaterial; // Cached copy of Materials
RawMaterialsEntity mCurrent;
public MaterialListAdapter(FragmentRawMaterials context) {
mInflater = LayoutInflater.from(context.getActivity());
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.list_item, parent, false);
return new ViewHolder(itemView);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final TextView materialName;
private final TextView materialBrand;
private final TextView materialQuantity;
LinearLayout parentLayout;
private ViewHolder(View itemView) {
super(itemView);
materialName = itemView.findViewById(R.id.raw_material_name);
materialBrand = itemView.findViewById(R.id.raw_material_brand);
materialQuantity = itemView.findViewById(R.id.raw_material_quantity);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (mMaterial != null) {
mCurrent = mMaterial.get(position);
holder.materialName.setText(mCurrent.getRawMaterialName());
holder.materialBrand.setText(mCurrent.getRawMaterialBrand());
holder.materialQuantity.setText(String.valueOf(mCurrent.getRawMaterialQuantity()));
} else {
// Covers the case of data not being ready yet.
holder.materialName.setText("Name NA");
holder.materialBrand.setText("Brand NA");
holder.materialQuantity.setText("Quantity NA");
}
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
mContext.startActivity(intent);
}
});
}
public void setMaterial(List<RawMaterialsEntity> materials){
mMaterial = materials;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't return null).
#Override
public int getItemCount() {
if (mMaterial != null)
return mMaterial.size();
else return 0;
}
}
MaterialItemView:
public class MaterialItemView extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.material_item_view);
}
}
material_list_item:
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Raw Material Name:"
style="#style/OtherTextViews"/>
<TextView
android:id="#+id/material_name_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Raw Material Brand:"
style="#style/OtherTextViews"/>
<TextView
android:id="#+id/material_brand_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unit Weight:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2000"
style="#style/OtherTextViewsBody"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="gm"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unit Cost:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cost per gm/ml:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.1"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Available Quantity:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1000"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total Cost:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50000"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Name:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pandah"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Email:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pandah#panadh.com"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Phone:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+966555699517"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
</LinearLayout>
FragmentRawMaterials:
public class FragmentRawMaterials extends Fragment{
private RawMaterialViewModel mMaterialViewModel;
private static final int NEW_MATERIAL_ACTIVITY_REQUEST_CODE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_raw_materials, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
//FloatingActionButton fab to insert recipes
TextView emptyViewText = view.findViewById(R.id.empty_raw__materials_view);
FloatingActionButton fab = view.findViewById(R.id.fab_raw_materials);
fab.setOnClickListener(view1 -> {
Intent intent = new Intent(getActivity(), RawMaterialsEditor.class);
startActivityForResult(intent, NEW_MATERIAL_ACTIVITY_REQUEST_CODE);
});
RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
//Decoration to add a line divider between recyclerView items
DividerItemDecoration decoration =
new DividerItemDecoration(Objects.requireNonNull(this.getActivity()),
R.drawable.border_line);
recyclerView.addItemDecoration(decoration);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
final MaterialListAdapter adapter = new MaterialListAdapter(this);
recyclerView.setAdapter(adapter);
// Check if adapter list is empty, if so empty text view will appear.
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
if (adapter.getItemCount() == 0) {
recyclerView.setVisibility(View.GONE);
emptyViewText.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
emptyViewText.setVisibility(View.GONE);
}
}
});
mMaterialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
// Update the cached copy of the words in the adapter.
mMaterialViewModel.getAllMaterials().observe(this, adapter::setMaterial);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_MATERIAL_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
RawMaterialsEntity material = new RawMaterialsEntity(data
.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_BRAND),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_WEIGHT)),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_COST)),
Integer.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_QUANTITY)),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_EMAIL),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_PHONE),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_UOM));
mMaterialViewModel.insertMaterial(material);
mMaterialViewModel.costPerGm();
mMaterialViewModel.totalCost();
} else {
Toast.makeText(
Objects.requireNonNull(getActivity()).getApplicationContext(),
R.string.editor_insert_rm_failed,
Toast.LENGTH_LONG).show();
}
}
}
each row of dataModel() must have ID and then use putExtra() whan clicked It happens
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
intent.putExtra("ID",mCurrent.getID());
mContext.startActivity(intent);
}
});
and use getIntent() in detailActivity
int id =getIntent().getIntExtra("ID",-1);
and then get a row data in detail activity from database(viewModel)by ID and parse it

Android setVisibility does not work on some logic

Just a little introduction of what I am doing.
I am granting different functionality based on the account type a user has sign in with.
The user's account type will be retrieved via Firebase Reference from Firebase Database. If you look at this image, there's the arrow indicated. That is where the account type will be displayed but to consider the UI, I have set the visibility of the text view to be "gone". I have validated that the database reference codes are working as when I set the visibility of the text view to be visible, and then I run the app, the text view will change accordingly to be either Administrator or Local User.
The problem lies on my setVisibility 'if else' logic. It does not work accordingy. Attached are the list of scenarios I have tested and the outcomes of it.
I have tried adding the visibility to 'gone' on my pencil icon, and use VISIBILE/INVISIBLE/GONE without the View infront of it (like what many have said as their solution on several similar posts), but when I tried that, the icon is invisible for all 8 scenarios.
As such, I am not sure what else I should do to overcome this. Any help is greatly appreciated.
Update #1: Added codes as requested
class SearchViewHolder extends RecyclerView.ViewHolder {
public TextView keyword, description, acronym, relatedkeyword1,
relatedkeyword2, relatedkeyword3, tv_rules_read_more;
public ImageView iv_rules;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
//knowledge feature
keyword = itemView.findViewById(R.id.keyword);
acronym = itemView.findViewById(R.id.acronym);
tv_rules_read_more = itemView.findViewById(R.id.tv_rules_read_more);
iv_rules = itemView.findViewById(R.id.iv_rules);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>
implements SectionIndexer {
// private Context context;
private List<Knowledge> knowledge;
private ArrayList<Integer> mSectionPositions;
Activity activity;
String positionUpdated;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;
public SearchAdapter(Activity activity, List<Knowledge> knowledge, String
positionUpdated) {
//this.context = context;
this.knowledge = knowledge;
this.activity = activity;
this.positionUpdated = positionUpdated;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder holder, final int
position) {
holder.keyword.setText(knowledge.get(position).getKeyword());
holder.acronym.setText(knowledge.get(position).getAcronym());
holder.tv_rules_read_more.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(position);
}
});
if (positionUpdated != null && !positionUpdated.equals("")) {
showDialog(Integer.parseInt(positionUpdated));
positionUpdated = "";
}
}
public void showDialog(final int position) {
try {
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.dialog_layout_item_rules);
dialog.setCancelable(false);
final TextView acctype, keyword1, description1, acronym1,
relatedkeyword4, relatedkeyword5, relatedkeyword6;
//final TextView keyword1, description1, acronym1,
relatedkeyword4, relatedkeyword5, relatedkeyword6;
ImageView iv_rules, iv_close_dialog, iv_edit_dialog;
//rules feature
acctype = dialog.findViewById(R.id.tvAccType);
keyword1 = dialog.findViewById(R.id.keyword);
acronym1 = dialog.findViewById(R.id.acronym);
description1 = dialog.findViewById(R.id.description);
relatedkeyword4 = dialog.findViewById(R.id.relatedKeyword1);
relatedkeyword5 = dialog.findViewById(R.id.relatedKeyword2);
relatedkeyword6 = dialog.findViewById(R.id.relatedKeyword3);
iv_rules = dialog.findViewById(R.id.iv_rules);
iv_close_dialog = dialog.findViewById(R.id.iv_close_dialog);
iv_edit_dialog = dialog.findViewById(R.id.iv_edit_dialog);
/////////
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference =
firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile =
dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
////////
keyword1.setText(knowledge.get(position).getKeyword());
description1.setText(knowledge.get(position).getDescription());
acronym1.setText(knowledge.get(position).getAcronym());
relatedkeyword4.setText(knowledge.get(position).getRelatedkeyword1());
relatedkeyword5.setText(knowledge.get(position).getRelatedkeyword2());
relatedkeyword6.setText(knowledge.get(position).getRelatedkeyword3());
byte[] bytesImage = knowledge.get(position).getImage();
if (bytesImage != null && bytesImage.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytesImage, 0,
bytesImage.length);
iv_rules.setImageBitmap(bitmap);
iv_rules.setVisibility(View.VISIBLE);
} else {
iv_rules.setVisibility(View.GONE);
}
dialog.show();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
WindowManager.LayoutParams layoutParams = new
WindowManager.LayoutParams();
Window window = dialog.getWindow();
layoutParams.copyFrom(window.getAttributes());
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(layoutParams);
iv_close_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
}
});
iv_edit_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity,
AddNewKnowledgeActivity.class);
intent.putExtra("id",
String.valueOf(knowledge.get(position).getId()));
intent.putExtra("position", String.valueOf(position));
intent.putExtra("call_type", "update_rule");
intent.putExtra("title",
knowledge.get(position).getKeyword());
intent.putExtra("code",
knowledge.get(position).getAcronym());
intent.putExtra("description",
knowledge.get(position).getDescription());
intent.putExtra("keyword1",
knowledge.get(position).getRelatedkeyword1());
intent.putExtra("keyword2",
knowledge.get(position).getRelatedkeyword2());
intent.putExtra("keyword3",
knowledge.get(position).getRelatedkeyword3());
intent.putExtra("bytesImage",
knowledge.get(position).getImage());
dialog.cancel();
activity.startActivityForResult(intent, 101);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return knowledge.size();
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
List<String> sections = new ArrayList<>(26);
mSectionPositions = new ArrayList<>(26);
for (int i = 0, size = knowledge.size(); i < size; i++) {
String section =
String.valueOf(knowledge.get(i).getKeyword().charAt(0)).toUpperCase();
if (!sections.contains(section)) {
sections.add(section);
mSectionPositions.add(i);
}
}
return sections.toArray(new String[0]);
}
#Override
public int getPositionForSection(int sectionIndex) {
return mSectionPositions.get(sectionIndex);
}
}
Update 2: Added XML file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
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="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#f5f0f0"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iv_rules"
android:layout_width="200dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:src="#color/deeppurpleColor"
android:visibility="gone" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_edit_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_5sdp"
android:background="#android:drawable/ic_menu_edit"
android:backgroundTint="#android:color/black"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_close_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_5sdp"
android:layout_alignParentRight="true"
android:background="#android:drawable/ic_menu_close_clear_cancel"
android:backgroundTint="#android:color/black" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:id="#+id/tvAccType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Account Type"
android:visibility="gone"/>
<TextView
android:id="#+id/keyword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_vertical|start"
android:text="Baggage Management Interface Device (BMID)
Testing 123"
android:textAllCaps="true"
android:textColor="#000000"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/codeHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Code:"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="bold" />
<TextView
android:id="#+id/acronym"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="GST"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="italic" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/ruleHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Desc:"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="bold" />
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:scrollbars="vertical"
android:text="If none are set then 'GST' is set to NULL"
android:textColor="#a8000000"
android:textSize="13dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/relatedKeyword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Related Keyword:"
android:textColor="#a8000000"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="#+id/relatedKeyword1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 1,"
android:textColor="#a8000000"
android:textSize="12sp" />
<TextView
android:id="#+id/relatedKeyword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 2,"
android:textColor="#a8000000"
android:textSize="12sp" />
<TextView
android:id="#+id/relatedKeyword3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 3"
android:textColor="#a8000000"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Problem is solved by placing the if/else logic inside onDataChange method!
The logic did not work accordingly as my if/else logic were placed outside of the loop. The logic should work while Firebase is retrieving then displaying the values.
As such, instead of these:
DatabaseReference databaseReference =
firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile =
dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
//note: these are outside of the loop at first
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
It should be like this instead:
DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
//granting different functionality based on account type
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I learnt my lesson the hard way! It is very important to understand the logic you want to come out with, followed by the expected work flow!
Many thanks to those who have taken their time to guide me through!

Android : Unable to delete ListView item from menu

I am new here so please bear with my naivety. I am working on a music player that will display a menu on clicking 'dots' buttton(given in code below) in listview item. Inside the menu there will be a button to delete. The listview is getting populated by a custom adapter. Here is the code of adapter...
private class hashmapAdapter extends BaseAdapter implements Filterable {
HashMap<Integer, NowPlayingActivity.Details> NewDetails = new HashMap<>();
private hashmapAdapter(HashMap<Integer, NowPlayingActivity.Details> hashMap) {
if(NewDetails.size()==0) {
NewDetails.putAll(hashMap);
}
}
#Override
public int getCount() {
return NewDetails.size();
}
#Override
public Object getItem(int position) {
return NewDetails.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View result;
if(convertView == null) {
result = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_item,parent,false);
} else {
result = convertView;
}
((TextView)result.findViewById(R.id.Name)).setText(NewDetails.get(position).getName());
((TextView)result.findViewById(R.id.artist)).setText(NewDetails.get(position).getArtist());
((TextView)result.findViewById(R.id.duration)).setText(NewDetails.get(position).getDuration()+" || ");
dots = (Button)result.findViewById(R.id.dots);
dots.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = (TextView)result.findViewById(R.id.Name);
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View popup_view = inflater.inflate(R.layout.option_layout,null);
RelativeLayout item = (RelativeLayout) popup_view.findViewById(R.id.popup);
final float width= (getResources().getDimension(R.dimen.width_entry_in_dp));
final float height= getResources().getDimension(R.dimen.height_entry_in_dp);
final PopupWindow popupWindow = new PopupWindow(popup_view,Math.round(width),Math.round(height),true);
popupWindow.showAtLocation(item, Gravity.END, 0, 0);
popupWindow.showAsDropDown(dots);
play_next_btn = (Button)popup_view.findViewById(R.id.play_next);
add_to_playlist = (Button)popup_view.findViewById(R.id.add_to_playlist);
share = (Button)popup_view.findViewById(R.id.share);
delete = (Button)popup_view.findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<NewDetails.size();i++) {
if(NewDetails.get(i).getName().equals(name.getText().toString())) {
for(int j=0;j<hashMap.size();j++) {
if(hashMap.get(j).getName().equals(name.getText().toString())) {
if (true) {
NewDetails.remove(i);
hashMap.remove(j);
}
}
}
}
}
populate1(NewDetails);
popupWindow.dismiss();
}
});
}
});
return result;}
Now the problem is that after deleting element when i call populate1(NewDetails), it gives a null pointer exception on NewDetails.get(position).getName(). So on repopulating listview i am getting NPE error. Following is the populate1() function code...
public void populate1(HashMap<Integer,NowPlayingActivity.Details> hashMap) {
adapter = new hashmapAdapter(hashMap);
library.setAdapter(adapter);
adapter.notifyDataSetChanged();
library.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
name = (TextView)view.findViewById(R.id.Name);
String SongName = name.getText().toString();
Intent intent = new Intent(getApplicationContext(),NowPlayingActivity.class);
intent.putExtra("SongName",SongName);
setResult(555,intent);
finish();
}
});
}
I have already tried notifydatasetchanged() and listview.invalidateviews(), both didnt work. File is getting deleted but the adapter is not refreshing the list to remove element. Here is the xml layout of single_item for listview....`
`<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="wrap_content"
android:layout_height="70dp"
android:paddingRight="8dp"
android:paddingEnd="8dp"
android:background="#drawable/element_shape_list"
android:descendantFocusability="blocksDescendants">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/v1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/v11"
android:orientation="horizontal" android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="#+id/art_work"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#mipmap/ic_launcher"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"/>
<TextView
android:id="#+id/Name"
android:textSize="17sp"
android:textColor="#000"
android:textStyle="bold"
android:gravity="bottom"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginRight="30dp"
android:layout_marginEnd="30dp"
android:layout_toRightOf="#id/art_work"
android:layout_toEndOf="#+id/art_work"
android:singleLine="true"
/>
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginRight="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#+id/art_work"
android:layout_toEndOf="#id/art_work"
android:layout_below="#id/Name">
<TextView
android:id="#+id/duration"
android:textSize="12sp"
android:textColor="#000"
android:layout_width="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_height="20dp"
android:singleLine="true"
android:gravity="clip_horizontal"
android:ellipsize="end"/>
<TextView
android:id="#+id/artist"
android:textSize="12sp"
android:textColor="#000"
android:layout_toRightOf="#+id/duration"
android:layout_toEndOf="#+id/duration"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:gravity="fill_horizontal"
android:layout_height="20dp"
android:singleLine="true" />
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent">
<Button
android:id="#+id/dots"
android:layout_width="40dp"
android:textStyle="bold"
android:background="?android:attr/selectableItemBackground"
android:layout_height="70dp"
android:text="#string/vertical_ellipsis"
android:textSize="25sp" />
</FrameLayout>
</RelativeLayout>

Categories

Resources