Duplicate values in listview in android - java

Am fetch my database values to custom ListView but whenever go to my ExistingPatient activity class from my MainActivity it creates duplicate values of my data in Listview.
My MainActivity contains only one button and in that button, I have used intent to go to ExistingPatient activity.
list_adapter.java
package com.example.voiceprescription;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class list_adapter extends ArrayAdapter<Patientinfo> {
private Context context;
ArrayList<Patientinfo> info;
public list_adapter(Context context, ArrayList<Patientinfo> info) {
super(context,R.layout.cutomlist,info);
this.context = context;
this.info = info;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cutomlist, parent, false);
TextView tvname = convertView.findViewById(R.id.tv_Cname);
TextView tvphone = convertView.findViewById(R.id.tv_Cphone);
tvname.setText(info.get(position).getName());
tvphone.setText(info.get(position).getPhone());
return convertView;
}
}
Exsistinpatient.java
package com.example.voiceprescription;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Exsistinpatient extends AppCompatActivity {
ListView list;
DatabaseReference reff;
FirebaseDatabase database;
list_adapter adapter;
Patientinfo patientinfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exsistinpatient);
Intent intent=new Intent();
list=findViewById(R.id.list);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(Exsistinpatient.this,Editinfo.class);
intent.putExtra("index",position);
startActivityForResult(intent,0);
}
});
patientinfo=new Patientinfo();
database=FirebaseDatabase.getInstance();
reff=database.getReference("Patients");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren()){
patientinfo=data.getValue(Patientinfo.class);
publicarray.info.add(patientinfo);
}
adapter=new list_adapter(Exsistinpatient.this,publicarray.info);
list.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0){
adapter.notifyDataSetChanged();
}
}
}

Try to clear list on every start, its help my when I use RecyclerView, I think here same problem

Related

Recycler view does not show up

I am having problem with my recyclerview I builed an app in android studio which suppose to create contacts and watch their cards using cardview and recyclerview the issue is that the list of contacts is not shown instead I am seeing a white screen
so here is my code:
import android.net.sip.SipSession;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
/*Connect contact list to
*
* */
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<Contact> contacts;
public ContactAdapter(List<Contact> contacts) {
this.contacts = contacts;
}
interface ContactsListener{
void onContactClicked(int position,View view);
}
ContactsListener listener;
public void setListener(ContactsListener listener){
this.listener=listener;
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
ImageView contactpicture;
TextView contactname;
TextView contactphone;
TextView contactemail;
public ContactViewHolder(View itemview) {
super(itemview);
contactpicture = itemview.findViewById(R.id.card_image);
contactphone = itemview.findViewById(R.id.contact_email);
contactphone = itemview.findViewById(R.id.contact_phone);
contactname = itemview.findViewById(R.id.contact_name);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null)
listener.onContactClicked(getAdapterPosition(), view);
}
});
}
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_layout,parent,false);
ContactViewHolder holder=new ContactViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder,int position){
Contact contact=contacts.get(position);
holder.contactpicture.setImageBitmap(contact.getPhoto());
holder.contactname.setText(contact.getName());
holder.contactphone.setText(contact.getPhone());
holder.contactemail.setText(contact.getEmail());
}
#Override
public int getItemCount(){
return contacts.size();
}
}
package com.example.b_safe;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/*Define the list of contacts*/
public class ContactsList extends Activity {
#Override
protected void onCreate(#Nullable Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.show_contacts_activity);//לבדוק שזה מתקיים
RecyclerView recyclerview=findViewById(R.id.contacts_list);
recyclerview.setHasFixedSize(true);
recyclerview.setLayoutManager(new LinearLayoutManager( this));//צריך להוסיף this
ContactManager manager=ContactManager.getInstance(this);
ContactAdapter adapter=new ContactAdapter(manager.getContacts());
recyclerview.setAdapter(adapter);
adapter.setListener(new ContactAdapter.ContactsListener() {
#Override
public void onContactClicked(int position, View view) {
}
});
}
}
package com.example.b_safe;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
/*Adds new member to the contacts list
*
*
* */
public class AddContactActivity extends AppCompatActivity{
Bitmap bitmap;
EditText nameEt,phone_numberEt,emailEt;
ImageView img;
final int CAMERA_REQUEST=1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contact_activity);
nameEt=findViewById(R.id.name_input);
phone_numberEt=findViewById(R.id.phone_input);
emailEt=findViewById(R.id.email_input);
img=findViewById(R.id.photo_result);
Button takepicture=findViewById(R.id.take_pic);
takepicture.setOnClickListener(new View.OnClickListener() {//Activation
#Override
public void onClick(View v) {
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera,CAMERA_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA_REQUEST&&resultCode==RESULT_OK){ //checks if results where properly
bitmap=(Bitmap)data.getExtras().get("data");
img.setImageBitmap(bitmap);//saving as contact's photo
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {//Load menu type
getMenuInflater().inflate(R.menu.contact_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {//fulfill actions
switch(item.getItemId()){
case R.id.action_save:
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Please confirm")
.setMessage("Would you like to save the following contact?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Contact contact=new Contact(nameEt.getText().toString(),phone_numberEt.getText().toString(),emailEt.getText().toString(),bitmap);
ContactManager manager=ContactManager.getInstance(AddContactActivity.this);
manager.addContact(contact);//Manager saved data
//Data zeroing
nameEt.setText("");
phone_numberEt.setText("");
emailEt.setText("");
img.setImageBitmap(null);
}})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AddContactActivity.this,"The conatct saved",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AddContactActivity.this,"The conatct saved",Toast.LENGTH_SHORT).show();
}
}).show();
break;
case R.id.action_back:
finish();
}
return super.onOptionsItemSelected(item);//Loads activity
}
}
AdapterActivity is the subclass adapter AddContactActivity creates new contacts and the problem is with the ContactsList activity which holds the list and does not show up

