Android setVisibility does not work on some logic - android

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!

Related

Having-clicks inside RecyclerAdapter on my Recyclerview

I was trying to make responsive clicks events inside my RecyclerAdapter. I can't understand the logic behind on it since my data is auto created by API, therefore i have some buttons in my list and I've like to have response by clicking on it.
This is my code:
My Adapter class:
public class EppViewCartAdapter extends RecyclerView.Adapter<EppViewCartAdapter.MyViewHolder> {
View itemView;
ImageView add,less;
private List<EppViewCartDetails> orderData;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView subject,category,brand,neww,newd,old,discount,count,color;
ImageView image;
public MyViewHolder(View view) {
super(view);
subject=view.findViewById(R.id.view_cart_item_subject);
category=view.findViewById(R.id.view_cart_item_category);
brand=view.findViewById(R.id.view_cart_item_brand);
neww=view.findViewById(R.id.view_cart_item_neww);
old=view.findViewById(R.id.view_cart_item_old);
discount=view.findViewById(R.id.view_cart_item_discount);
newd=view.findViewById(R.id.view_cart_item_new_depends_count);
count=view.findViewById(R.id.view_cart_item_count);
image=view.findViewById(R.id.view_cart_item_image);
add=itemView.findViewById(R.id.view_btn_add);
less=itemView.findViewById(R.id.view_btn_less);
}
}
public EppViewCartAdapter(List<EppViewCartDetails> preorderList) {
this.orderData = preorderList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_cart_card_view, parent, false);
//TODO: I was trying to make a set onlcick listener here but it has errors.
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
EppViewCartDetails data= orderData.get(position);
double amount = Double.parseDouble(data.getCount())*Double.parseDouble(data.getNeww());
DecimalFormat formatter = new DecimalFormat("#,###.00");
holder.subject.setText(data.getSubject());
holder.category.setText(data.getCategory());
holder.brand.setText(data.getBrand());
holder.neww.setText("₱ "+formatter.format(amount));
holder.newd.setText(data.getNewd());
holder.old.setText(data.getOld());
holder.old.setPaintFlags(holder.old.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.discount.setText(data.getDiscount());
holder.count.setText(data.getCount());
Picasso.with(itemView.getContext()).load("https://eppteststorage.blob.core.windows.net/images/"+data.getImage()).placeholder(R.drawable.small_logo).into(holder.image, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
Log.e("tae tae"," PAkultie");
}
#Override
public void onError() {
}
}
);
}
#Override
public int getItemCount() {
return orderData.size();
}
}
My error trying my OnclickEvent:(upon my //TODO:)
Process: eppmobile.intellismart.com.EPP, PID: 18675
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at eppmobile.intellismart.com.EPP.ViewCart.EppViewCartAdapter.onCreateViewHolder(EppViewCartAdapter.java:58)
at eppmobile.intellismart.com.EPP.ViewCart.EppViewCartAdapter.onCreateViewHolder(EppViewCartAdapter.java:22)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6794)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5975)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
My Activity class:
public class EppViewCart extends Fragment {
View inflatedView = null;
EppViewCartDetails items;
private List<EppViewCartDetails> dataitems = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
inflatedView = inflater.inflate(R.layout.fragment_epp_view_cart, container, false);
retriveSQLITE();
return inflatedView;
}
private void retriveSQLITE() {
SqLiteDB sql = new SqLiteDB(getContext());
SQLiteDatabase db = sql.getWritableDatabase();
Cursor c = sql.retrieveAddToCart(db);
ArrayList<AddToCartModel> get = new ArrayList<>();
while (c.moveToNext()) {
final AddToCartModel details = new AddToCartModel();
details.setID(c.getString(c.getColumnIndexOrThrow("ID")));
details.setDateTime(c.getString(c.getColumnIndexOrThrow("DateTime")));
details.setID_ProductMasterListV(c.getString(c.getColumnIndexOrThrow("ID_ProductMasterListV")));
details.setImageFile(c.getString(c.getColumnIndexOrThrow("ImageFile")));
details.setOrdered(c.getString(c.getColumnIndexOrThrow("Ordered")));
get.add(details);
APICaller service = EppMainFragmentPropertyClient.getRetrofit().create(APICaller.class);
View_Response gets = new View_Response("1", details.getID(), details.getID_ProductMasterListV());
Call<List<View_Data_Properties>> call = service.getView(gets);
call.enqueue(new Callback<List<View_Data_Properties>>() {
#Override
public void onResponse(Call<List<View_Data_Properties>> call, Response<List<View_Data_Properties>> response) {
//Discount
String q = String.format("%.2f", Double.parseDouble(response.body().get(0).getLess()));
long l = Math.round(Double.parseDouble(q));
String percent = l + "%";
double amount = Double.parseDouble(response.body().get(0).getNewPrice());
DecimalFormat formatter = new DecimalFormat("#,###.00");
double amount2 = Double.parseDouble(response.body().get(0).getSRP());
DecimalFormat formatter2 = new DecimalFormat("#,###.00");
items = new EppViewCartDetails(
response.body().get(0).getID(),
response.body().get(0).getName(),
response.body().get(0).getCategory(),
response.body().get(0).getProductsBrand(),
response.body().get(0).getNewPrice(),
"₱ " + formatter.format(amount),
"₱ " + formatter2.format(amount2),
"-" + percent,
details.getOrdered(), response.body().get(0).getHexValue(),
response.body().get(0).getImageFile());
dataitems.add(items);
prepareItems();
}
#Override
public void onFailure(Call<List<View_Data_Properties>> call, Throwable t) {
}
});
}
}
private void prepareItems() {
//Items
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
RecyclerView recyclerView = inflatedView.findViewById(R.id.view_cart_recycler);
recyclerView.setLayoutManager(layoutManager);
EppViewCartAdapter mAdapter = new EppViewCartAdapter(dataitems);
recyclerView.setAdapter(mAdapter);
}
}
My CardView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_marginTop="8dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#drawable/radius_all_two"
android:layout_width="match_parent"
android:layout_height="190dp">
<ImageView
android:layout_width="110dp"
android:layout_height="120dp"
android:src="#drawable/bestseller"
android:id="#+id/view_cart_item_image"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JBL- Grip 100"
android:id="#+id/view_cart_item_subject"
android:textColor="#000"
android:textSize="14dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="25dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_marginTop="15dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Category"
android:textColor="#089bcc"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="48dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Headphones"
android:id="#+id/view_cart_item_category"
android:textSize="11dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="48dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Brand"
android:textColor="#089bcc"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="65dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JBL"
android:id="#+id/view_cart_item_brand"
android:textSize="11dp"
android:layout_marginLeft="180dp"
android:layout_marginTop="65dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 1,290.00"
android:id="#+id/view_cart_item_neww"
android:textColor="#00c1ab"
android:textSize="15dp"
android:textStyle="bold"
android:layout_marginLeft="140dp"
android:layout_marginTop="83dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 2,580.00"
android:textSize="11dp"
android:id="#+id/view_cart_item_old"
android:layout_marginLeft="140dp"
android:layout_marginTop="106dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="- 50%"
android:textSize="11dp"
android:id="#+id/view_cart_item_discount"
android:layout_marginLeft="210dp"
android:textColor="#ba0101"
android:layout_marginTop="106dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 1,290.00"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:id="#+id/view_cart_item_new_depends_count"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="x"
android:textSize="12dp"
android:layout_marginLeft="240dp"
android:textColor="#000"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="#drawable/left_arrow"
android:text="x"
android:id="#+id/view_cart_item_increment"
android:textSize="12dp"
android:layout_marginLeft="250dp"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="#drawable/right_arrow"
android:text="x"
android:id="#+id/view_cart_item_decrement"
android:textSize="12dp"
android:layout_marginLeft="304dp"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="31dp"
android:layout_height="16dp"
android:textSize="11dp"
android:textAlignment="center"
android:text="100"
android:id="#+id/view_cart_item_count"
android:layout_marginLeft="270dp"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color"
android:textSize="11dp"
android:textColor="#089bcc"
android:layout_marginLeft="140dp"
android:layout_marginTop="147dp"/>
<ImageView
android:layout_width="34dp"
android:layout_height="17dp"
android:textSize="12dp"
android:id="#+id/view_cart_variant"
android:background="#color/colorPrimaryDark"
android:layout_marginLeft="175dp"
android:layout_marginTop="145dp"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
My Cart_view :
enter image description here
(if you see the "<" and ">" sign, I was trying to add responsive there but it is running in RecyclerView with my adapter so that I didn't know if where could I put my onclick-event.)
My View in recyclerview(I set into comment my //TODO:)
(It is running but no fuction on add and subtract.)
enter image description here
Also, I've try this to (holder.add.setOn...)
enter image description here
And this:(MyViewHolder)
enter image description here
This is null pointer exception you need to understand.
you should replace itemView.findViewById(R.id.view_btn_add) with view.findViewById(R.id.view_btn_add)
because the adapter layout name is view not itemview
just look your code
public MyViewHolder(View view) {
super(view);
}
and you need add click listener either in MyViewHolder() or in onBindViewHolder()
move this code
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});
I found the answer, in my other view cart data, there are the same ID in my xml so that ive just rename my buttons in my xml and inherit it on my class.
My viewCart:
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="#drawable/left_arrow"
android:text="x"
android:id="#+id/view_cart_item_increment1"
android:textSize="12dp"
android:layout_marginLeft="250dp"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="#drawable/right_arrow"
android:text="x"
android:id="#+id/view_cart_item_decrement1"
android:textSize="12dp"
android:layout_marginLeft="304dp"
android:layout_marginTop="123dp"/>
My Adapter:
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_cart_card_view, parent, false);
add=itemView.findViewById(R.id.view_cart_item_increment1);
less=itemView.findViewById(R.id.view_cart_item_decrement1);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
EppViewCartDetails data= orderData.get(position);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});
}
The crash is occurs because you are setting click listener on null add view.
First of check your layout file for the all defined IDs in MyViewHolder class. i can't find view_btn_add id in your layout file. So assign it with appropriate view.
And then in your onCreateViewHolder method, you are setting up onClick listener on add view before initialising it.
So move your add.setOnClickListener(...) inside MyViewHolder class after defining all views. So your crash will gone.