Deleting item from listview behaving strange

I have a listview that extends base adapter. There is a delete button on every list item. When the delete button is clicked then the list item should be deleted. But when I try to do so listview behaves strangely. The delete button is causing the main problem. Sometimes the list is becoming double and sometimes app is crashing. I am trying to add a delete button to the item of the listview. When someone clicks on the button then the list item will be deleted and it will delete the item also from firebase.
I am trying to achieve this.
Sorry for my bad English. Advance thanks for your help.
package com.owoshopkeeperpanel.adapters;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.owoshopkeeperpanel.Interface.ItemClickListener;
import com.owoshopkeeperpanel.Model.Cart;
import com.owoshopkeeperpanel.Prevalent.Prevalent;
import com.owoshopkeeperpanel.R;
import java.util.ArrayList;
public class CartListAdapter extends BaseAdapter {
private Context mCtx;
private ArrayList<Cart> cartList;
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
public CartListAdapter(Context mCtx, ArrayList<Cart> cartList) {
this.mCtx = mCtx;
this.cartList = cartList;
}
#Override
public int getCount() {
return cartList.size();
}
#Override
public Object getItem(int position) {
return cartList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Cart cart = cartList.get(position);
if(convertView==null) {
LayoutInflater layoutInflater = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.cart_items_sample, null);
}
ImageView delete = convertView.findViewById(R.id.cart_item_delete);
ImageView cart_product_image = convertView.findViewById(R.id.cart_product_image);
TextView cart_product_name = convertView.findViewById(R.id.cart_product_name);
TextView cart_product_quantity = convertView.findViewById(R.id.cart_product_quantity);
TextView cart_product_price = convertView.findViewById(R.id.cart_product_price);
ElegantNumberButton cart_item_change_button = convertView.findViewById(R.id.cart_item_change_btn);
Glide.with(mCtx).load(cart.getProduct_image()).into(cart_product_image);
cart_product_name.setText(cart.getProduct_name());
cart_product_quantity.setText(cart.getProduct_price()+" × "+cart.getNeeded_quantity());
double product_total_price = Double.parseDouble(cart.getProduct_price()) * Double.parseDouble(cart.getNeeded_quantity());
cart_product_price.setText("৳ "+String.valueOf(product_total_price));
cart_item_change_button.setNumber(cart.getNeeded_quantity());
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mCtx);
alertDialogBuilder.setMessage("Are you sure you want to remove this item from cart ?");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
cartListRef.child(Prevalent.currentOnlineUser.getPhone())
.child(String.valueOf(cart.getProduct_id()))
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(mCtx, String.valueOf(cartList.size()), Toast.LENGTH_LONG).show();
cartList.remove(cart);
notifyDataSetChanged();
}
}
});
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
return convertView;
}
}