Firebase Children Count to listview

Good Day,
I'm Trying to count the number of children based on votes.
This is my Firebase structure.
Candidate Table
and
Votes table
I successfully recovered the candidates from candidates table to listview, but I can't recover the number of votes they got on the votes table.
This is my xml for the listview
<?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">
<TextView
android:id="#+id/count_ssc_president_last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="40sp"
android:textColor="#color/colorBlack"/>
<TextView
android:id="#+id/count_ssc_president_first_middle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20sp"/>
<TextView
android:id="#+id/count_ssc_president_partylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/count_ssc_president_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TextView"
android:textSize="20sp"
android:textColor="#color/colorBlack"/>
</LinearLayout>
This is my xml for the Main java class
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".Voter_SSC_President">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="14dp"
android:text="#string/choose_ssc_president"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2" />
<ListView
android:id="#+id/listCountSSCPresident"
android:layout_width="309dp"
android:layout_height="338dp"
android:layout_marginBottom="32dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="34dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="277dp"
android:layout_height="111dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/textView4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_ssc_logo" />
</android.support.constraint.ConstraintLayout>
This is my adapter
private Activity context;
private List<SSC_Presidents> CountSSC_PresidentsList;
DatabaseReference userReference;
long num;
private LayoutInflater inflater;
public CountSSCPresLists(Activity context, List<SSC_Presidents> CountSSC_PresidentsList )
{
super(context, R.layout.listview_count_ssc_president, CountSSC_PresidentsList);
this.context = context;
this.CountSSC_PresidentsList = CountSSC_PresidentsList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.listview_count_ssc_president, null, false);
TextView textViewLast_name = (TextView) listViewItem.findViewById(R.id.count_ssc_president_last_name);
TextView textViewFirst_middle_name = (TextView) listViewItem.findViewById(R.id.count_ssc_president_first_middle);
TextView textViewPartylist = (TextView) listViewItem.findViewById(R.id.count_ssc_president_partylist);
TextView textViewCount = (TextView) listViewItem.findViewById(R.id.count_ssc_president_count);
SSC_Presidents sscPresidents = CountSSC_PresidentsList.get(position);
/*
userReference = FirebaseDatabase.getInstance().getReference("vote");
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
textViewCount.setText((int) num);*/
textViewLast_name.setText(sscPresidents.getLast_name());
textViewFirst_middle_name.setText(sscPresidents.getFirst_name()+", "+sscPresidents.getMiddle_name());
textViewPartylist.setText(sscPresidents.getPartylist_id());
return listViewItem;
The block-comment is my try to generate the vote number based on the candidate-id
This is my main java class
String stud_no;
DatabaseReference databaseReferenceCountSSCPres;
ListView listViewCountSSCPresident;
List<SSC_Presidents> sscCountPresList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__count__ssc__president);
databaseReferenceCountSSCPres = FirebaseDatabase.getInstance().getReference("candidate");
stud_no = LoginScreen.TBPstud_no1();
listViewCountSSCPresident = findViewById(R.id.listCountSSCPresident);
sscCountPresList = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
Query CountSSCPresident = databaseReferenceCountSSCPres.orderByChild("council_id_position_id_school_year").equalTo("SSC_PRES_201819");
CountSSCPresident.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
sscCountPresList.clear();
for (DataSnapshot CountSSCPresSnapshot : dataSnapshot.getChildren())
{
SSC_Presidents CountSSCPres = CountSSCPresSnapshot.getValue(SSC_Presidents.class);
sscCountPresList.add(CountSSCPres);
}
CountSSCPresLists adapter = new CountSSCPresLists(Admin_Count_SSC_President.this, sscCountPresList);
listViewCountSSCPresident.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is the result
Result
I want to put the count in the TextView in the Result.
Thank you.
PS. When I remove the block comment on the adapter the screen for the result crashes.
EDIT:
The suggestion worked but only on the last candidate.
I also used query now.
userReference = FirebaseDatabase.getInstance().getReference("vote");
Query CountSSCPresident = userReference.orderByChild("candidate_id").equalTo(sscPresidents.getCandidate_id());
CountSSCPresident.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
textViewCount.setText(String.valueOf((int)num));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The result
textViewCount.setText((int) num);
You need to cast num to a string. Try this:
textViewCount.setText(String.valueOf((int)num));
EDIT: Also place it inside the listener:
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
textViewCount.setText(String.valueOf((int)num));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Display corresponding details of user when selected from list

I have developed a screen where a no. of people from the database are displayed in a list view. I want to display the profile page of the selected person. So my question is how to bind each detail of the selected person like name, contact, etc. to the profile page which I have created? Will I have to call the getById API in the onItemClickListener?
Here's the edited code:-
public class Test extends AppCompatActivity {
List<Genie> genieList;
GenieAdapter genieAdapter;
TextView responseView;
ProgressBar progressBar;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
responseView = (TextView) findViewById(R.id.responseView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
button = (Button) findViewById(R.id.test);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Test.this, "Blahblah", Toast.LENGTH_LONG).show();
new RetrieveFeedTask().execute();
}
});
}
class RetrieveFeedTask extends AsyncTask<Void, Void, List<Genie>> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected List<Genie> doInBackground(Void... urls) {
GenieService genieService = new GenieService();
return genieService.getAll();
}
protected void onPostExecute(List<Genie> genies) {
if (genies == null) {
new ArrayList<Genie>(); // "THERE WAS AN ERROR"
} else {
progressBar.setVisibility(View.GONE);
Log.i("INFO", genies.get(0).name);
List<String> rows = genies.stream().map(genie -> getRow(genie)).collect(Collectors.toList());
genieAdapter=new GenieAdapter(getApplicationContext(),R.layout.genie_list, genies);
ListView list=(ListView)findViewById(R.id.listViewMain);
list.setAdapter(genieAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(Test.this, "" + position, Toast.LENGTH_SHORT).show();
// if (position == 1) {
// startActivity(new Intent(Test.this, viewGenie1.class));
// }
}
});
list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Test.this, viewGenie1.class);
intent.putExtra("name", "%s");
intent.putExtra("add", "%s");
intent.putExtra("phn", "%s");
intent.putExtra("sal", "%s");
intent.putExtra("lea", "%s");
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
private String getRow(Genie g) {
return String.format("%s, %s, %s, %s, %s", g.name, g.salary, g.contact, g.paid_leaves, g.address);
}
}
}
Here's the viewGenie1.class:-
public class viewGenie1 extends AppCompatActivity implements View.OnClickListener {
TextView name;
EditText address, contact, salary, leaves;
Button attendance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_genie1);
name = (TextView) findViewById(R.id.txName);
address = (EditText) findViewById(R.id.txAddress);
contact = (EditText) findViewById(R.id.txContact);
salary = (EditText) findViewById(R.id.txSalary);
leaves = (EditText) findViewById(R.id.txLeaves);
Button update=(Button)findViewById(R.id.btUpdate);
update.setOnClickListener(this);
Button delete=(Button)findViewById(R.id.delete);
delete.setOnClickListener(this);
Button attendance = (Button) findViewById(R.id.attendance);
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAtt();
}
});
String value = "";
if (getIntent().hasExtra("name")) {
String name = getIntent().getExtras().getString("name");
String add = getIntent().getExtras().getString("add");
String phn = getIntent().getExtras().getString("phn");
String sal = getIntent().getExtras().getString("sal");
String lea = getIntent().getExtras().getString("lea");
}
name.setText(value);
address.setText(value);
contact.setText(value);
salary.setText(value);
leaves.setText(value);
}
#Override
public void onClick(View view) {
final AlertDialog.Builder builder=new AlertDialog.Builder(viewGenie1.this);
builder.setMessage("Are you sure you want to delete records?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
new deleteTask().execute();
Toast.makeText(viewGenie1.this, "Genie deleted..!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(viewGenie1.this, navDrawer.class));
// GenieService genieService=new GenieService();
// genieService.delete(2);
// Log.d("Information", String.valueOf(genieService.delete(2)));
// Log.i("INFO", genies.get(0).name);
// startActivity(new Intent(viewGenie1.this,Test.class));
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
private class deleteTask extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
GenieService genieService = new GenieService();
return genieService.delete(6);
}
}
public void showAtt() {
Intent intent = new Intent(this, viewAbsentee.class);
startActivity(intent);
}
}
Here's the xml file of the profile page I have created with hard coded values but want to display the actual values from the local mysql database using an API call:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bcak"
tools:context="com.codionics.geniem.AddGenie"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="313dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#drawable/gradientbackground"
android:orientation="vertical">
<ImageView
android:layout_width="117dp"
android:layout_height="117dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:src="#drawable/genie" />
<TextView
android:id="#+id/txName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Abc"
android:textColor="#ffffff"
android:textSize="21sp"
android:textStyle="bold" />
</LinearLayout>
<android.support.v7.widget.CardView
android:layout_width="300dp"
android:layout_height="115dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="175dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:textColor="#f000"
android:textStyle="bold"
android:textSize="20sp" />
<EditText
android:id="#+id/txContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="123456789"
android:textColor="#3F51B5"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#f000"
android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:id="#+id/txAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Pune"
android:textColor="#3F51B5"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<LinearLayout
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="42dp"
android:paddingLeft="25dp">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="center"
android:src="#drawable/ic_attach_money_black_24dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="20dp"
android:text="Paid leaves : "
android:textColor="#303F9F"
android:textSize="27dp"
android:textStyle="bold" />
<EditText
android:id="#+id/txLeaves"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:layout_weight="1"
android:text=" 5" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="42dp"
android:paddingLeft="25dp">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="center"
android:src="#drawable/ic_money" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="20dp"
android:text="Salary : "
android:textColor="#303F9F"
android:textSize="27dp"
android:textStyle="bold" />
<EditText
android:id="#+id/txSalary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:text=" 5000"
android:textColor="#123" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/btUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginTop="30dp"
android:background="#drawable/buttonstylegradient"
android:text="Update Genie"
android:textColor="#fff" />
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="80dp"
android:layout_marginTop="-50dp"
android:background="#drawable/buttonstylegradient"
android:text="Delete Genie"
android:textColor="#fff" />
<Button
android:id="#+id/attendance"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/buttonstylegradient"
android:textColor="#fff"
android:text="Attendance" />
</LinearLayout>
I want to display the details in the a profile page like this:-
profile page
Please pass the value in Intent using putExtra()
Intent intent = new Intent(Test.this, viewGenie1.class);
intent.putExtra("key","Value"); //Key must be unique and value should be the value which you want to pass to viewGenie1 class.
startActivity(intent);
In viewGenie1 class you can get the value like this
String value="";
if(getIntent().hasExtra("key")) {
value = getIntent().getExtras().getString("key");
}
Please replace
String value = "";
if (getIntent().hasExtra("name")) {
String name = getIntent().getExtras().getString("name");
String add = getIntent().getExtras().getString("add");
String phn = getIntent().getExtras().getString("phn");
String sal = getIntent().getExtras().getString("sal");
String lea = getIntent().getExtras().getString("lea");
}
name.setText(value);
address.setText(value);
contact.setText(value);
salary.setText(value);
leaves.setText(value);
To
String mName = "",mAdd="",mPhn="",mSal="",mLea="";
if (getIntent().hasExtra("name")) {
mName = getIntent().getExtras().getString("name");
mAdd = getIntent().getExtras().getString("add");
mPhn = getIntent().getExtras().getString("phn");
mSal = getIntent().getExtras().getString("sal");
mLea = getIntent().getExtras().getString("lea");
}
name.setText(mName);
address.setText(mAdd);
contact.setText(mPhn);
salary.setText(mSal);
leaves.setText(mLea);