Error to set itemclicklistener in Recyclerview

I'm new to stackoverflow, please forgive me if I did anything wrong or broke any rules and regulations. But I hope someone can help me with this problem.I'm having this problem where I have an error to do an itemclicklistener in recyclerview. Here is the code
My Adapter
package com.fyp.eventlocater;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<Event> events;
private RecyclerViewClickItemInterface recyclerViewClickItemInterface;
public MyAdapter( Context c, ArrayList<Event> e, RecyclerViewClickItemInterface recyclerViewClickItemInterface)
{
context = c;
events = e;
this.recyclerViewClickItemInterface = recyclerViewClickItemInterface;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.card_view, parent, false));
// View v = LayoutInflater.from(context).inflate(R.layout.card_view, parent, false);
// MyViewHolder mvh = new MyViewHolder(v, (OnItemClickListener) mListener);
// return mvh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.eventTitle.setText(events.get(position).getEventTitle());
holder.eventTime.setText(events.get(position).getEventTime());
holder.eventDesc.setText(events.get(position).getEventDesc());
holder.eventLocation.setText(events.get(position).getEventLocation());
}
#Override
public int getItemCount() {
return events.size();
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView eventTitle, eventTime, eventDesc, eventLocation;
public MyViewHolder(View itemView) {
super(itemView);
eventTitle = itemView.findViewById(R.id.eventTitle);
eventTime = itemView.findViewById(R.id.eventTime);
eventDesc = itemView.findViewById(R.id.eventDesc);
eventLocation = itemView.findViewById(R.id.eventLocation);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerViewClickItemInterface.onItemClick(getAdapterPosition());
}
});
}
}
}
This is my Interface
package com.fyp.eventlocater;
public interface RecyclerViewClickItemInterface {
void onItemClick(int position);
}
This is my activity
package com.fyp.eventlocater;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class CominSoonActivity extends AppCompatActivity implements RecyclerViewClickItemInterface {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Event> list;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comin_soon);
recyclerView = findViewById(R.id.myRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<Event>();
reference = FirebaseDatabase.getInstance().getReference().child("EventDisplay");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Event e = dataSnapshot1.getValue(Event.class);
list.add(e);
}
adapter = new MyAdapter(CominSoonActivity.this, list, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CominSoonActivity.this, "Opps.... Something went wrong", Toast.LENGTH_SHORT).show();
}
});
//add back button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
//taking the user back to the previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent homeActivity = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(homeActivity);
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(int position) {
Uri uri = Uri.parse("http://wwww.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
This is my error output
I'm a student and new to android studio. I don't know what this means
This is another error. I hope it helps.
It says this
So it seems that you are initializing a new adapter every time the data changes. You can change it to be:
public class CominSoonActivity extends AppCompatActivity implements RecyclerViewClickItemInterface {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Event> list;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comin_soon);
recyclerView = findViewById(R.id.myRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<Event>();
adapter = new MyAdapter(CominSoonActivity.this, list, this);
recyclerView.setAdapter(adapter);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Event e = dataSnapshot1.getValue(Event.class);
list.add(e); // This will add it to the adapter
adapter.notifyDataSetChanged();
}
}
// the rest of the class
This way when you reference this in the adapter you get CominSoonActivity rather than ValueEventListener.
create adapter instance like below in your activity class:
adapter = new MyAdapter(CominSoonActivity.this, list, CominSoonActivity.this);
your activity class looks like:
package com.fyp.eventlocater;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class CominSoonActivity extends AppCompatActivity implements RecyclerViewClickItemInterface {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Event> list;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comin_soon);
recyclerView = findViewById(R.id.myRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<Event>();
reference = FirebaseDatabase.getInstance().getReference().child("EventDisplay");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Event e = dataSnapshot1.getValue(Event.class);
list.add(e);
}
adapter = new MyAdapter(CominSoonActivity.this, list, CominSoonActivity.this);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CominSoonActivity.this, "Opps.... Something went wrong", Toast.LENGTH_SHORT).show();
}
});
//add back button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
//taking the user back to the previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent homeActivity = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(homeActivity);
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(int position) {
Uri uri = Uri.parse("http://wwww.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}

how to get the post key with position in Firebase Android

package com.novela.minha.novela;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<Beaches> beaches;
private long itemId;
private Firebase firebase;
Firebase likeRef;
FirebaseAuth user;
public com.firebase.client.Firebase Ref ;
private DatabaseReference Database = FirebaseDatabase.getInstance().getReference();
private DatabaseReference mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
private boolean mProcessLike = false;
public MyAdapter(Context c, ArrayList<Beaches> beaches){
this.c= c;
this.beaches=beaches;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
final MyHolder holder= new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final MyHolder holder, final int position) {
final String post_key = Database.getRef(position).getKey().toString(); // <- Error
mDatabaseLike.keepSynced(true);
holder.nameTxt.setText(beaches.get(position).getName());
holder.textoTxt.setText(beaches.get(position).getTexto());
holder.siteTxt.setText(beaches.get(position).getSite());
holder.emissoraTxt.setText(beaches.get(position).getEmissora());
holder.enderecoTxt.setText(beaches.get(position).getEndereco());
PicassoClient.downloadimg(c, beaches.get(position).getUrl(),holder.img);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String url = beaches.get(position).getEndereco().toString();
Intent intent = new Intent( v.getContext().getApplicationContext(), Web.class);
intent.putExtra("VALOR", url);
v.getContext().getApplicationContext().startActivity(intent);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
Toast.makeText(v.getContext(), post_key, Toast.LENGTH_SHORT).show();
mProcessLike = true ;
if (mProcessLike) {
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
#Override
public int getItemCount() {
return beaches.size();
}
}
Note that getRef does not accept position,
returns an error, which could be done in the code, I already searched here in the Forum but I did not find a solution, thank you ,Note that getRef does not accept position,
returns an error, which could be done in the code, I already searched here in the Forum
 but I did not find a solution, I'm new to programming, thank you
final String post_key = Database.push().getKey();

how to set event for grid view by imageview

I'm newbie and just study Java around 1 month.
i'm trying to create group picture by grid view and if i click any picture then show for user alert dialog ask user want to delete picture or not. But somehow when i try to set event for grid view by image. i can't start up app. can help me find where is crash cause app can't start up.
package com.example.hi.gridviewhinhanh;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Danhsachhinhanh> manghinhanh;
HinhanhAdapter arrayAdapter;
GridView gridView;
ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.gridview);
manghinhanh = new ArrayList<>();
manghinhanh.add(new Danhsachhinhanh(R.drawable.chupanh));
manghinhanh.add(new Danhsachhinhanh(R.drawable.goidien));
manghinhanh.add(new Danhsachhinhanh(R.drawable.photoshop));
manghinhanh.add(new Danhsachhinhanh(R.drawable.quality));
manghinhanh.add(new Danhsachhinhanh(R.drawable.secutiry));
manghinhanh.add(new Danhsachhinhanh(R.drawable.signuptoday));
arrayAdapter = new HinhanhAdapter(MainActivity.this, manghinhanh);
gridView.setAdapter(arrayAdapter);
imgView = findViewById(R.id.imageviewHinhanh);
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder hopthoai = new AlertDialog.Builder(MainActivity.this);
hopthoai.setTitle("Do you want to delete");
hopthoai.setMessage("Please confirm");
hopthoai.setIcon(R.mipmap.ic_launcher);
hopthoai.setCancelable(false);
hopthoai.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
hopthoai.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "You choose No", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
package com.example.hi.gridviewhinhanh;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class HinhanhAdapter extends BaseAdapter {
Context context;
ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList;
public HinhanhAdapter (Context context, ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList){
this.context = context;
this.danhsachhinhanhArrayList = danhsachhinhanhArrayList;
}
#Override
public int getCount() {
return danhsachhinhanhArrayList.size();
}
#Override
public Object getItem(int position) {
return danhsachhinhanhArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.dong_item_gridviewhinhanh,null);
ImageView imageView = convertView.findViewById(R.id.imageviewHinhanh);
Danhsachhinhanh danhsachhinhanh = (Danhsachhinhanh) getItem(position);
imageView.setImageResource(danhsachhinhanh.getHinhanh());
return convertView;
}
}
place you imageView clickListener in Adapter's getView() and check it again.
Becuase your imageView does not exist there. For more information read about adapter and recycleview.

Categories

Resources