AVLoadingIndicatorView Library not visible in app

added the library for showing loading effects but it is not visible or any effect is not seen. Although no error occurs but there is no effect seen when the network call begins. The show method doesnot have any effect. Currently im using using android version 4.1.2.
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10">
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="50dp">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="#+id/signin_back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_gravity="center"
android:background="#drawable/ic_arrow_back_black_24dp"></ImageView>
</FrameLayout>
<TextView
android:id="#+id/txt_signIn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:background="#color/colorPrimary"
android:gravity="center"
android:padding="12dp"
android:text="#string/sign_in"
android:textColor="#color/white"
android:textSize="18dp"></TextView>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Sign in to TruePay"
android:textColor="#color/black"
android:textSize="20dp"
android:textStyle="bold"></TextView>
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="50dp">
<EditText
android:id="#+id/signin_email_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
android:hint="Username"
android:inputType="textEmailAddress"></EditText>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_password"
android:layout_width="match_parent"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content">
<EditText
android:id="#+id/signin_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:hint="#string/signin_password"
android:inputType="textPassword"></EditText>
</android.support.design.widget.TextInputLayout>
<TextView
android:id="#+id/forgot_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:clickable="true"
android:gravity="center"
android:padding="10dp"
android:text="#string/forgot_password"
android:textColor="#color/black"
android:textSize="18dp"
android:textStyle="bold"></TextView>
<TextView
android:id="#+id/use_device_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:gravity="center"
android:padding="10dp"
android:text="#string/device_code"
android:textColor="#color/black"
android:textSize="18dp"
android:textStyle="bold"></TextView>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<com.wang.avi.AVLoadingIndicatorView
android:id="#+id/avi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
app:indicatorName="BallPulseIndicator" />
</RelativeLayout>
</LinearLayout>
java code
public class SignIn extends BaseSupportFragment {
private View view;
private ImageView backPage;
private TextView signInBtn;
private TextView forgotPassword;
private TextView deviiceCodes;
TextInputLayout emailLayout,passwordLayout;
EditText email,password;
private static SessionManagement sessionManagement;
AVLoadingIndicatorView avi;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.sign_in_fragment, container, false);
initiateUI();
setListener();
return view;
}
public void getTokenFromServer()
{
WeakHashMap<String, String> param = new WeakHashMap<>();
param.put("username",email.getText().toString());
param.put("password",password.getText().toString());
Log.e("param...", String.valueOf(param));
RetrofitInterface apiService = RetrofitClient.getClient().create(RetrofitInterface.class);
Observable<TokenModel> call = apiService.postFishDetails(param)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
call.subscribe(new Observer<TokenModel>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
//handle error
Log.e("access",e.toString());
try {
if (e instanceof HttpException) {
if (((HttpException) e).code() == 401) {
// GlobalBus.getBus().post(new TokenExpirationNotification("Token Expired"));
}
}
if (e instanceof IOException) {
}
} catch (Exception e1) {
}
}
#Override
public void onNext(TokenModel response)
{
Constant.ACCESS_TOKEN = "Bearer" + response.getAccessToken();
avi.hide();
Intent intent = new Intent(getActivity(), DrawerAct.class);
getActivity().startActivity(intent);
getActivity().finish();
}
});
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private void setListener() {
backPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
}
});
signInBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(TextUtils.isEmpty(email.getText().toString()))
{
emailLayout.setError("Enter Username");
requestFocus(email);
}
else if(TextUtils.isEmpty(password.getText().toString()))
{
passwordLayout.setError("Enter Password");
requestFocus(password);
}
else
{
avi.show();
getTokenFromServer();
}
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replaceFragment(R.id.frame_layout, new ForgotPassword());
}
});
deviiceCodes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replaceFragment(R.id.frame_layout, new DeviceCode());
}
});
}
private void initiateUI()
{
backPage = (ImageView) view.findViewById(R.id.signin_back_button);
signInBtn = (TextView) view.findViewById(R.id.txt_signIn);
forgotPassword = (TextView) view.findViewById(R.id.forgot_password);
deviiceCodes = (TextView) view.findViewById(R.id.use_device_code);
emailLayout=(TextInputLayout)view.findViewById(R.id.input_layout_email);
passwordLayout=(TextInputLayout)view.findViewById(R.id.input_layout_password);
email=(EditText)view.findViewById(R.id.signin_email_address);
password=(EditText)view.findViewById(R.id.signin_password);
avi=(AVLoadingIndicatorView)view.findViewById(R.id.avi);
}
}
Resolved the issue. Forgot to mention the indiacator color which is white by default so the loader was actually working but wasnt visible;
XML code
<com.wang.avi.AVLoadingIndicatorView
android:id="#+id/avi"
style="#style/AVLoadingIndicatorView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"
app:indicatorColor="#color/colorPrimaryDark"
app:indicatorName="LineSpinFadeLoaderIndicator" />
Your parent layout is LinearLayout, try wrapping your main layout with a RelativeLayout and put the AVLoadingIndicatorView outside the LinearLayout
Just add
app:indicatorColor="#color/grovery_blue" - set your color here
that's all. Enjoy your coding...

Dynamically inserting list items to listview in 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

Categories

Resources